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

(Install package: clbiwiki-boot-skip-preview-manager-save-20260708 / js/Common.js)
(Install package: clbiwiki-portal-section-fit-20260721-008 / js/Common.js)
 
(같은 사용자의 중간 판 89개는 보이지 않습니다)
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 || String(Date.now());
window.CLBI_RAW_LOAD_BUST = 'portal-frame-section-fit-20260721-008';


/*
/*
12번째 줄: 12번째 줄:
window.EntryScriptLoads = window.EntryScriptLoads || [];
window.EntryScriptLoads = window.EntryScriptLoads || [];
window.EntryRawScriptPromises = window.EntryRawScriptPromises || {};
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) {
function loadClbiRawScript(title) {
     var key = String(title || '').trim();
     var key = String(title || '').trim();
19번째 줄: 38번째 줄:
     if (window.EntryRawScriptPromises[key]) return window.EntryRawScriptPromises[key];
     if (window.EntryRawScriptPromises[key]) return window.EntryRawScriptPromises[key];


     promise = new Promise(function (resolve) {
     promise = Promise.resolve()
        var script = document.createElement('script');
        .then(function () {
        script.src = '/index.php?title=' + encodeURIComponent(key) + '&action=raw&ctype=text/javascript&v=' + encodeURIComponent(window.CLBI_RAW_LOAD_BUST);
            if (window.RevisionManifest && typeof window.RevisionManifest.ensureLoaded === 'function') {
        script.async = true;
                return window.RevisionManifest.ensureLoaded();
        script.setAttribute('data-entry-raw-script', key);
            }
        script.onload = function () { resolve({ title: key, ok: true }); };
            return null;
        script.onerror = function () { resolve({ title: key, ok: false }); };
        })
        (document.head || document.documentElement).appendChild(script);
        .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.EntryRawScriptPromises[key] = promise;
36번째 줄: 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) {
        * Developer/system pages must stay practical.  Editing MediaWiki:, File:,
                if (settled) return;
        * Project:, Template:, Module:, Category:, or any non-view action already forces
                settled = true;
        * a full page load in MediaWiki, so showing the entry boot screen there only slows
                window.clearTimeout(timeout);
        * maintenance work and does not improve the public first impression.
                resolve(ok);
        */
            }
        if (hasQueryFlag('bootGatePreview', '1')) return false;
 
        if (action && action !== 'view') return true;
            link.rel = 'stylesheet';
        if (systemNamespaces[String(ns)]) return true;
            link.href = rawUrl('MediaWiki:MainPage.css', 'style');
        if (model === 'css' || model === 'javascript' || model === 'json' || model === 'sanitized-css') return true;
            link.setAttribute('data-main-page-fresh-style', sessionToken);
        if (/\.(?:css|js|json)$/i.test(name)) return true;
            link.onload = function () {
        if (/^(?:mediawiki|미디어위키|file|파일|project|프로젝트|template|틀|module|모듈|category|분류|special|특수):/i.test(name)) return true;
                styleNode = link;
         return false;
                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);
         });
     }
     }


     var disabled = hasQueryFlag('bootGate', '0') || isDeveloperOrEditingPage();
     function loadScript(title) {
        var key = String(title || '').trim();


    function injectStyle() {
         if (!key || !isMainPage()) return Promise.resolve(false);
        var style;
         if (scriptPromises[key]) return scriptPromises[key];
         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;overflow:hidden!important;font-family:inherit!important;}',
            '#boot-gate-screen:before{content:"";position:absolute;inset:0;background:radial-gradient(circle at 72% 18%,rgba(255,255,255,.045),transparent 28%),linear-gradient(135deg,rgba(255,255,255,.032) 0,transparent 24%,transparent 100%);opacity:.9;}',
            '#boot-gate-screen:after{content:"";position:absolute;inset:10px;border:1px solid #000;box-shadow:inset 1px 1px 0 #1f1f1f,inset -1px -1px 0 #050505;pointer-events:none;}',
            '#boot-gate-screen .boot-gate-panel{position:relative;z-index:2;width:min(520px,calc(100vw - 56px));background:#111;border:1px solid #000;box-shadow:inset 1px 1px 0 #242424,inset -1px -1px 0 #050505,0 14px 40px rgba(0,0,0,.45);padding:3px;}',
            '#boot-gate-screen .boot-gate-title{height:27px;display:flex;align-items:center;padding:0 9px;background:#1d1d1d;color:#e6e6e6;font-size:11px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;border-bottom:1px solid #000;box-shadow:inset 0 1px 0 #2a2a2a;}',
            '#boot-gate-screen .boot-gate-status{padding:12px 10px 7px;color:#cfcfcf;font-size:12px;}',
            '#boot-gate-screen .boot-gate-meter{height:12px;margin:0 10px;background:#070707;border:1px solid #000;box-shadow:inset 1px 1px 0 #020202,inset -1px -1px 0 #1a1a1a;overflow:hidden;}',
            '#boot-gate-screen .boot-gate-meter-fill{height:100%;width:0;background:linear-gradient(90deg,#3a3a3a,#d8d8d8);box-shadow:0 0 12px rgba(255,255,255,.16);transition:width .18s ease-out;}',
            '#boot-gate-screen .boot-gate-progress{padding:6px 10px 0;color:#f2f2f2;font-size:18px;font-weight:800;text-align:right;line-height:1;}',
            '#boot-gate-screen .boot-gate-detail{padding:3px 10px 11px;color:#858585;font-size:10px;letter-spacing:.03em;text-align:right;min-height:14px;}',
            '#boot-gate-screen .boot-gate-decoration-layer{position:absolute;inset:0;z-index:1;pointer-events:none;overflow:hidden;}',
            '#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 .boot-gate-close{display:block;}',
            '#boot-gate-screen.is-preview .boot-gate-title{padding-right:42px;}'
        ].join('');
        (document.head || document.documentElement).appendChild(style);
    }


    function activate() {
        scriptPromises[key] = new Promise(function (resolve) {
        if (disabled) return;
            var script = document.createElement('script');
        injectStyle();
            var settled = false;
        if (document.documentElement) document.documentElement.classList.add('boot-gate-active');
            var timeout = 0;
        if (document.body) document.body.classList.add('boot-gate-active');
    }


    function makeNode() {
            function settle(ok) {
        var node;
                if (settled) return;
        var panel;
                settled = true;
        var title;
                window.clearTimeout(timeout);
        var status;
                resolve(ok);
        var meter;
            }
        var fill;
        var progress;
        var detail;
        var decoLayer;
        var close;


        if (disabled || !document.body) return null;
            script.src = rawUrl(key, 'script');
         activate();
            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);
         });


         node = document.getElementById(SCREEN_ID);
         return scriptPromises[key];
        if (node) return node;
    }


        node = document.createElement('div');
    function validatePortalFrameSet() {
         node.id = SCREEN_ID;
         var modules = [
        node.className = 'boot-gate-screen is-active';
            ['PortalFrame', window.PortalFrame],
        node.setAttribute('role', 'status');
            ['CategoryNav', window.CategoryNav],
        node.setAttribute('aria-live', 'polite');
            ['CategoryPillar', window.CategoryPillar],
         node.setAttribute('data-boot-gate-prelude', '1');
            ['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;
        });


         panel = document.createElement('div');
         document.documentElement.toggleAttribute(
         panel.className = 'boot-gate-panel';
            'data-portal-frame-build-mismatch',
            mismatches.length > 0
        );
         document.documentElement.setAttribute('data-portal-frame-build', PORTAL_FRAME_BUILD);


         title = document.createElement('div');
         if (mismatches.length && window.console && typeof window.console.error === 'function') {
        title.className = 'boot-gate-title';
            window.console.error(
         title.textContent = 'ARCHIVE INITIALIZATION';
                '[PortalFrame] 원자적 배포 세트의 버전이 일치하지 않습니다:',
                mismatches.map(function (entry) { return entry[0]; }).join(', ')
            );
         }
        return mismatches.length === 0;
    }


        status = document.createElement('div');
    function ensure() {
         status.className = 'boot-gate-status';
         if (!isMainPage()) return Promise.resolve(false);
        status.textContent = 'Preparing site entry systems';


         meter = document.createElement('div');
         return loadStyle()
        meter.className = 'boot-gate-meter';
            .then(function () {
        fill = document.createElement('div');
                return loadScript('MediaWiki:CategoryNav.js');
        fill.className = 'boot-gate-meter-fill';
            })
        meter.appendChild(fill);
            .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;
            });
    }


         progress = document.createElement('div');
    function status() {
        progress.className = 'boot-gate-progress';
         return {
        progress.textContent = '0%';
            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()
        };
    }


         detail = document.createElement('div');
    if (mw && mw.hook) {
         detail.className = 'boot-gate-detail';
         mw.hook('wikipage.content').add(function () {
        detail.textContent = 'boot gate prelude';
            ensure();
         });
    }


        close = document.createElement('button');
    window.setTimeout(ensure, 0);
        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');
    return {
         decoLayer.className = 'boot-gate-decoration-layer';
         ensure: ensure,
        decoLayer.setAttribute('data-decoration-target', 'boot-gate');
         status: status
        decoLayer.setAttribute('aria-hidden', 'true');
    };
}(window, document, window.mw));


        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;
  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';


     function onBody(callback) {
    var canonical = '';
         if (document.body) {
    var pageName = '';
            callback();
    var isLoginPage = false;
            return;
 
         }
    try {
         if (document.readyState === 'loading') {
        canonical = String(window.mw && mw.config ? mw.config.get('wgCanonicalSpecialPageName') || '' : '').toLowerCase();
             document.addEventListener('DOMContentLoaded', callback, { once: true });
        pageName = String(window.mw && mw.config ? mw.config.get('wgPageName') || '' : '').replace(/_/g, ' ').toLowerCase();
         }
    } catch (err) {}
         window.setTimeout(function tick() {
 
             if (document.body) return callback();
    isLoginPage = canonical === 'userlogin' || /^(?:special|특수):(?:userlogin|로그인)$/.test(pageName);
             window.setTimeout(tick, 10);
    if (!isLoginPage) return;
         }, 0);
 
    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 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
    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 changesIf 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) {
(function installBootGatePrelude(window, document) {
     'use strict';
     'use strict';


     var MANIFEST_TITLE = 'MediaWiki:EntryManifest.json';
     var SCREEN_ID = 'boot-gate-screen';
    var BUILD_ID = '20260708-boot-skip-preview-and-manager-save-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 || '');
310번째 줄: 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;
             }
             }
320번째 줄: 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,
336번째 줄: 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;
349번째 줄: 428번째 줄:
     }
     }


     var BOOT_EXCLUDED_PAGE = isBootExcludedPage();
    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 injectEarlyBootStyle() {
     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;


    var defaultManifest = {
        node = document.createElement('div');
         version: '20260708-boot-skip-preview-and-manager-save-001',
         node.id = SCREEN_ID;
         boot: {
        node.className = 'boot-gate-screen is-active';
            minDisplayMs: 950,
         node.setAttribute('role', 'status');
            cachedMinDisplayMs: 350,
        node.setAttribute('aria-live', 'polite');
            maxBlockingMs: 15000
        node.setAttribute('data-boot-gate-prelude', '1');
        },
        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() {
        panel = document.createElement('div');
         return Date.now ? Date.now() : new Date().getTime();
         panel.className = 'boot-gate-panel';
    }


    function toArray(value) {
        title = document.createElement('div');
         return Array.prototype.slice.call(value || []);
         title.className = 'boot-gate-title';
    }
        title.textContent = 'ARCHIVE INITIALIZATION';


    function unique(list) {
        status = document.createElement('div');
        var seen = {};
         status.className = 'boot-gate-status';
         var out = [];
         status.textContent = 'Preparing site entry systems';
         (list || []).forEach(function (item) {
            item = String(item || '').trim();
            if (!item || seen[item]) return;
            seen[item] = true;
            out.push(item);
        });
        return out;
    }


    function hasBootParam(value) {
         meter = document.createElement('div');
         var search = String(window.location && window.location.search || '');
         meter.className = 'boot-gate-meter';
         var re = new RegExp('[?&]' + DISMISS_PARAM + '=([^&]+)');
        fill = document.createElement('div');
         var match = search.match(re);
         fill.className = 'boot-gate-meter-fill';
         return match && decodeURIComponent(match[1]) === value;
         meter.appendChild(fill);
    }


    function normalizeTitle(value) {
        progress = document.createElement('div');
         return String(value || '')
         progress.className = 'boot-gate-progress';
            .split('#')[0]
        progress.textContent = '0%';
            .replace(/_/g, ' ')
 
            .trim();
        detail = document.createElement('div');
    }
        detail.className = 'boot-gate-detail';
        detail.textContent = 'boot gate prelude';


    function extractTitleFromUrl(value) {
        close = document.createElement('button');
         var text = String(value || '');
         close.type = 'button';
         var match = text.match(/[?&]title=([^&]+)/i);
         close.className = 'boot-gate-close';
         if (match) return normalizeTitle(decodeURIComponent(match[1].replace(/\+/g, ' ')));
         close.setAttribute('aria-label', 'Close boot preview');
         return '';
         close.textContent = '×';
    }
        close.addEventListener('click', function () { release(node); });


    function normalizeRefKey(ref) {
         decoLayer = document.createElement('div');
         var text = String(ref || '').trim();
         decoLayer.className = 'boot-gate-decoration-layer';
         var title;
         decoLayer.setAttribute('data-decoration-target', 'boot-gate');
         if (!text) return '';
         decoLayer.setAttribute('aria-hidden', 'true');
        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) {
        panel.appendChild(title);
         var text = String(ref || '').trim();
         panel.appendChild(status);
         var title;
         panel.appendChild(meter);
         if (!text) return '';
         panel.appendChild(progress);
         if (/^(?:https?:)?\/\//i.test(text) || text.charAt(0) === '/') return text;
         panel.appendChild(detail);
         title = normalizeTitle(text.indexOf(':') !== -1 ? text : ('MediaWiki:' + text));
         node.appendChild(decoLayer);
         if (mw && mw.util && typeof mw.util.getUrl === 'function') {
         node.appendChild(panel);
            return mw.util.getUrl(title, { action: 'raw', ctype: ctype || 'application/json' });
         node.appendChild(close);
         }
        return '/index.php?title=' + encodeURIComponent(title) + '&action=raw&ctype=' + encodeURIComponent(ctype || 'application/json');
    }


    function getApiEndpoint() {
         document.body.insertBefore(node, document.body.firstChild || null);
         return (mw && mw.util && typeof mw.util.wikiScript === 'function') ? mw.util.wikiScript('api') : '/api.php';
        return node;
     }
     }


     function fetchApi(params) {
     function onBody(callback) {
         var body = new URLSearchParams();
         if (document.body) {
        Object.keys(params || {}).forEach(function (key) {
             callback();
             body.append(key, params[key]);
            return;
         });
         }
         return fetch(getApiEndpoint(), {
         if (document.readyState === 'loading') {
             method: 'POST',
             document.addEventListener('DOMContentLoaded', callback, { once: true });
            credentials: 'same-origin',
         }
            headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
        window.setTimeout(function tick() {
            body: body.toString()
             if (document.body) return callback();
         }).then(function (res) {
             window.setTimeout(tick, 10);
             if (!res.ok) throw new Error('HTTP ' + res.status);
         }, 0);
             return res.json();
         });
     }
     }


 
     function release(node) {
     /* =========================================
        node = node || document.getElementById(SCREEN_ID);
      Revision manifest and persistent entry cache
        if (node) {
      =========================================
            node.classList.add('is-complete');
      The first boot still prepares current-tab artifacts, but freshness is not guessed from
            node.classList.remove('is-active');
      filenames or old localStorage flags. The client reads a tiny server-side current-state
            window.setTimeout(function () {
      manifest, compares page revisions / file sha1 values, and only keeps cached raw resources
                if (node.parentNode) node.parentNode.removeChild(node);
      whose revision token still matches the server. The manifest is a latest-state table, not
            }, 240);
      an append-only client log.
        }
    */
        window.setTimeout(function () {
    var REVISION_MANIFEST_ACTION = 'entryrevisionmanifest';
            if (document.documentElement) document.documentElement.classList.remove('boot-gate-active');
    var REVISION_MANIFEST_LOCAL_KEY = 'entry-revision-manifest-current-v1';
            if (document.body) document.body.classList.remove('boot-gate-active');
    var REVISION_MANIFEST_PRUNE_LOCAL_KEY = 'entry-revision-manifest-last-client-prune-v1';
        }, 250);
    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) {
     activate();
         try { return JSON.parse(text); } catch (err) { return fallback; }
    onBody(function () {
     }
         activate();
        makeNode();
     });


     function readLocalJson(key, fallback) {
     window.__BootGatePrelude = {
        try {
        startTime: START_TIME,
            var text = window.localStorage ? window.localStorage.getItem(key) : null;
        activate: activate,
            return text ? safeJsonParse(text, fallback) : fallback;
        ensure: makeNode,
         } catch (err) {
        release: release,
            return fallback;
        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 writeLocalJson(key, value) {
     function readConfig(name, fallback) {
         try {
         try {
             if (window.localStorage) window.localStorage.setItem(key, JSON.stringify(value));
             if (mw && mw.config && typeof mw.config.get === 'function') {
                var value = mw.config.get(name);
                return value == null ? fallback : value;
            }
         } catch (err) {}
         } catch (err) {}
        return fallback;
     }
     }


     function normalizeManifestTitle(value) {
     function normalizeBootPageName(value) {
         var text = String(value || '').trim();
         return String(value || '').split('?')[0].replace(/^\/index\.php\//, '').replace(/_/g, ' ').trim();
        var match;
    }
        var i;
 
        if (!text) return '';
    function isCreateAccountPage() {
        for (i = 0; i < 3; i += 1) {
         var canonical = String(readConfig('wgCanonicalSpecialPageName', '') || '').toLowerCase();
            try {
         var name = normalizeBootPageName(readConfig('wgPageName', '') || window.location.pathname || '').toLowerCase();
                if (/%[0-9a-f]{2}/i.test(text)) text = decodeURIComponent(text);
        return canonical === 'createaccount' || /^(?:special|특수):(?:createaccount|계정 ?(?:만들기|생성))/i.test(name);
            } 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) {
     function isAnonymousUser() {
         if (!resource || typeof resource !== 'object') return '';
         var userName = readConfig('wgUserName', null);
         return String(resource.revision || resource.sha1 || resource.hash || resource.timestamp || resource.updatedAt || resource.url || '').trim();
         var userId = Number(readConfig('wgUserId', 0) || 0);
        return !userName && !userId;
     }
     }


     function createEntryCache() {
     function isAuthenticationPage() {
         var index = readLocalJson(ENTRY_CACHE_INDEX_KEY, { entries: {} }) || { entries: {} };
         var canonical = String(readConfig('wgCanonicalSpecialPageName', '') || '').toLowerCase();
         var packs = readLocalJson(ENTRY_CACHE_PACK_KEY, { packs: {} }) || { packs: {} };
         var name = normalizeBootPageName(readConfig('wgPageName', '') || window.location.pathname || '').toLowerCase();
        var objectUrls = {};
         var allowed = {
         var stats = {
             userlogin: true,
             textHits: 0,
             passwordreset: true,
            blobHits: 0,
             resetpass: true,
            misses: 0,
             confirmemail: true
             networkStores: 0,
             stores: 0,
             deletes: 0
         };
         };


         function ensureIndex() {
         if (allowed[canonical]) return true;
            if (!index || typeof index !== 'object') index = { entries: {} };
        return /^(?:special|특수):(?:userlogin|로그인|passwordreset|비밀번호 ?재설정|resetpass|confirmemail)/i.test(name);
            if (!index.entries || typeof index.entries !== 'object') index.entries = {};
    }
        }


        function ensurePacks() {
    function requiresLoginGate() {
            if (!packs || typeof packs !== 'object') packs = { packs: {} };
        return isAnonymousUser() && !isAuthenticationPage();
            if (!packs.packs || typeof packs.packs !== 'object') packs.packs = {};
    }
        }


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


         function requestForKey(key) {
         /*
            return new Request(ENTRY_CACHE_REQUEST_PREFIX + encodeURIComponent(String(key || '')), { credentials: 'same-origin' });
        * 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;
    }


        function openCache() {
    var LOGIN_REQUIRED = requiresLoginGate();
            if (!hasCacheStorage()) return Promise.resolve(null);
    var BOOT_EXCLUDED_PAGE = isBootExcludedPage() && !LOGIN_REQUIRED;
            return window.caches.open(ENTRY_CACHE_NAME).catch(function () { return null; });
        }


        function cacheEntry(key, meta) {
    function injectEarlyBootStyle() {
            key = String(key || '');
        var style;
            ensureIndex();
        if (earlyBootStyleInjected || !document.documentElement) return;
            index.entries[key] = Object.assign({}, index.entries[key] || {}, {
        earlyBootStyleInjected = true;
                key: key,
        style = document.createElement('style');
                resourceKey: String(meta && meta.resourceKey || ''),
        style.id = 'boot-gate-early-style';
                token: String(meta && meta.token || ''),
        style.textContent = [
                kind: String(meta && meta.kind || 'raw'),
            'html.boot-gate-active, body.boot-gate-active{overflow:hidden!important;}',
                contentType: String(meta && meta.contentType || ''),
            'html.boot-gate-active body{background:#080808!important;}',
                size: Number(meta && meta.size || 0) || null,
            'html.boot-gate-active body> :not(#boot-gate-screen){visibility:hidden!important;pointer-events:none!important;}',
                createdAt: index.entries[key] && index.entries[key].createdAt ? index.entries[key].createdAt : now(),
            'html.boot-gate-active #boot-gate-screen,html.boot-gate-active #boot-gate-screen *{visibility:visible!important;}'
                updatedAt: now(),
        ].join('');
                lastHitAt: index.entries[key] && index.entries[key].lastHitAt ? index.entries[key].lastHitAt : null,
        (document.head || document.documentElement).appendChild(style);
                hits: Number(index.entries[key] && index.entries[key].hits || 0)
    }
            });
            saveIndex();
        }


        function markHit(key, field) {
    function activateBootSurface() {
            key = String(key || '');
        injectEarlyBootStyle();
            ensureIndex();
        if (document.documentElement) document.documentElement.classList.add('boot-gate-active');
            if (index.entries[key]) {
        if (document.body) document.body.classList.add('boot-gate-active');
                index.entries[key].hits = Number(index.entries[key].hits || 0) + 1;
    }
                index.entries[key].lastHitAt = now();
 
                saveIndex();
    if (!BOOT_EXCLUDED_PAGE) activateBootSurface();
             }
    else if (window.__BootGatePrelude && window.__BootGatePrelude.release) window.__BootGatePrelude.release();
             if (field && stats[field] != null) stats[field] += 1;
 
    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();
    }


        function getResponse(key) {
    var BootPerf = window.BootPerf = window.BootPerf || (function () {
            key = String(key || '');
        var t0 = now();
            if (!key || !hasCacheStorage()) return Promise.resolve(null);
        var entries = [];
             return openCache().then(function (cache) {
        var active = {};
                 if (!cache) return null;
        var seq = 0;
                 return cache.match(requestForKey(key)).then(function (res) {
 
                     if (!res) {
        function cloneMeta(meta) {
                        stats.misses += 1;
            var out = {};
                        return null;
             Object.keys(meta || {}).forEach(function (key) {
                    }
                var value = meta[key];
                    return res;
                 if (value == null) return;
                });
                 if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') out[key] = value;
             }).catch(function () { return null; });
                else {
                    try { out[key] = JSON.parse(JSON.stringify(value)); }
                     catch (err) { out[key] = String(value); }
                }
            });
             return out;
         }
         }


         function putResponse(key, response, meta) {
         function start(name, meta) {
             key = String(key || '');
             var id = String(++seq);
             if (!key || !response || !hasCacheStorage()) return Promise.resolve(false);
             active[id] = { id: id, name: String(name || 'entry'), start: now(), meta: cloneMeta(meta) };
            meta = meta || {};
             return id;
            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) {
         function end(id, meta) {
             return getResponse(key).then(function (res) {
             var item = active[id];
                if (!res) return null;
            var ended = now();
                markHit(key, 'textHits');
            if (!item) return null;
                return res.text();
            delete active[id];
             }).catch(function () { return null; });
            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 putText(key, text, meta) {
         function instant(name, meta) {
             key = String(key || '');
             var t = now();
             if (!key || !hasCacheStorage()) return Promise.resolve(false);
             entries.push({ id: String(++seq), name: String(name || 'mark'), start: t, end: t, ms: 0, offset: t - t0, meta: cloneMeta(meta) });
            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) {
         function measure(name, meta, fn) {
             key = String(key || '');
             var id = start(name, meta);
             if (!key) return Promise.resolve('');
             try {
             if (objectUrls[key]) {
                return Promise.resolve(fn()).then(function (value) {
                 markHit(key, 'blobHits');
                    end(id, { ok: true });
                 return Promise.resolve(objectUrls[key]);
                    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);
             }
             }
            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 rows() {
             url = String(url || '').trim();
             return entries.slice().sort(function (a, b) { return a.start - b.start; }).map(function (item) {
            key = String(key || '').trim();
                 return {
            if (!url || !key) return Promise.resolve('');
                     offset: item.offset,
            return getBlobUrl(key).then(function (cachedUrl) {
                     ms: item.ms,
                 if (cachedUrl) return cachedUrl;
                     name: item.name,
                return fetch(url, {
                     meta: item.meta || {}
                     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: 'blob' })).then(function () {
                        return getBlobUrl(key);
                    });
                 }).catch(function () {
                    return '';
                });
             });
             });
         }
         }


         function deleteKey(key) {
         function summary() {
             key = String(key || '');
             var list = rows();
             if (!key || !hasCacheStorage()) return Promise.resolve(false);
             var total = list.reduce(function (max, item) { return Math.max(max, item.offset + item.ms); }, 0);
             if (objectUrls[key]) {
             return {
                 try { URL.revokeObjectURL(objectUrls[key]); } catch (err) {}
                 build: BUILD_ID,
                delete objectUrls[key];
                startedAt: t0,
             }
                totalMs: total,
            return openCache().then(function (cache) {
                entries: list,
                if (!cache) return false;
                active: Object.keys(active).map(function (id) { return active[id]; })
                 return cache.delete(requestForKey(key)).then(function (ok) {
             };
                     ensureIndex();
        }
                    if (index.entries && index.entries[key]) {
 
                         delete index.entries[key];
        function print() {
                         stats.deletes += 1;
            var list = rows();
                         saveIndex();
            if (!window.console || !console.log) return summary();
                     }
            try {
                    return ok;
                 console.groupCollapsed('[BootPerf] entry loading timeline · ' + BUILD_ID);
                 });
                if (console.table) console.table(list.map(function (item) {
             }).catch(function () { return false; });
                     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();
         }
         }


         function invalidateResources(resourceKeys) {
         return {
             var map = {};
             start: start,
             var entries;
            end: end,
             var keys = [];
            mark: instant,
             ensureIndex();
             measure: measure,
             entries = index.entries || {};
             rows: rows,
            (resourceKeys || []).forEach(function (resourceKey) {
             summary: summary,
                resourceKey = String(resourceKey || '').toLowerCase();
             print: print
                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);
    var InteractionPerf = window.InteractionPerf = window.InteractionPerf || (function () {
            });
        var BUILD = '20260710-interaction-perf-instrument-001';
             return Promise.all(keys.map(deleteKey)).then(function () { return keys.length; });
        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 prune(maxAgeDays) {
         function cloneMeta(meta) {
             var days = Math.max(1, Number(maxAgeDays) || 7);
             var out = {};
            var cutoff = now() - days * 24 * 60 * 60 * 1000;
            Object.keys(meta || {}).forEach(function (key) {
            var entries;
                var value = meta[key];
            var keys;
                if (value == null) return;
            ensureIndex();
                if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') out[key] = value;
            entries = index.entries || {};
                else {
            keys = Object.keys(entries).filter(function (key) {
                    try { out[key] = JSON.parse(JSON.stringify(value)); }
                return Number(entries[key] && entries[key].createdAt || 0) < cutoff;
                    catch (err) { out[key] = String(value); }
                }
             });
             });
            window.localStorage && window.localStorage.setItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY, String(now()));
             return out;
             return Promise.all(keys.map(deleteKey)).then(function () { return keys.length; });
         }
         }


         function reset() {
         function push(entry) {
             Object.keys(objectUrls).forEach(function (key) {
             entries.push(entry);
                try { URL.revokeObjectURL(objectUrls[key]); } catch (err) {}
             if (entries.length > maxEntries) entries.splice(0, entries.length - maxEntries);
            });
             return entry;
            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) {
         function start(name, meta) {
             key = String(key || '');
             var id = String(++seq);
             token = String(token || '');
             active[id] = { id: id, name: String(name || 'interaction'), start: perfNow(), meta: cloneMeta(meta) };
            ensurePacks();
             return id;
            if (!key || !token) return false;
             return !!(packs.packs[key] && String(packs.packs[key].token || '') === token && packs.packs[key].ready);
         }
         }


         function setPackReady(key, token, meta) {
         function end(id, meta) {
             key = String(key || '');
             var item = active[id];
             token = String(token || '');
             var ended = perfNow();
             if (!key || !token) return false;
             if (!item) return null;
             ensurePacks();
            delete active[id];
             packs.packs[key] = Object.assign({}, meta || {}, {
            item.end = ended;
                key: key,
            item.ms = Math.round((ended - item.start) * 100) / 100;
                token: token,
             item.offset = Math.round((item.start - t0) * 100) / 100;
                ready: true,
             item.meta = Object.assign({}, item.meta || {}, cloneMeta(meta));
                updatedAt: now()
             return push(item);
            });
             savePacks();
            return true;
         }
         }


         function packInfo() {
         function mark(name, meta) {
             ensurePacks();
             var t = perfNow();
             return Object.assign({}, packs.packs || {});
             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 info() {
         function measureSync(name, meta, fn) {
             var lastClientPrune = 0;
             var id = start(name, meta);
            var entries;
             try {
            var byKind = {};
                 var value = fn();
            try { lastClientPrune = Number(window.localStorage && window.localStorage.getItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY) || 0); } catch (err) {}
                 end(id, { ok: true });
            ensureIndex();
                return value;
             ensurePacks();
             } catch (err) {
            entries = index.entries || {};
                 end(id, { ok: false, error: err && (err.message || String(err)) || String(err) });
            Object.keys(entries).forEach(function (key) {
                throw err;
                 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)
             };
         }
         }


         return {
         function measureAsync(name, meta, fn) {
            getResponse: getResponse,
             var id = start(name, meta);
            putResponse: putResponse,
             try {
             getText: getText,
                return Promise.resolve(fn()).then(function (value) {
             putText: putText,
                    end(id, { ok: true });
            getBlobUrl: getBlobUrl,
                    return value;
            fetchBlobUrl: fetchBlobUrl,
                }, function (err) {
            invalidateResources: invalidateResources,
                    end(id, { ok: false, error: err && (err.message || String(err)) || String(err) });
            prune: prune,
                    throw err;
            reset: reset,
                });
            packReady: packReady,
            } catch (err) {
            setPackReady: setPackReady,
                end(id, { ok: false, error: err && (err.message || String(err)) || String(err) });
            packInfo: packInfo,
                return Promise.reject(err);
            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) {
         function summary() {
             return manifest && manifest.resources && typeof manifest.resources === 'object' ? manifest.resources : {};
             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 buildLookup(manifest) {
         function table() {
             var lookup = {};
             var data = summary().entries.map(function (entry) {
            Object.keys(resourcesOf(manifest)).forEach(function (title) {
                 return { offset: entry.offset, ms: entry.ms, name: entry.name, meta: entry.meta };
                 lookup[normalizeManifestTitle(title).toLowerCase()] = resourcesOf(manifest)[title];
             });
             });
             return lookup;
            if (window.console && console.table) console.table(data);
             return data;
         }
         }


         function computeChanged(prev, next) {
         try {
            var prevLookup = buildLookup(prev);
            if (window.PerformanceObserver && !window.CLBI_InteractionLongTaskObserverBound) {
            var nextLookup = buildLookup(next);
                window.CLBI_InteractionLongTaskObserverBound = true;
            var out = [];
                new PerformanceObserver(function (list) {
            Object.keys(nextLookup).forEach(function (key) {
                    list.getEntries().forEach(function (entry) {
                if (resourceToken(prevLookup[key]) !== resourceToken(nextLookup[key])) out.push(key);
                        mark('browser long task', {
            });
                            ms: Math.round(entry.duration * 100) / 100,
            Object.keys(prevLookup).forEach(function (key) {
                            start: Math.round(entry.startTime * 100) / 100,
                if (!nextLookup[key]) out.push(key);
                            attribution: entry.attribution && entry.attribution.length ? entry.attribution.length : 0
             });
                        });
            return unique(out);
                    });
        }
                }).observe({ entryTypes: ['longtask'] });
            }
        } catch (ignoreLongTaskObserver) {}
 
        return {
            build: BUILD,
            start: start,
            end: end,
            mark: mark,
            measureSync: measureSync,
            measureAsync: measureAsync,
            summary: summary,
             table: table
        };
    }());


        function load(options) {
    function toArray(value) {
            if (loadPromise && !(options && options.force)) return loadPromise;
        return Array.prototype.slice.call(value || []);
            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 = 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() {
    function unique(list) {
             return current ? Promise.resolve(current) : load();
        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 resourceForRef(ref) {
    function hasBootParam(value) {
            var title = normalizeManifestTitle(ref);
        var search = String(window.location && window.location.search || '');
            var lookup;
        var re = new RegExp('[?&]' + DISMISS_PARAM + '=([^&]+)');
            if (!title || !current) return null;
        var match = search.match(re);
            lookup = buildLookup(current);
        return match && decodeURIComponent(match[1]) === value;
            return lookup[title.toLowerCase()] || null;
    }
        }


        function tokenForRef(ref) {
    function normalizeTitle(value) {
             return resourceToken(resourceForRef(ref));
        return String(value || '')
        }
             .split('#')[0]
            .replace(/_/g, ' ')
            .trim();
    }


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


        function cacheKeyForRef(ref, type) {
    function normalizeRefKey(ref) {
            var resourceKey = resourceKeyForRef(ref);
        var text = String(ref || '').trim();
            var token = tokenForRef(ref);
        var title;
            if (!resourceKey || !token) return '';
        if (!text) return '';
            return String(type || 'raw') + ':' + resourceKey + '@' + token;
        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 manifestToken(extra) {
    function rawUrlForRef(ref, ctype) {
            var base = current && (current.manifestVersion || current.version || current.generatedAt || '') || '';
        var text = String(ref || '').trim();
            return String(base || 'no-manifest') + (extra ? (':' + String(extra)) : '');
        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 tokenFromUrl(url) {
    function getApiEndpoint() {
            var text = String(url || '');
        return (mw && mw.util && typeof mw.util.wikiScript === 'function') ? mw.util.wikiScript('api') : '/api.php';
            var match = text.match(/[?&](?:_entryFileRev|_entryAsset|_entryRev)=([^&]+)/);
    }
            if (!match) return '';
            try { return decodeURIComponent(match[1]); } catch (err) { return match[1]; }
        }


        function cacheKeyForUrl(url, type) {
    function fetchApi(params) {
            var text = String(url || '').trim();
        var body = new URLSearchParams();
             var token = tokenFromUrl(text) || manifestToken('url');
        Object.keys(params || {}).forEach(function (key) {
             var normalized;
             body.append(key, params[key]);
             if (!text) return '';
        });
             try {
        return fetch(getApiEndpoint(), {
                normalized = new URL(text, window.location.href);
            method: 'POST',
                text = normalized.pathname + (normalized.search || '');
             credentials: 'same-origin',
            } catch (err) {}
             headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
            text = text.replace(/[?&](?:_entryFileRev|_entryAsset|_entryRev)=[^&]*/g, '').replace(/[?&]$/, '');
             body: body.toString()
            try { text = decodeURI(text); } catch (err2) {}
        }).then(function (res) {
            return String(type || 'blob') + ':url:' + text.toLowerCase() + '@' + token;
            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 addRevisionParam(url, ref) {
    function safeJsonParse(text, fallback) {
            var token = tokenForRef(ref);
        try { return JSON.parse(text); } catch (err) { return fallback; }
            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() {
    function readLocalJson(key, fallback) {
            var days = current && Number(current.pruneDays || current.clientPruneDays) || 7;
        try {
             var last = 0;
             var text = window.localStorage ? window.localStorage.getItem(key) : null;
            var due;
             return text ? safeJsonParse(text, fallback) : fallback;
            try { last = Number(window.localStorage && window.localStorage.getItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY) || 0); } catch (err) {}
        } catch (err) {
             due = !last || (now() - last >= days * 24 * 60 * 60 * 1000);
            return fallback;
            if (due && window.EntryCache && typeof window.EntryCache.prune === 'function') {
                window.EntryCache.prune(days);
            }
         }
         }
    }


        function countdown() {
    function writeLocalJson(key, value) {
            var days = current && Number(current.pruneDays || current.clientPruneDays) || 7;
        try {
             var last = 0;
             if (window.localStorage) window.localStorage.setItem(key, JSON.stringify(value));
            var next;
        } catch (err) {}
            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 };
    function normalizeManifestTitle(value) {
            next = last + days * 24 * 60 * 60 * 1000;
        var text = String(value || '').trim();
            remain = Math.max(0, next - now());
        var match;
             return {
        var i;
                 days: days,
        if (!text) return '';
                lastClientPruneAt: last,
        for (i = 0; i < 3; i += 1) {
                nextClientPruneAt: next,
             try {
                remainingMs: remain,
                 if (/%[0-9a-f]{2}/i.test(text)) text = decodeURIComponent(text);
                remainingDays: Math.ceil(remain / (24 * 60 * 60 * 1000)),
             } catch (err) { break; }
                due: remain <= 0
             };
         }
         }
 
        match = text.match(/[?&]title=([^&#]+)/i);
         function status() {
         if (match) text = match[1];
            return {
        text = text.replace(/^https?:\/\/[^/]+/i, '')
                available: !!current,
            .replace(/^\/+/, '')
                manifestVersion: current && (current.manifestVersion || current.version || ''),
            .replace(/^index\.php\/?/i, '')
                generatedAt: current && current.generatedAt || '',
            .replace(/^wiki\/?/i, '')
                changedResources: changedResources.slice(0, 50),
            .trim();
                changedCount: changedResources.length,
        match = text.match(/(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\/([^?#]+)(?:[?#].*)?$/i);
                prune: countdown(),
        if (match) text = 'File:' + match[1];
                cache: window.EntryCache && typeof window.EntryCache.info === 'function' ? window.EntryCache.info() : null
        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;
    }


         return {
    function resourceToken(resource) {
            load: load,
         if (!resource || typeof resource !== 'object') return '';
            ensureLoaded: ensureLoaded,
        return String(resource.revision || resource.sha1 || resource.hash || resource.timestamp || resource.updatedAt || resource.url || '').trim();
            current: function () { return current; },
    }
            resourceForRef: resourceForRef,
 
            tokenForRef: tokenForRef,
    function createEntryCache() {
            cacheKeyForRef: cacheKeyForRef,
        var index = readLocalJson(ENTRY_CACHE_INDEX_KEY, { entries: {} }) || { entries: {} };
            cacheKeyForUrl: cacheKeyForUrl,
        var packs = readLocalJson(ENTRY_CACHE_PACK_KEY, { packs: {} }) || { packs: {} };
             manifestToken: manifestToken,
        var objectUrls = {};
             resourceKeyForRef: resourceKeyForRef,
        var stats = {
             addRevisionParam: addRevisionParam,
             textHits: 0,
             maybePrune: maybePrune,
             blobHits: 0,
             countdown: countdown,
             misses: 0,
             status: status
             networkStores: 0,
             stores: 0,
             deletes: 0
         };
         };
    }


    window.RevisionManifest = window.RevisionManifest || createRevisionManifestService();
        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 createEntryStore() {
        function ensurePacks() {
        var jsonCache = {};
            if (!packs || typeof packs !== 'object') packs = { packs: {} };
        var flagUrlCache = {};
            if (!packs.packs || typeof packs.packs !== 'object') packs.packs = {};
        var fileUrlCache = {};
         }
        var imageReadyCache = {};
        var imageObjectCache = {};
        var imageDisplayUrlCache = {};
        var imagePromiseCache = {};
        var rawPromiseCache = {};
        var textCache = {};
         var textPromiseCache = {};


         function fetchJsonRef(ref, options) {
         function saveIndex() {
            var key = normalizeRefKey(ref);
             ensureIndex();
            var cacheKey;
             compactIndexForLocalStorage();
            var promiseKey;
             writeLocalJson(ENTRY_CACHE_INDEX_KEY, index);
            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) {
         function savePacks() {
             var key = normalizeRefKey(ref);
             ensurePacks();
             return key && jsonCache[key] ? jsonCache[key].data : null;
             writeLocalJson(ENTRY_CACHE_PACK_KEY, packs);
         }
         }


         function setJsonRef(ref, data) {
         function requestForKey(key) {
             var key = normalizeRefKey(ref);
             return new Request(ENTRY_CACHE_REQUEST_PREFIX + encodeURIComponent(String(key || '')), { credentials: 'same-origin' });
            if (!key) return;
            jsonCache[key] = { key: key, ref: ref, url: rawUrlForRef(ref, 'application/json'), data: data, loadedAt: now() };
         }
         }


         function normalizeFile(value) {
         function openCache() {
             return String(value || '')
             if (!hasCacheStorage()) return Promise.resolve(null);
                .replace(/^(?:file|파일):/i, '')
            return window.caches.open(ENTRY_CACHE_NAME).catch(function () { return null; });
                .trim();
         }
         }


         function fileKey(value) {
         function cacheEntry(key, meta) {
             return normalizeFile(value).replace(/_/g, ' ').replace(/\s+/g, ' ').toLowerCase();
             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 setFlagUrl(file, url) {
         function markHit(key, field) {
             var key = fileKey(file);
             key = String(key || '');
             if (!key) return;
            ensureIndex();
            flagUrlCache[key] = String(url || '');
             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 getFlagUrl(file) {
         function getResponse(key) {
             var key = fileKey(file);
             key = String(key || '');
             return key ? (flagUrlCache[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 resolveFlagUrls(files) {
         function putResponse(key, response, meta) {
             var clean = unique((files || []).map(normalizeFile).filter(Boolean));
             key = String(key || '');
 
            if (!key || !response || !hasCacheStorage()) return Promise.resolve(false);
             function cacheKeyForFile(file) {
            meta = meta || {};
                 return window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef('File:' + file, 'flagurl') : '';
             return openCache().then(function (cache) {
            }
                 var cloned;
 
                var headers;
            function resourceKeyForFile(file) {
                var bodyPromise;
                 return window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef('File:' + file) : ('file:' + fileKey(file));
                if (!cache) return false;
            }
                 cloned = response.clone();
 
                bodyPromise = cloned.blob().catch(function () { return null; });
            function tokenForFile(file) {
                return bodyPromise.then(function (blob) {
                return window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef('File:' + file) : '';
                    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');
            function hydrateCachedFlagUrl(file) {
                    headers.set('X-Entry-Cache-Key', key);
                var key = fileKey(file);
                    headers.set('X-Entry-Resource-Key', String(meta.resourceKey || ''));
                var cacheKey = cacheKeyForFile(file);
                    headers.set('X-Entry-Revision-Token', String(meta.token || ''));
                if (!key || flagUrlCache[key] !== undefined || !cacheKey || !window.EntryCache || typeof window.EntryCache.getText !== 'function') {
                     headers.set('X-Entry-Cached-At', String(now()));
                     return Promise.resolve(false);
                    return cache.put(requestForKey(key), new Response(blob, { status: 200, headers: headers })).then(function () {
                }
                        stats.stores += 1;
                return window.EntryCache.getText(cacheKey).then(function (cachedUrl) {
                         cacheEntry(key, {
                    if (cachedUrl !== null && cachedUrl !== undefined) {
                            resourceKey: meta.resourceKey,
                         flagUrlCache[key] = String(cachedUrl || '');
                            token: meta.token,
                            kind: meta.kind || 'blob',
                            contentType: headers.get('Content-Type') || blob.type || '',
                            size: blob.size
                        });
                         return true;
                         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 = [];
            }).catch(function () { return false; });
        }


                while (pending.length) chunks.push(pending.splice(0, 20));
        function getText(key) {
                 if (!chunks.length) return flagUrlCache;
            return getResponse(key).then(function (res) {
                if (!res) return null;
                markHit(key, 'textHits');
                 return res.text();
            }).catch(function () { return null; });
        }


                return Promise.all(chunks.map(function (chunk) {
        function putText(key, text, meta) {
                    var titleToKey = {};
            key = String(key || '');
                    var keyToFile = {};
            if (!key || !hasCacheStorage()) return Promise.resolve(false);
                    var titles = [];
            meta = meta || {};
                    chunk.forEach(function (file) {
            return openCache().then(function (cache) {
                        var key = fileKey(file);
                var headers;
                        if (!key) return;
                var body = String(text || '');
                        titleToKey[fileKey('File:' + file)] = key;
                if (!cache) return false;
                        titleToKey[fileKey('파일:' + file)] = key;
                headers = new Headers({
                        keyToFile[key] = file;
                    'Content-Type': meta.contentType || 'text/plain; charset=UTF-8',
                         titles.push('File:' + file);
                    'X-Entry-Cache-Key': key,
                         titles.push('파일:' + file);
                    '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 fetchApi({
                     return true;
                        action: 'query',
                });
                        format: 'json',
            }).catch(function () { return false; });
                        formatversion: '2',
        }
                        redirects: '1',
 
                        prop: 'imageinfo',
        function getBlobUrl(key) {
                        iiprop: 'url|sha1|timestamp|size',
            key = String(key || '');
                        iiurlwidth: '16',
            if (!key) return Promise.resolve('');
                        titles: titles.join('|')
            if (objectUrls[key]) {
                    }).then(function (json) {
                markHit(key, 'blobHits');
                        var pages = (json && json.query && json.query.pages) || [];
                return Promise.resolve(objectUrls[key]);
                        var seen = {};
            }
                        pages.forEach(function (page) {
            return getResponse(key).then(function (res) {
                            var key = titleToKey[fileKey(page && page.title)] || fileKey(page && page.title);
                if (!res) return '';
                            var file = keyToFile[key] || (page && page.title || '').replace(/^(?:File|파일):/i, '');
                return res.blob().then(function (blob) {
                            var imageinfo = page && page.imageinfo && page.imageinfo[0];
                    if (!blob || !blob.size) return '';
                            var url;
                    objectUrls[key] = URL.createObjectURL(blob);
                            var rev;
                    markHit(key, 'blobHits');
                            var sep;
                    return objectUrls[key];
                            var cacheKey;
                });
                            if (!key) return;
            }).catch(function () { return ''; });
                            seen[key] = true;
        }
                            url = imageinfo && (imageinfo.thumburl || imageinfo.url) ? (imageinfo.thumburl || imageinfo.url) : '';
 
                            if (url) {
        function fetchBlobUrl(url, key, meta, options) {
                                rev = imageinfo && (imageinfo.sha1 || imageinfo.timestamp || imageinfo.size) ? (imageinfo.sha1 || imageinfo.timestamp || imageinfo.size) : '';
            url = String(url || '').trim();
                                if (rev && !/[?&]_entryFileRev=/.test(url)) {
            key = String(key || '').trim();
                                    sep = url.indexOf('?') === -1 ? '?' : '&';
            if (!url || !key) return Promise.resolve('');
                                    url += sep + '_entryFileRev=' + encodeURIComponent(String(rev));
            return getBlobUrl(key).then(function (cachedUrl) {
                                }
                if (cachedUrl) return cachedUrl;
                            }
                return fetch(url, {
                            flagUrlCache[key] = url;
                    credentials: 'same-origin',
                            cacheKey = cacheKeyForFile(file);
                    cache: options && options.noStore ? 'no-store' : 'force-cache'
                            if (cacheKey && window.EntryCache && typeof window.EntryCache.putText === 'function') {
                }).then(function (res) {
                                window.EntryCache.putText(cacheKey, url || '', {
                    if (!res.ok) throw new Error('HTTP ' + res.status);
                                    resourceKey: resourceKeyForFile(file),
                    stats.networkStores += 1;
                                    token: tokenForFile(file),
                    return putResponse(key, res, Object.assign({}, meta || {}, { kind: meta && meta.kind ? meta.kind : 'blob' })).then(function () {
                                    kind: 'flagurl',
                         return getBlobUrl(key);
                                    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; });
                 }).catch(function () {
                    return '';
                });
             });
             });
         }
         }


         function normalizeGenericFileTitle(value) {
         function deleteKey(key) {
             var text = String(value || '').trim();
             key = String(key || '');
            var match;
             if (!key || !hasCacheStorage()) return Promise.resolve(false);
            var i;
             if (objectUrls[key]) {
 
                 try { URL.revokeObjectURL(objectUrls[key]); } catch (err) {}
             if (!text) return '';
                delete objectUrls[key];
             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);
             return openCache().then(function (cache) {
            if (match) text = match[1];
                if (!cache) return false;
            text = text.replace(/^https?:\/\/[^/]+/i, '').replace(/^\/+/, '').replace(/^index\.php\/?/i, '').replace(/^wiki\/?/i, '').trim();
                return cache.delete(requestForKey(key)).then(function (ok) {
            match = text.match(/(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\/(.+)$/i);
                    ensureIndex();
            if (match) text = match[1];
                    if (index.entries && index.entries[key]) {
             text = text.replace(/^(?:File|파일|Image|이미지)\s*:/i, '').replace(/^:+/, '').trim();
                        delete index.entries[key];
            return text;
                        stats.deletes += 1;
                        saveIndex();
                    }
                    return ok;
                });
             }).catch(function () { return false; });
         }
         }


         function isFileRef(value) {
         function invalidateResources(resourceKeys) {
             var text = String(value || '').trim();
             var map = {};
             return /^(?:file|파일)\s*:/i.test(text) || /(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\//i.test(text);
            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 fileUrlKey(value) {
         function prune(maxAgeDays) {
             return normalizeGenericFileTitle(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 stableDirectImageUrl(url) {
         function reset() {
             var text = String(url || '').trim();
             Object.keys(objectUrls).forEach(function (key) {
             var separator;
                try { URL.revokeObjectURL(objectUrls[key]); } catch (err) {}
             var bust;
             });
             if (!text) return '';
             objectUrls = {};
             if (/[?&]_entryAsset=/.test(text) || /[?&]_=/.test(text)) return text;
             index = { entries: {} };
             bust = String(BUILD_ID || 'entry');
             packs = { packs: {} };
             separator = text.indexOf('?') === -1 ? '?' : '&';
            saveIndex();
             return text + separator + '_entryAsset=' + encodeURIComponent(bust);
             savePacks();
             if (!hasCacheStorage()) return Promise.resolve(false);
             return window.caches.delete(ENTRY_CACHE_NAME).catch(function () { return false; });
         }
         }


         function resolveFileUrl(ref) {
         function packReady(key, token) {
             var original = String(ref || '').trim();
             key = String(key || '');
             var file;
             token = String(token || '');
            var key;
             ensurePacks();
            var cacheKey;
             if (!key || !token) return false;
            var resourceKey;
             return !!(packs.packs[key] && String(packs.packs[key].token || '') === token && packs.packs[key].ready);
            var token;
        }
            if (!original) return Promise.resolve('');
 
             if (!isFileRef(original)) return Promise.resolve(stableDirectImageUrl(original));
        function setPackReady(key, token, meta) {
            file = normalizeGenericFileTitle(original);
             key = String(key || '');
            key = fileUrlKey(file);
             token = String(token || '');
             if (!file || !key) return Promise.resolve(stableDirectImageUrl(original));
             if (!key || !token) return false;
             if (fileUrlCache[key]) return Promise.resolve(fileUrlCache[key]);
            ensurePacks();
            cacheKey = window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef('File:' + file, 'fileurl') : '';
            packs.packs[key] = Object.assign({}, meta || {}, {
             resourceKey = window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef('File:' + file) : ('file:' + key);
                key: key,
             token = window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef('File:' + file) : '';
                token: token,
             if (cacheKey && window.EntryCache && typeof window.EntryCache.getText === 'function') {
                ready: true,
                return window.EntryCache.getText(cacheKey).then(function (cachedUrl) {
                updatedAt: now()
                    if (cachedUrl !== null && cachedUrl !== undefined) {
            });
                        fileUrlCache[key] = String(cachedUrl || '');
            savePacks();
                        return fileUrlCache[key];
            return true;
                    }
        }
                    return fetchApi({
 
                        action: 'query',
        function packInfo() {
                        format: 'json',
            ensurePacks();
                        formatversion: '2',
            return Object.assign({}, packs.packs || {});
                        redirects: '1',
        }
                        prop: 'imageinfo',
 
                        iiprop: 'url|sha1|timestamp|size|mime',
        function info() {
                        titles: 'File:' + file
            var lastClientPrune = 0;
                    }).then(function (json) {
            var entries;
                        var pages = (json && json.query && json.query.pages) || [];
            var byKind = {};
                        var info = pages[0] && pages[0].imageinfo && pages[0].imageinfo[0] ? pages[0].imageinfo[0] : null;
            try { lastClientPrune = Number(window.localStorage && window.localStorage.getItem(REVISION_MANIFEST_PRUNE_LOCAL_KEY) || 0); } catch (err) {}
                        var url = info && info.url ? info.url : original;
            ensureIndex();
                        var rev = info && (info.sha1 || info.timestamp || info.size) ? (info.sha1 || info.timestamp || info.size) : String(window.CLBI_RAW_LOAD_BUST || BUILD_ID);
            ensurePacks();
                        var separator = url.indexOf('?') === -1 ? '?' : '&';
             entries = index.entries || {};
                        var resolved = url + separator + '_entryFileRev=' + encodeURIComponent(String(rev));
             Object.keys(entries).forEach(function (key) {
                        fileUrlCache[key] = resolved;
                 var kind = String(entries[key] && entries[key].kind || 'raw');
                        window.EntryCache.putText(cacheKey, resolved, { resourceKey: resourceKey, token: token, kind: 'fileurl', contentType: 'text/plain; charset=UTF-8' });
                 byKind[kind] = (byKind[kind] || 0) + 1;
                        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(window.CLBI_RAW_LOAD_BUST || BUILD_ID);
                var separator = url.indexOf('?') === -1 ? '?' : '&';
                 var resolved = url + separator + '_entryFileRev=' + encodeURIComponent(String(rev));
                fileUrlCache[key] = resolved;
                return resolved;
            }).catch(function () {
                return stableDirectImageUrl(original);
             });
             });
            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 preloadImageUrl(url) {
         /* Trim legacy image/blob metadata rows produced by older builds. */
            var key = String(url || '').trim();
        try { saveIndex(); } catch (err) {}
            var cacheKey;
            var sourcePromise;
            if (!key) return Promise.resolve(false);
            if (imageReadyCache[key]) return Promise.resolve(true);
            if (imagePromiseCache[key]) return imagePromiseCache[key];


             cacheKey = window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForUrl === 'function' ? window.RevisionManifest.cacheKeyForUrl(key, 'image') : '';
        return {
             sourcePromise = Promise.resolve('');
            getResponse: getResponse,
             if (cacheKey && window.EntryCache && typeof window.EntryCache.fetchBlobUrl === 'function') {
            putResponse: putResponse,
                sourcePromise = window.EntryCache.fetchBlobUrl(key, cacheKey, {
             getText: getText,
                    resourceKey: '',
            putText: putText,
                    token: '',
             getBlobUrl: getBlobUrl,
                    kind: 'image'
             fetchBlobUrl: fetchBlobUrl,
                }).catch(function () { return ''; });
            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 = [];


            imagePromiseCache[key] = sourcePromise.then(function (cachedObjectUrl) {
        function unwrap(payload) {
                return new Promise(function (resolve) {
            return payload && (payload.entryrevisionmanifest || payload.revisionManifest || payload) || null;
                    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) {
         function resourcesOf(manifest) {
             var list = unique((urls || []).filter(Boolean));
             return manifest && manifest.resources && typeof manifest.resources === 'object' ? manifest.resources : {};
            var limit = options && Number(options.limit);
        }
             var concurrency = Math.max(1, Math.min(48, Number(options && options.concurrency) || 24));
 
             var index = 0;
        function compactRevisionManifest(manifest) {
             var ok = 0;
             var out;
             var fail = 0;
             var resources;
            if (Number.isFinite(limit) && limit > 0) list = list.slice(0, limit);
             if (!manifest || typeof manifest !== 'object') return null;
            if (!list.length) return Promise.resolve({ total: 0, ok: 0, fail: 0 });
             out = {
             return new Promise(function (resolve) {
                manifestVersion: manifest.manifestVersion || manifest.version || '',
                function pump() {
                version: manifest.version || manifest.manifestVersion || '',
                    while (index < list.length && concurrency > 0) {
                generatedAt: manifest.generatedAt || '',
                        (function (url) {
                pruneDays: manifest.pruneDays,
                            concurrency -= 1;
                clientPruneDays: manifest.clientPruneDays,
                            preloadImageUrl(url).then(function (result) {
                resources: {}
                                if (result) ok += 1;
            };
                                else fail += 1;
             resources = resourcesOf(manifest);
                            }).catch(function () {
            Object.keys(resources).forEach(function (title) {
                                fail += 1;
                var src = resources[title];
                            }).then(function () {
                var dst;
                                concurrency += 1;
                if (!src || typeof src !== 'object') return;
                                if (index >= list.length && ok + fail >= list.length) resolve({ total: list.length, ok: ok, fail: fail });
                dst = {};
                                else pump();
                ['revision', 'sha1', 'hash', 'timestamp', 'updatedAt', 'url'].forEach(function (key) {
                            });
                    if (src[key] !== undefined && src[key] !== null && String(src[key]) !== '') dst[key] = src[key];
                        })(list[index++]);
                });
                    }
                out.resources[title] = dst;
                }
                pump();
             });
             });
            return out;
         }
         }


         function isImageReady(url) {
         function buildLookup(manifest) {
             var key = String(url || '').trim();
             var lookup = {};
            return !!(key && imageReadyCache[key]);
            Object.keys(resourcesOf(manifest)).forEach(function (title) {
                lookup[normalizeManifestTitle(title).toLowerCase()] = resourcesOf(manifest)[title];
            });
            return lookup;
         }
         }


         function getImageElement(url) {
         function computeChanged(prev, next) {
             var key = String(url || '').trim();
             var prevLookup = buildLookup(prev);
             return key ? (imageObjectCache[key] || null) : null;
            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 getImageDisplayUrl(url) {
         function load(options) {
             var key = String(url || '').trim();
             if (loadPromise && !(options && options.force)) return loadPromise;
             return key ? (imageDisplayUrlCache[key] || key) : '';
            loadPromise = fetchApi({
         }
                action: REVISION_MANIFEST_ACTION,
 
                format: 'json',
         function normalizeUrlKey(url) {
                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 text = String(url || '').trim();
             var a;
             var token = tokenFromUrl(text) || manifestToken('url');
            var normalized;
             if (!text) return '';
             if (!text) return '';
             try {
             try {
                 a = document.createElement('a');
                 normalized = new URL(text, window.location.href);
                a.href = text;
                 text = normalized.pathname + (normalized.search || '');
                 text = a.pathname + (a.search || '');
             } catch (err) {}
             } catch (err) {}
            try {
             text = text.replace(/[?&](?:_entryFileRev|_entryAsset|_entryRev)=[^&]*/g, '').replace(/[?&]$/, '');
                text = decodeURI(text);
             try { text = decodeURI(text); } catch (err2) {}
            } catch (err2) {}
             return String(type || 'blob') + ':url:' + text.toLowerCase() + '@' + token;
             text = text.replace(/([?&])_=[^&]*/g, '$1').replace(/[?&]$/, '');
             text = text.replace(/_/g, '_');
             return text;
         }
         }


         function fetchTextUrl(url, options) {
         function addRevisionParam(url, ref) {
            var key = normalizeUrlKey(url);
             var token = tokenForRef(ref);
            var cacheKey;
             var text = String(url || '').trim();
            var resourceRef;
             var sep;
            var resourceKey;
             if (!text || !token || /[?&]_entryRev=/.test(text)) return text;
             var token;
            sep = text.indexOf('?') === -1 ? '?' : '&';
            if (!key) return Promise.reject(new Error('empty text url'));
             return text + sep + '_entryRev=' + encodeURIComponent(token);
            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) {
         function maybePrune() {
             var key = normalizeUrlKey(url);
             var days = current && Number(current.pruneDays || current.clientPruneDays) || 7;
             return key && textCache[key] ? textCache[key].text : '';
            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 setTextUrl(url, text) {
         function countdown() {
             var key = normalizeUrlKey(url);
             var days = current && Number(current.pruneDays || current.clientPruneDays) || 7;
             if (!key) return;
            var last = 0;
             textCache[key] = { key: key, url: url, text: String(text || ''), loadedAt: now() };
            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 cacheInfo() {
         function status() {
             return {
             return {
                 json: Object.keys(jsonCache).length,
                 available: !!current,
                 jsonKeys: Object.keys(jsonCache),
                 manifestVersion: current && (current.manifestVersion || current.version || ''),
                 flags: Object.keys(flagUrlCache).length,
                 generatedAt: current && current.generatedAt || '',
                 files: Object.keys(fileUrlCache).length,
                 changedResources: changedResources.slice(0, 50),
                 images: Object.keys(imageReadyCache).length,
                 changedCount: changedResources.length,
                 retainedImages: Object.keys(imageObjectCache).length,
                 prune: countdown(),
                 displayImages: Object.keys(imageDisplayUrlCache).length,
                 cache: window.EntryCache && typeof window.EntryCache.info === 'function' ? window.EntryCache.info() : null
                text: Object.keys(textCache).length,
                textKeys: Object.keys(textCache)
             };
             };
         }
         }


         return {
         return {
             fetchJsonRef: fetchJsonRef,
             load: load,
             getJsonSync: getJsonSync,
             ensureLoaded: ensureLoaded,
             setJsonRef: setJsonRef,
             current: function () { return current; },
             normalizeRefKey: normalizeRefKey,
             resourceForRef: resourceForRef,
             rawUrlForRef: rawUrlForRef,
             tokenForRef: tokenForRef,
             resolveFlagUrls: resolveFlagUrls,
             cacheKeyForRef: cacheKeyForRef,
             setFlagUrl: setFlagUrl,
             cacheKeyForUrl: cacheKeyForUrl,
             getFlagUrl: getFlagUrl,
             manifestToken: manifestToken,
             resolveFileUrl: resolveFileUrl,
             resourceKeyForRef: resourceKeyForRef,
             preloadImageUrl: preloadImageUrl,
             addRevisionParam: addRevisionParam,
             preloadImages: preloadImages,
             maybePrune: maybePrune,
             isImageReady: isImageReady,
             countdown: countdown,
             getImageElement: getImageElement,
             status: status
            getImageDisplayUrl: getImageDisplayUrl,
            fetchTextUrl: fetchTextUrl,
            getTextSync: getTextSync,
            setTextUrl: setTextUrl,
            stableDirectImageUrl: stableDirectImageUrl,
            cacheInfo: cacheInfo
         };
         };
     }
     }


     window.EntryStore = window.EntryStore || createEntryStore();
     window.RevisionManifest = window.RevisionManifest || createRevisionManifestService();


     function updateBootProgress(done, total, label) {
     function createEntryStore() {
         var pct = total ? Math.max(0, Math.min(100, Math.round((done / total) * 100))) : 0;
         var jsonCache = {};
         if (bootProgressNode) bootProgressNode.textContent = pct + '%';
        var flagUrlCache = {};
         if (bootFillNode) bootFillNode.style.width = pct + '%';
        var fileUrlCache = {};
         if (bootDetailNode && label) bootDetailNode.textContent = label;
        var imageReadyCache = {};
    }
        var imageObjectCache = {};
        var imageDisplayUrlCache = {};
         var imagePromiseCache = {};
         var rawPromiseCache = {};
         var textCache = {};
        var textPromiseCache = {};


    function adoptBootScreen(node) {
        function fetchJsonRef(ref, options) {
        if (!node) return null;
            var key = normalizeRefKey(ref);
        bootNode = node;
            var cacheKey;
        bootStatusNode = bootNode.querySelector('.boot-gate-status');
            var promiseKey;
        bootProgressNode = bootNode.querySelector('.boot-gate-progress');
            var url;
        bootDetailNode = bootNode.querySelector('.boot-gate-detail');
            var resourceKey;
        bootFillNode = bootNode.querySelector('.boot-gate-meter-fill');
            var token;
        bootNode.classList.add('is-active');
            if (!key) return Promise.reject(new Error('empty json ref'));
        bootNode.classList.remove('is-complete');
            cacheKey = window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef(ref, 'json') : '';
        return bootNode;
            promiseKey = cacheKey ? (key + '@' + cacheKey) : key;
    }
            if (jsonCache[promiseKey]) return Promise.resolve(jsonCache[promiseKey].data);
 
            if (rawPromiseCache[promiseKey]) return rawPromiseCache[promiseKey];
    function ensureBootScreen() {
            url = rawUrlForRef(ref, 'application/json');
        var panel;
            if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
        var header;
                url = window.RevisionManifest.addRevisionParam(url, ref);
        var meter;
            }
        var existing;
            resourceKey = window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef(ref) : key;
        var decoLayer;
            token = window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef(ref) : '';
        var close;
            if (cacheKey && !(options && options.noStore) && window.EntryCache && typeof window.EntryCache.getText === 'function') {
        if (bootNode && bootNode.parentNode) return bootNode;
                rawPromiseCache[promiseKey] = window.EntryCache.getText(cacheKey).then(function (cachedText) {
        if (!document.body) return null;
                    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];
        }


         if (BOOT_EXCLUDED_PAGE) return null;
         function getJsonSync(ref) {
         activateBootSurface();
            var key = normalizeRefKey(ref);
            return key && jsonCache[key] ? jsonCache[key].data : null;
         }


         existing = document.getElementById('boot-gate-screen') || (window.__BootGatePrelude && window.__BootGatePrelude.ensure ? window.__BootGatePrelude.ensure() : null);
         function setJsonRef(ref, data) {
        if (existing) return adoptBootScreen(existing);
            var key = normalizeRefKey(ref);
            if (!key) return;
            jsonCache[key] = { key: key, ref: ref, url: rawUrlForRef(ref, 'application/json'), data: data, loadedAt: now() };
        }


         bootNode = document.createElement('div');
         function normalizeFile(value) {
        bootNode.id = 'boot-gate-screen';
            return String(value || '')
        bootNode.className = 'boot-gate-screen is-active';
                .replace(/^(?:file|파일):/i, '')
        bootNode.setAttribute('role', 'status');
                .trim();
        bootNode.setAttribute('aria-live', 'polite');
        }


         panel = document.createElement('div');
         function fileKey(value) {
        panel.className = 'boot-gate-panel';
            return normalizeFile(value).replace(/_/g, ' ').replace(/\s+/g, ' ').toLowerCase();
        }


         header = document.createElement('div');
         function setFlagUrl(file, url) {
        header.className = 'boot-gate-title';
            var key = fileKey(file);
         header.textContent = 'ARCHIVE INITIALIZATION';
            if (!key) return;
            flagUrlCache[key] = String(url || '');
         }


         bootStatusNode = document.createElement('div');
         function getFlagUrl(file) {
        bootStatusNode.className = 'boot-gate-status';
            var key = fileKey(file);
         bootStatusNode.textContent = 'Preparing entry systems';
            return key ? (flagUrlCache[key] || '') : '';
         }


         meter = document.createElement('div');
         function resolveFlagUrls(files) {
        meter.className = 'boot-gate-meter';
            var clean = unique((files || []).map(normalizeFile).filter(Boolean));
        bootFillNode = document.createElement('div');
        bootFillNode.className = 'boot-gate-meter-fill';
        meter.appendChild(bootFillNode);


        bootProgressNode = document.createElement('div');
            function cacheKeyForFile(file) {
        bootProgressNode.className = 'boot-gate-progress';
                return window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef('File:' + file, 'flagurl') : '';
        bootProgressNode.textContent = '0%';
            }


        bootDetailNode = document.createElement('div');
            function resourceKeyForFile(file) {
        bootDetailNode.className = 'boot-gate-detail';
                return window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef('File:' + file) : ('file:' + fileKey(file));
        bootDetailNode.textContent = 'loading manifest';
            }


        close = document.createElement('button');
            function tokenForFile(file) {
        close.type = 'button';
                return window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef('File:' + file) : '';
        close.className = 'boot-gate-close';
            }
        close.setAttribute('aria-label', 'Close boot preview');
        close.textContent = '×';
        close.addEventListener('click', function () { hideBootScreen(); });


        decoLayer = document.createElement('div');
            function hydrateCachedFlagUrl(file) {
        decoLayer.className = 'boot-gate-decoration-layer';
                var key = fileKey(file);
        decoLayer.setAttribute('data-decoration-target', 'boot-gate');
                var cacheKey = cacheKeyForFile(file);
        decoLayer.setAttribute('aria-hidden', 'true');
                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; });
            }


        panel.appendChild(header);
            return Promise.all(clean.map(hydrateCachedFlagUrl)).then(function () {
        panel.appendChild(bootStatusNode);
                var pending = clean.filter(function (file) {
        panel.appendChild(meter);
                    return getFlagUrl(file) === '' && flagUrlCache[fileKey(file)] === undefined;
        panel.appendChild(bootProgressNode);
                });
        panel.appendChild(bootDetailNode);
                var chunks = [];
        bootNode.appendChild(decoLayer);
        bootNode.appendChild(panel);
        bootNode.appendChild(close);
        document.body.appendChild(bootNode);
        return bootNode;
    }


    function hideBootScreen() {
                while (pending.length) chunks.push(pending.splice(0, 20));
        var node = bootNode || document.getElementById('boot-gate-screen');
                if (!chunks.length) return flagUrlCache;
        if (!node) {
            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) {
                return Promise.all(chunks.map(function (chunk) {
        var files = [];
                    var titleToKey = {};
        function add(value) {
                    var keyToFile = {};
            if (!value) return;
                    var titles = [];
            if (typeof value === 'string') {
                    chunk.forEach(function (file) {
                files.push(value);
                        var key = fileKey(file);
                return;
                        if (!key) return;
            }
                        titleToKey[fileKey('File:' + file)] = key;
            if (typeof value === 'object') files.push(value.file || value.flag_file || value.flag || value.flag_title || '');
                        titleToKey[fileKey('파일:' + file)] = key;
        }
                        keyToFile[key] = file;
        function scanItem(item) {
                        titles.push('File:' + file);
            if (!item || typeof item !== 'object') return;
                        titles.push('파일:' + file);
            if (Array.isArray(item.flags)) item.flags.forEach(add);
                    });
            add(item.flag_file || item.flag || item.flag_title || '');
                    return fetchApi({
        }
                        action: 'query',
        (payload && payload.continents || []).forEach(function (continent) {
                        format: 'json',
            (continent.regions || []).forEach(function (region) {
                        formatversion: '2',
                (region.items || []).forEach(scanItem);
                        redirects: '1',
            });
                        prop: 'imageinfo',
        });
                        iiprop: 'url|sha1|timestamp|size',
        return unique(files);
                        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 collectFlagsFromLinkMap(payload) {
         function normalizeGenericFileTitle(value) {
        var files = [];
             var text = String(value || '').trim();
        var source = payload && payload.items ? payload.items : {};
            var match;
         Object.keys(source || {}).forEach(function (key) {
            var i;
             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) {
            if (!text) return '';
        return window.EntryStore.preloadImages(urls, {
            for (i = 0; i < 4; i += 1) {
             limit: Number(limit) > 0 ? Number(limit) : 0,
                try {
             concurrency: 24
                    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 getDecorationRuntime() {
        function isFileRef(value) {
        return window.Decorations || window.CLBI_DECORATIONS || null;
            var text = String(value || '').trim();
    }
            return /^(?:file|파일)\s*:/i.test(text) || /(?:^|\/)(?:(?:Special|특수)\s*[:/]\s*)?(?:Redirect|넘겨주기)\s*\/\s*file\s*\//i.test(text);
        }


    function waitForDecorationRuntime() {
         function fileUrlKey(value) {
         return new Promise(function (resolve) {
             return normalizeGenericFileTitle(value).replace(/_/g, ' ').replace(/\s+/g, ' ').toLowerCase();
             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) {
        function stableDirectImageUrl(url) {
        var era = String(filter && filter.era || '').trim();
            var text = String(url || '').trim();
        var page = String(filter && filter.page || '').trim();
            var separator;
        var entryPage = String(entry && entry.page || '').replace(/_/g, ' ').trim();
            var bust;
        if (!entry || typeof entry !== 'object') return false;
            if (!text) return '';
        if (page && entryPage && entryPage !== page) return false;
            if (/[?&]_entryAsset=/.test(text) || /[?&]_=/.test(text)) return text;
        if (era && String(entry.era || '').trim() && String(entry.era || '').trim() !== era) return false;
            bust = String(BUILD_ID || 'entry');
        return true;
            separator = text.indexOf('?') === -1 ? '?' : '&';
    }
            return text + separator + '_entryAsset=' + encodeURIComponent(bust);
        }


    function prepareDecorationSet(task, level) {
        function resolveFileUrl(ref) {
        var ref = task.ref || 'MediaWiki:Decorations.json';
            var original = String(ref || '').trim();
        return window.EntryStore.fetchJsonRef(ref, { noStore: !!task.noStore }).then(function (registry) {
             var file;
             var list = registry && Array.isArray(registry.decorations) ? registry.decorations : [];
             var key;
             var pixelRefs = [];
             var cacheKey;
             list.forEach(function (entry) {
            var resourceKey;
                var type = String(entry && entry.assetType || '').toLowerCase();
            var token;
                var asset = String(entry && (entry.asset || entry.src) || '').trim();
            if (!original) return Promise.resolve('');
                if (!asset) return;
            if (!isFileRef(original)) return Promise.resolve(stableDirectImageUrl(original));
                if (type !== 'pixel-json' && !/\.json(?:[?#].*)?$/i.test(asset)) return;
            file = normalizeGenericFileTitle(original);
                if (!matchesDecorationEntry(entry, task)) return;
             key = fileUrlKey(file);
                pixelRefs.push(asset);
             if (!file || !key) return Promise.resolve(stableDirectImageUrl(original));
             });
             if (fileUrlCache[key]) return Promise.resolve(fileUrlCache[key]);
             if (level !== 'full' || task.preparePixels === false || !pixelRefs.length) return registry;
            cacheKey = window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForRef === 'function' ? window.RevisionManifest.cacheKeyForRef('File:' + file, 'fileurl') : '';
             return waitForDecorationRuntime().then(function (runtime) {
            resourceKey = window.RevisionManifest && typeof window.RevisionManifest.resourceKeyForRef === 'function' ? window.RevisionManifest.resourceKeyForRef('File:' + file) : ('file:' + key);
                if (!runtime || typeof runtime.preparePixelCanvas !== 'function') {
            token = window.RevisionManifest && typeof window.RevisionManifest.tokenForRef === 'function' ? window.RevisionManifest.tokenForRef('File:' + file) : '';
                    return Promise.all(pixelRefs.map(function (pixelRef) {
            if (cacheKey && window.EntryCache && typeof window.EntryCache.getText === 'function') {
                        return window.EntryStore.fetchJsonRef(pixelRef).catch(function () { return null; });
                return window.EntryCache.getText(cacheKey).then(function (cachedUrl) {
                    })).then(function () { return registry; });
                    if (cachedUrl !== null && cachedUrl !== undefined) {
                }
                        fileUrlCache[key] = String(cachedUrl || '');
                return Promise.all(pixelRefs.map(function (pixelRef) {
                        return fileUrlCache[key];
                    return runtime.preparePixelCanvas(pixelRef).catch(function () { return null; });
                    }
                })).then(function () { return registry; });
                    return fetchApi({
            });
                        action: 'query',
        });
                        format: 'json',
    }
                        formatversion: '2',
 
                        redirects: '1',
    function prepareNationsEra(task, level) {
                        prop: 'imageinfo',
        var era = String(task.era || '1950');
                        iiprop: 'url|sha1|timestamp|size|mime',
        var listRef = task.listRef || ('MediaWiki:' + era + '_Nation_List.json');
                        titles: 'File:' + file
        var linkRef = task.linkMapRef || ('MediaWiki:' + era + '_Nation_Link_Map.json');
                    }).then(function (json) {
        var listPromise = window.EntryStore.fetchJsonRef(listRef).catch(function () { return null; });
                        var pages = (json && json.query && json.query.pages) || [];
        var linkPromise = window.EntryStore.fetchJsonRef(linkRef).catch(function () { return null; });
                        var info = pages[0] && pages[0].imageinfo && pages[0].imageinfo[0] ? pages[0].imageinfo[0] : null;
 
                        var url = info && info.url ? info.url : original;
        return Promise.all([listPromise, linkPromise]).then(function (results) {
                        var rev = info && (info.sha1 || info.timestamp || info.size) ? (info.sha1 || info.timestamp || info.size) : String(BUILD_ID || 'entry-file');
            var files;
                        var separator = url.indexOf('?') === -1 ? '?' : '&';
            var flagUrls;
                        var resolved = url + separator + '_entryFileRev=' + encodeURIComponent(String(rev));
            if (level !== 'full') return results;
                        fileUrlCache[key] = resolved;
            files = unique(collectFlagsFromNationPayload(results[0]).concat(collectFlagsFromLinkMap(results[1])));
                        window.EntryCache.putText(cacheKey, resolved, { resourceKey: resourceKey, token: token, kind: 'fileurl', contentType: 'text/plain; charset=UTF-8' });
            return window.EntryStore.resolveFlagUrls(files).then(function () {
                        return resolved;
                 flagUrls = files.map(function (file) { return window.EntryStore.getFlagUrl(file); }).filter(Boolean);
                    });
                 /* Full means visible flag images are already downloaded and decoded, not just URL-resolved. */
                }).catch(function () {
                return prewarmImages(flagUrls, task.flagLimit == null ? 0 : Number(task.flagLimit)).then(function () { return results; });
                    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 prepareGlobeSharedAssets(task, level) {
        function preloadImageUrl(url, options) {
        var refs = Array.isArray(task && task.assets) ? task.assets : [];
            var key = String(url || '').trim();
        var full = level === 'full';
            var cacheKey;
        if (!refs.length) return Promise.resolve(null);
            var sourcePromise;
        return Promise.all(refs.map(function (ref) {
            var persistent = !(options && options.persistent === false);
             return window.EntryStore.resolveFileUrl(ref).catch(function () { return ''; });
            if (!key) return Promise.resolve(false);
        })).then(function (urls) {
             if (imageReadyCache[key]) return Promise.resolve(true);
            urls = urls.filter(Boolean);
             if (imagePromiseCache[key]) return imagePromiseCache[key];
             if (!full) return urls;
            return window.EntryStore.preloadImages(urls, {
                limit: task.imageLimit == null ? 0 : Number(task.imageLimit),
                concurrency: Math.max(1, Math.min(16, Number(task.concurrency) || 8))
            }).then(function () { return urls; });
        });
    }


    function prepareHtmlEntry(task) {
            cacheKey = persistent && window.RevisionManifest && typeof window.RevisionManifest.cacheKeyForUrl === 'function' ? window.RevisionManifest.cacheKeyForUrl(key, 'image') : '';
        var url = String(task && (task.url || task.ref) || '').trim();
            sourcePromise = Promise.resolve('');
        if (!url) return Promise.resolve(null);
            if (cacheKey && window.EntryCache && typeof window.EntryCache.fetchBlobUrl === 'function') {
        return window.EntryStore.fetchTextUrl(url, { noStore: !!task.noStore, resourceRef: task.resourceRef || task.ref || task.title || '' });
                sourcePromise = window.EntryCache.fetchBlobUrl(key, cacheKey, {
    }
                    resourceKey: '',
                    token: '',
                    kind: 'image'
                }).catch(function () { return ''; });
            }


    function prepareTask(task, defaultLevel) {
            imagePromiseCache[key] = sourcePromise.then(function (cachedObjectUrl) {
        var level = String(task && (task.level || defaultLevel) || 'half').toLowerCase();
                return new Promise(function (resolve) {
        var type = String(task && task.type || '').toLowerCase();
                    var img = new Image();
        if (!task || typeof task !== 'object') return Promise.resolve(null);
                    var settled = false;
        if (type === 'html') return prepareHtmlEntry(task);
                    var src = cachedObjectUrl || key;
        if (type === 'json') return window.EntryStore.fetchJsonRef(task.ref, { noStore: !!task.noStore });
                    function finish(ok) {
        if (type === 'pixel-json') {
                        if (settled) return;
            return waitForDecorationRuntime().then(function (runtime) {
                        settled = true;
                if (level === 'full' && runtime && typeof runtime.preparePixelCanvas === 'function') {
                        if (ok) {
                    return runtime.preparePixelCanvas(task.ref || task.asset);
                            imageReadyCache[key] = true;
                }
                            imageReadyCache[src] = true;
                 return window.EntryStore.fetchJsonRef(task.ref || task.asset);
                            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];
         }
         }
        if (type === 'decorations') return prepareDecorationSet(task, level);
        if (type === 'nations-era') return prepareNationsEra(task, level);
        if (type === 'globe-shared-assets') return prepareGlobeSharedAssets(task, level);
        return Promise.resolve(null);
    }


    function loadManifest() {
        function preloadImages(urls, options) {
        return (window.RevisionManifest && typeof window.RevisionManifest.load === 'function' ? window.RevisionManifest.load() : Promise.resolve(null))
            var list = unique((urls || []).filter(Boolean));
             .then(function () {
            var limit = options && Number(options.limit);
                 return window.EntryStore.fetchJsonRef(MANIFEST_TITLE, { noStore: false });
            var concurrency = Math.max(1, Math.min(48, Number(options && options.concurrency) || 24));
            })
            var index = 0;
            .then(function (manifest) {
            var ok = 0;
                if (!manifest || typeof manifest !== 'object' || !manifest.version) return defaultManifest;
            var fail = 0;
                return manifest;
            if (Number.isFinite(limit) && limit > 0) list = list.slice(0, limit);
            })
            if (!list.length) return Promise.resolve({ total: 0, ok: 0, fail: 0 });
            .catch(function () {
             return new Promise(function (resolve) {
                 return defaultManifest;
                 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 flattenInitialTasks(manifest) {
         function isImageReady(url) {
         var initial = manifest && manifest.initial ? manifest.initial : {};
             var key = String(url || '').trim();
        var full = Array.isArray(initial.full) ? initial.full : [];
             return !!(key && imageReadyCache[key]);
        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 currentInitialPackKey(manifest) {
        function getImageElement(url) {
        var version = manifest && manifest.version ? String(manifest.version) : BUILD_ID;
            var key = String(url || '').trim();
        return 'initial-entry-full:' + version;
            return key ? (imageObjectCache[key] || null) : null;
    }
        }


    function currentInitialPackToken(manifest) {
        function getImageDisplayUrl(url) {
        var version = manifest && manifest.version ? String(manifest.version) : BUILD_ID;
            var key = String(url || '').trim();
        var revToken = window.RevisionManifest && typeof window.RevisionManifest.manifestToken === 'function' ? window.RevisionManifest.manifestToken(version) : version;
            return key ? (imageDisplayUrlCache[key] || key) : '';
         return revToken;
         }
    }


    function isInitialPackWarm(manifest) {
        function normalizeUrlKey(url) {
        var key = currentInitialPackKey(manifest);
            var text = String(url || '').trim();
        var token = currentInitialPackToken(manifest);
            var a;
        return !!(window.EntryCache && typeof window.EntryCache.packReady === 'function' && window.EntryCache.packReady(key, token));
            if (!text) return '';
    }
            try {
 
                a = document.createElement('a');
    function markInitialPackWarm(manifest, meta) {
                a.href = text;
        var key = currentInitialPackKey(manifest);
                text = a.pathname + (a.search || '');
        var token = currentInitialPackToken(manifest);
            } catch (err) {}
        if (window.EntryCache && typeof window.EntryCache.setPackReady === 'function') {
            try {
             window.EntryCache.setPackReady(key, token, Object.assign({ manifestVersion: manifest && manifest.version || BUILD_ID }, meta || {}));
                text = decodeURI(text);
            } catch (err2) {}
            text = text.replace(/([?&])_=[^&]*/g, '$1').replace(/[?&]$/, '');
             text = text.replace(/_/g, '_');
            return text;
         }
         }
    }


 
        function fetchTextUrl(url, options) {
    function waitMs(ms) {
            var key = normalizeUrlKey(url);
        return new Promise(function (resolve) { window.setTimeout(resolve, Math.max(0, ms || 0)); });
            var cacheKey;
    }
            var resourceRef;
 
            var resourceKey;
    function waitForBody() {
            var token;
        if (document.body) return Promise.resolve(document.body);
            if (!key) return Promise.reject(new Error('empty text url'));
        return new Promise(function (resolve) {
            if (textCache[key]) return Promise.resolve(textCache[key].text);
             function tick() {
            if (textPromiseCache[key]) return textPromiseCache[key];
                if (document.body) return resolve(document.body);
            resourceRef = options && options.resourceRef ? options.resourceRef : (options && options.ref ? options.ref : '');
                window.setTimeout(tick, 10);
             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');
            tick();
             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) {
    function waitForDomReady() {
                    if (cachedText !== null && cachedText !== undefined) {
        if (document.readyState !== 'loading') return Promise.resolve();
                        textCache[key] = { key: key, url: url, text: cachedText, loadedAt: now(), persistent: true };
        return new Promise(function (resolve) {
                        return cachedText;
            document.addEventListener('DOMContentLoaded', resolve, { once: true });
                    }
        });
                    return fetch(url, {
    }
                        credentials: 'same-origin',
 
                        cache: 'force-cache'
    function waitForAnimationFrames(count) {
                    }).then(function (res) {
        count = Math.max(1, Math.round(count || 1));
                        if (!res.ok) throw new Error('HTTP ' + res.status);
        return new Promise(function (resolve) {
                        return res.text();
            function next(left) {
                    }).then(function (text) {
                if (left <= 0) return resolve();
                        textCache[key] = { key: key, url: url, text: text, loadedAt: now() };
                window.requestAnimationFrame(function () { next(left - 1); });
                        window.EntryCache.putText(cacheKey, text, { resourceKey: resourceKey, token: token, kind: 'text', contentType: 'text/html; charset=UTF-8' });
                        return text;
                    });
                });
                return textPromiseCache[key];
             }
             }
             next(count);
             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 waitUntil(predicate, options) {
        function getTextSync(url) {
        var started = now();
            var key = normalizeUrlKey(url);
        var timeout = options && options.timeoutMs ? options.timeoutMs : 8000;
            return key && textCache[key] ? textCache[key].text : '';
        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() {
        function setTextUrl(url, text) {
        var list = (window.EntryScriptLoads || []).slice();
            var key = normalizeUrlKey(url);
        if (!list.length) return Promise.resolve([]);
            if (!key) return;
         return Promise.all(list.map(function (promise) {
            textCache[key] = { key: key, url: url, text: String(text || ''), loadedAt: now() };
            return Promise.resolve(promise).catch(function (err) { return { ok: false, error: err }; });
         }
        }));
 
    }
        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)
            };
        }


    function waitForDocumentSurface() {
         return {
         return waitForDomReady().then(function () {
             fetchJsonRef: fetchJsonRef,
             return waitForBody();
            getJsonSync: getJsonSync,
        }).then(function () {
            setJsonRef: setJsonRef,
            return waitUntil(function () {
            normalizeRefKey: normalizeRefKey,
                 return document.querySelector('.content-wrapper') && document.querySelector('.liberty-content-main');
            rawUrlForRef: rawUrlForRef,
             }, { timeoutMs: 8000, intervalMs: 50 });
            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
         };
     }
     }


     function isNationsPageSurface() {
     window.EntryStore = window.EntryStore || createEntryStore();
        var page = String(mw && mw.config ? (mw.config.get('wgPageName') || mw.config.get('wgTitle') || '') : '');
        return !!document.querySelector('.clbi-nations-panel-stack') || /국가[_ ]및[_ ]조합/.test(page);
    }


     function getInitialNationsEra(manifest) {
     function updateBootProgress(done, total, label) {
         var tasks = flattenInitialTasks(manifest);
         var pct = total ? Math.max(0, Math.min(100, Math.round((done / total) * 100))) : 0;
         var i;
         if (bootProgressNode) bootProgressNode.textContent = pct + '%';
        for (i = 0; i < tasks.length; i += 1) {
        if (bootFillNode) bootFillNode.style.width = pct + '%';
            if (tasks[i] && tasks[i].type === 'nations-era' && String(tasks[i].level || '').toLowerCase() === 'full') {
        if (bootDetailNode && label) bootDetailNode.textContent = label;
                return String(tasks[i].era || '1950');
            }
        }
        return '1950';
     }
     }


     function waitForNationsPanelReady(era) {
     function adoptBootScreen(node) {
         return waitUntil(function () { return window.NationsPanel && typeof window.NationsPanel.whenEraReady === 'function'; }, {
         if (!node) return null;
            timeoutMs: 8000,
        bootNode = node;
            intervalMs: 50
         bootStatusNode = bootNode.querySelector('.boot-gate-status');
         }).then(function (result) {
        bootProgressNode = bootNode.querySelector('.boot-gate-progress');
            if (!result.ok || !window.NationsPanel || typeof window.NationsPanel.whenEraReady !== 'function') return null;
         bootDetailNode = bootNode.querySelector('.boot-gate-detail');
            return window.NationsPanel.whenEraReady(era, { timeoutMs: 15000 }).catch(function () { return null; });
        bootFillNode = bootNode.querySelector('.boot-gate-meter-fill');
         }).then(function () {
        bootNode.classList.add('is-active');
            return waitUntil(function () {
        bootNode.classList.remove('is-complete');
                var panel = document.querySelector('.clbi-nations-era-content[data-era-content="' + era + '"] .clbi-nations-tabpanel[data-nation-list-source="1"]') ||
         return bootNode;
                    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) {
     function ensureBootScreen(options) {
         var globe = document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
         var panel;
         var soft;
        var header;
         var timeout;
        var meter;
 
        var existing;
         var decoLayer;
         var close;
        var previewMode;
         options = options || {};
         options = options || {};
         soft = !!options.soft;
         previewMode = !!options.preview;
         timeout = Number(options.timeoutMs || (soft ? 450 : 30000));
         if (bootNode && bootNode.parentNode) return bootNode;
        if (!document.body) return null;


         if (!globe) return Promise.resolve(null);
         if (BOOT_EXCLUDED_PAGE && !previewMode) return null;
        if (!previewMode) activateBootSurface();


         if (soft) {
         existing = document.getElementById('boot-gate-screen') || (!previewMode && window.__BootGatePrelude && window.__BootGatePrelude.ensure ? window.__BootGatePrelude.ensure() : null);
            /*
        if (existing) return adoptBootScreen(existing);
            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 }).then(function (result) {
                return result;
            });
        }


         return waitUntil(function () {
         bootNode = document.createElement('div');
            var node = document.querySelector('.clbi-nations-globe-window[data-nations-globe], [data-nations-globe="real-world"]');
        bootNode.id = 'boot-gate-screen';
            return node && (node.classList.contains('is-ready') || node.classList.contains('has-error'));
        bootNode.className = 'boot-gate-screen is-active';
        }, { timeoutMs: timeout, intervalMs: 100 });
        bootNode.setAttribute('role', 'status');
    }
        bootNode.setAttribute('aria-live', 'polite');


    function waitForDecorationsReady() {
         panel = document.createElement('div');
         return waitForDecorationRuntime().then(function (runtime) {
        panel.className = 'boot-gate-panel';
            if (!runtime || typeof runtime.reload !== 'function') return null;
            return runtime.reload().catch(function () { return null; }).then(function () {
                return waitForAnimationFrames(2);
            });
        });
    }


    function waitForCurrentEntrySurface(manifest, options) {
        header = document.createElement('div');
         var era = getInitialNationsEra(manifest);
         header.className = 'boot-gate-title';
         var warmPack;
         header.textContent = 'ARCHIVE INITIALIZATION';


         options = options || {};
         bootStatusNode = document.createElement('div');
         warmPack = !!options.warmPack;
         bootStatusNode.className = 'boot-gate-status';
        bootStatusNode.textContent = 'Preparing entry systems';


         if (!isNationsPageSurface()) {
         meter = document.createElement('div');
            return waitForDecorationsReady().then(function () { return waitForAnimationFrames(1); });
         meter.className = 'boot-gate-meter';
        }
         bootFillNode = document.createElement('div');
         if (bootStatusNode) bootStatusNode.textContent = warmPack ? 'Hydrating current information surface from warm cache' : 'Preparing current information surface';
        bootFillNode.className = 'boot-gate-meter-fill';
         if (bootDetailNode) bootDetailNode.textContent = 'waiting for nations ' + era + ' ready contract';
        meter.appendChild(bootFillNode);
        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();
            })
            .then(function () { return waitForAnimationFrames(warmPack ? 1 : 2); });
    }


    function runInitialLoad(options) {
        bootProgressNode = document.createElement('div');
        var done = 0;
         bootProgressNode.className = 'boot-gate-progress';
        var manifestRef;
         bootProgressNode.textContent = '0%';
        var tasks;
        var bootOptions;
         var timedOut = false;
         var warmPack = false;


         options = options || {};
         bootDetailNode = document.createElement('div');
        bootStartTime = window.__BootGatePrelude && window.__BootGatePrelude.startTime ? window.__BootGatePrelude.startTime : now();
         bootDetailNode.className = 'boot-gate-detail';
         activateBootSurface();
         bootDetailNode.textContent = 'loading manifest';
         ensureBootScreen();
        updateBootProgress(0, 1, 'loading entry manifest');


         manifestRef = loadManifest().then(function (manifest) {
         close = document.createElement('button');
            var minDisplay;
        close.type = 'button';
            var totalSteps;
        close.className = 'boot-gate-close';
            var maxBlockingMs;
        close.setAttribute('aria-label', 'Close boot preview');
            var timeoutHandle;
        close.textContent = '×';
            bootOptions = manifest.boot || {};
        close.addEventListener('click', function () { hideBootScreen({ force: true }); });
            warmPack = isInitialPackWarm(manifest);
            minDisplay = options.minDisplayMs || (warmPack ? (bootOptions.cachedMinDisplayMs || 220) : (bootOptions.minDisplayMs || 950));
            tasks = flattenInitialTasks(manifest);
            if (!tasks.length) tasks = flattenInitialTasks(defaultManifest);


            /*
        decoLayer = document.createElement('div');
            Full/half contract:
        decoLayer.className = 'boot-gate-decoration-layer';
            These manifest tasks only prepare data assets. The gate is not allowed to open
        decoLayer.setAttribute('data-decoration-target', 'boot-gate');
            until the current page surface has consumed that data and reported a real ready
        decoLayer.setAttribute('aria-hidden', 'true');
            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) {
        panel.appendChild(header);
                maxBlockingMs = Number(options.maxBlockingMs || bootOptions.maxBlockingMs || 30000);
        panel.appendChild(bootStatusNode);
                timeoutHandle = window.setTimeout(function () {
        panel.appendChild(meter);
                    timedOut = true;
        panel.appendChild(bootProgressNode);
                    resolve();
        panel.appendChild(bootDetailNode);
                }, maxBlockingMs);
        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 = {};


                Promise.all(tasks.map(function (task) {
        if (pageName && !isAuthenticationPage() && !isCreateAccountPage()) params.returnto = pageName;
                    var label = task.label || task.id || task.type || 'entry task';
        try {
                    return prepareTask(task, task.level).catch(function () {
            if (mw && mw.util && typeof mw.util.getUrl === 'function') {
                        return null;
                 return mw.util.getUrl('Special:UserLogin', params);
                    }).then(function () {
             }
                        done += 1;
         } catch (err) {}
                        updateBootProgress(done, totalSteps, label);
                    });
                })).then(function () {
                    updateBootProgress(++done, totalSteps, 'loading subsystem scripts');
                    return waitForTrackedScripts();
                }).then(function () {
                    updateBootProgress(++done, totalSteps, 'waiting for document shell');
                    return waitForDocumentSurface();
                }).then(function () {
                    updateBootProgress(++done, totalSteps, 'waiting for current entry surface');
                    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'));
                window.setTimeout(hideBootScreen, 120);
                return manifest;
             });
         });


         return manifestRef;
         return '/index.php?title=Special%3AUserLogin' + (params.returnto ? '&returnto=' + encodeURIComponent(params.returnto) : '');
     }
     }


     function startBoot(options) {
     function ensureLoginGateAction(panel) {
         if (BOOT_EXCLUDED_PAGE && !(options && options.force)) {
         var copy;
            hideBootScreen();
        var action;
            return Promise.resolve({ skipped: true, reason: 'developer-or-editing-page' });
 
        }
         if (loginGateActionNode && loginGateActionNode.parentNode) return loginGateActionNode;
         if (hasBootParam('0') && !(options && options.force)) return Promise.resolve(null);
         loginGateActionNode = document.createElement('div');
         if (bootStarted && bootPromise && !(options && options.force)) return bootPromise;
         loginGateActionNode.className = 'boot-gate-login';
         bootStarted = true;
        bootPromise = runInitialLoad(options || {});
        return bootPromise;
    }


    function resetBoot() {
         copy = document.createElement('div');
         localStorage.removeItem(READY_KEY);
         copy.className = 'boot-gate-login-copy';
         bootStarted = false;
         copy.textContent = 'SIGN IN TO ENTER THE WIKI.';
         bootPromise = null;
    }


    /*
        action = document.createElement('a');
    BootGate intentionally has no SPA hold/release API.
        action.className = 'boot-gate-login-action';
    Initial boot is the only blocking phase; later SPA routes must consume prepared
        action.href = buildLoginUrl();
    EntryStore artifacts without reopening the loading surface.
        action.textContent = 'LOGIN';
    */
        action.setAttribute('role', 'button');


    function buildBootReport() {
         loginGateActionNode.appendChild(copy);
         return {
        loginGateActionNode.appendChild(action);
            build: BUILD_ID,
        panel.appendChild(loginGateActionNode);
            state: {
         return loginGateActionNode;
                started: bootStarted,
                excludedPage: BOOT_EXCLUDED_PAGE,
                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,
            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 || {
     function showLoginGate() {
         loadManifest: loadManifest,
         var node = ensureBootScreen();
         prepareTask: prepareTask,
         var panel;
         prepareNationsEra: prepareNationsEra,
         var title;
         prepareDecorationSet: prepareDecorationSet,
         var action;
        prepareGlobeSharedAssets: prepareGlobeSharedAssets,
        prepareHtmlEntry: prepareHtmlEntry,
        runInitialLoad: runInitialLoad
    };


    function showBootPreview(options) {
        if (!node || !requiresLoginGate()) return false;
        var node;
        options = options || {};
        BOOT_EXCLUDED_PAGE = false;
         activateBootSurface();
         activateBootSurface();
         node = ensureBootScreen();
        loginGateLocked = true;
         if (!node) return null;
         node.classList.remove('is-complete');
         node.classList.add('is-preview');
        node.classList.add('is-active', 'is-login-required');
         if (bootStatusNode) bootStatusNode.textContent = options.status || 'Loading screen preview';
        node.setAttribute('role', 'dialog');
         updateBootProgress(Number(options.progress || 64), 100, options.detail || 'preview mode: no entry tasks are running');
         node.setAttribute('aria-modal', 'true');
         try {
        node.setAttribute('aria-live', 'off');
             if (window.Decorations && typeof window.Decorations.sync === 'function') window.Decorations.sync();
 
        } catch (err) {}
         panel = node.querySelector('.boot-gate-panel');
         return node;
        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;
     }
     }


     window.BootGate = window.BootGate || {
     function hideBootScreen(options) {
        version: BUILD_ID,
        var node = bootNode || document.getElementById('boot-gate-screen');
        start: startBoot,
        options = options || {};
        show: function (options) {
        if (loginGateLocked && requiresLoginGate() && !options.force) return false;
            options = options || {};
        if (!node) {
            options.force = true;
             document.documentElement.classList.remove('boot-gate-active');
             resetBoot();
             if (document.body) document.body.classList.remove('boot-gate-active');
             return startBoot(options);
            return true;
         },
         }
         reset: resetBoot,
         node.classList.add('is-complete');
         hide: hideBootScreen,
         node.classList.remove('is-active');
         preview: showBootPreview,
         window.setTimeout(function () {
        report: buildBootReport,
             if (node.parentNode) node.parentNode.removeChild(node);
        state: function () {
            if (bootNode === node) bootNode = null;
             return {
            loginGateActionNode = null;
                started: bootStarted,
            document.documentElement.classList.remove('boot-gate-active');
                hasNode: !!((bootNode && bootNode.parentNode) || document.getElementById('boot-gate-screen')),
            if (document.body) document.body.classList.remove('boot-gate-active');
                htmlActive: !!(document.documentElement && document.documentElement.classList.contains('boot-gate-active')),
        }, 240);
                bodyActive: !!(document.body && document.body.classList.contains('boot-gate-active')),
        return true;
                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 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;
    function prime() {
             if (Array.isArray(item.flags)) item.flags.forEach(add);
        if (BOOT_EXCLUDED_PAGE) {
             add(item.flag_file || item.flag || item.flag_title || '');
             hideBootScreen();
             return;
         }
         }
         activateBootSurface();
         (payload && payload.continents || []).forEach(function (continent) {
        waitForBody().then(function () {
             (continent.regions || []).forEach(function (region) {
             ensureBootScreen();
                (region.items || []).forEach(scanItem);
            return waitForAnimationFrames(1);
             });
        }).then(function () {
             startBoot();
         });
         });
        return unique(files);
     }
     }


     waitForBody().then(function () {
     function collectFlagsFromLinkMap(payload) {
        if (!BOOT_EXCLUDED_PAGE) ensureBootScreen();
        var files = [];
        else hideBootScreen();
        var source = payload && payload.items ? payload.items : {};
    });
        Object.keys(source || {}).forEach(function (key) {
    window.setTimeout(prime, 0);
            var item = source[key];
})(window, document, window.mediaWiki || window.mw);
            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
        });
    }


loadClbiRawScript('MediaWiki:DevTools.js');
    function getDecorationRuntime() {
loadClbiRawScript('MediaWiki:CategoryNav.js');
        return window.Decorations || window.CLBI_DECORATIONS || null;
loadClbiRawScript('MediaWiki:NationsPanel.js');
    }
loadClbiRawScript('MediaWiki:NationsGlobe.js');


/* CLBI safety guard: adaptive reset functions must exist before shell metric callbacks run. */
    function waitForDecorationRuntime() {
function resetLeftRecentAdaptiveState() {
        return new Promise(function (resolve) {
    var list = document.getElementById('clbi-left-recent-list');
            var tries = 0;
    var newsBox = list ? list.closest('.clbi-left-news-box') : null;
            function tick() {
    var items = list ? Array.prototype.slice.call(list.querySelectorAll('.news-recent-item')) : [];
                var runtime = getDecorationRuntime();
 
                if (runtime) return resolve(runtime);
    if (newsBox) {
                tries += 1;
        newsBox.classList.remove('is-adaptive-constrained');
                if (tries > 40) return resolve(null);
         newsBox.style.removeProperty('--adaptive-news-h');
                window.setTimeout(tick, 25);
            }
            tick();
         });
     }
     }


     if (list) {
     function matchesDecorationEntry(entry, filter) {
         list.classList.remove('is-adaptive-faded');
         var era = String(filter && filter.era || '').trim();
         list.removeAttribute('data-adaptive-limit');
        var page = String(filter && filter.page || '').trim();
         list.style.removeProperty('--adaptive-recent-h');
         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;
     }
     }


     items.forEach(function (item) {
     function prepareDecorationSet(task, level) {
        item.classList.remove('is-adaptive-hidden');
        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 = [];
function resetLeftBillboardAdaptiveState() {
            list.forEach(function (entry) {
    var box = document.querySelector('#clbi-left-sidebar .left-billboard-box');
                var type = String(entry && entry.assetType || '').toLowerCase();
 
                var asset = String(entry && (entry.asset || entry.src) || '').trim();
    if (!box) return;
                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; });
            });
        });
    }


     box.classList.remove('is-left-ad-title-only', 'is-left-ad-extended');
     function prepareNationsEra(task, level) {
    box.style.removeProperty('--left-billboard-h');
        var era = String(task.era || '1950');
    box.style.removeProperty('--left-billboard-finish-h');
        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; });


window.resetLeftRecentAdaptiveState = resetLeftRecentAdaptiveState;
        return Promise.all([listPromise, linkPromise]).then(function (results) {
window.resetLeftBillboardAdaptiveState = resetLeftBillboardAdaptiveState;
            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;
            });
        });
    }


loadClbiRawScript('MediaWiki:AnecdoteViewer.js');
    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 () {
    function prepareHtmlEntry(task) {
    'use strict';
        var url = String(task && (task.url || task.ref) || '').trim();
 
        if (!url) return Promise.resolve(null);
    var SYSTEM_TITLE_NAMESPACES = {
        return window.EntryStore.fetchTextUrl(url, { noStore: !!task.noStore, resourceRef: task.resourceRef || task.ref || task.title || '' });
        '-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() {
     function prepareTask(task, defaultLevel) {
         var pageName = mw.config.get('wgPageName') || '';
         var level = String(task && (task.level || defaultLevel) || 'half').toLowerCase();
 
        var type = String(task && task.type || '').toLowerCase();
         if (pageName) {
        if (!task || typeof task !== 'object') return Promise.resolve(null);
             return normalizePageNameForShell(pageName);
        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);
    }


         return normalizePageNameForShell(window.location.pathname || '');
    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 isAnecdoteNamespaceForShell() {
     function flattenInitialTasks(manifest) {
         var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
         var initial = manifest && manifest.initial ? manifest.initial : {};
         var canonicalNamespace = String(mw.config.get('wgCanonicalNamespace') || '').toLowerCase();
        var full = Array.isArray(initial.full) ? initial.full : [];
        var pageName = readCurrentPageNameForShell();
        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;


        return namespaceNumber === 3000 ||
            /*
             canonicalNamespace === 'anecdote' ||
            * Warm boot fast path — 20260708.
             /^(anecdote|에넥도트):/i.test(pageName);
            *
            * 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 isBackendOrSystemPageForShell() {
     function currentInitialPackKey(manifest) {
         var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
         var version = manifest && manifest.version ? String(manifest.version) : BUILD_ID;
        var action = String(mw.config.get('wgAction') || 'view').toLowerCase();
         return 'initial-entry-full:' + version;
         var contentModel = String(mw.config.get('wgPageContentModel') || '').toLowerCase();
    }
        var pageName = readCurrentPageNameForShell();
        var lowerPageName = pageName.toLowerCase();


         if (action && action !== 'view') {
    function currentInitialPackToken(manifest) {
            return true;
         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;
    }


         if (pageName === '대문') {
    function isInitialPackWarm(manifest) {
            return false;
         var key = currentInitialPackKey(manifest);
        }
        var token = currentInitialPackToken(manifest);
        return !!(window.EntryCache && typeof window.EntryCache.packReady === 'function' && window.EntryCache.packReady(key, token));
    }


        if (SYSTEM_TITLE_NAMESPACES[String(namespaceNumber)]) {
    function markInitialPackWarm(manifest, meta) {
            return true;
        var key = currentInitialPackKey(manifest);
         }
         var token = currentInitialPackToken(manifest);
 
         if (window.EntryCache && typeof window.EntryCache.setPackReady === 'function') {
         if (contentModel === 'css' || contentModel === 'javascript' || contentModel === 'json' || contentModel === 'sanitized-css') {
            window.EntryCache.setPackReady(key, token, Object.assign({ manifestVersion: manifest && manifest.version || BUILD_ID }, meta || {}));
            return true;
         }
         }
    }


        if (/\.(css|js|json)$/i.test(pageName)) {
            return true;
        }


         if (/^(mediawiki|미디어위키|special|특수):/i.test(pageName)) {
    function waitMs(ms) {
            return true;
         return new Promise(function (resolve) { window.setTimeout(resolve, Math.max(0, ms || 0)); });
        }
    }


         return false;
    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 isMediaWikiSystemAssetPageForShell() {
     function waitForDomReady() {
         var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
         if (document.readyState !== 'loading') return Promise.resolve();
        var pageName = readCurrentPageNameForShell();
         return new Promise(function (resolve) {
        var contentModel = String(mw.config.get('wgPageContentModel') || '').toLowerCase();
            document.addEventListener('DOMContentLoaded', resolve, { once: true });
 
        });
         return namespaceNumber === 8 &&
            (/\.(css|js)$/i.test(pageName) || contentModel === 'css' || contentModel === 'javascript' || contentModel === 'sanitized-css');
     }
     }


 
     function waitForAnimationFrames(count) {
    var systemDocRawFetchToken = 0;
         count = Math.max(1, Math.round(count || 1));
 
        return new Promise(function (resolve) {
     function cleanupLegacySystemDocCodeMutationsForShell() {
             function next(left) {
         document.querySelectorAll('.clbi-system-doc-codepane').forEach(function (pane) {
                if (left <= 0) return resolve();
             var parent;
                window.requestAnimationFrame(function () { next(left - 1); });
 
            if (!pane || !pane.parentNode) return;
 
            parent = pane.parentNode;
            while (pane.firstChild) {
                parent.insertBefore(pane.firstChild, pane);
             }
             }
             parent.removeChild(pane);
             next(count);
         });
         });
    }


         document.querySelectorAll('.clbi-system-doc-codebox').forEach(function (node) {
    function waitUntil(predicate, options) {
             node.classList.remove('clbi-system-doc-codebox');
        var started = now();
            node.removeAttribute('data-clbi-system-doc-codebox');
         var timeout = options && options.timeoutMs ? options.timeoutMs : 8000;
             node.removeAttribute('style');
        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 getSystemDocOutputForShell() {
     function waitForTrackedScripts() {
         return document.querySelector('.liberty-content-main .mw-parser-output');
         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 findSystemDocSourceNodeForShell() {
     function waitForDocumentSurface() {
         var output = getSystemDocOutputForShell();
         return waitForDomReady().then(function () {
         var children;
            return waitForBody();
         var preferred;
         }).then(function () {
            return waitUntil(function () {
                return document.querySelector('.content-wrapper') && document.querySelector('.liberty-content-main');
            }, { timeoutMs: 8000, intervalMs: 50 });
         });
    }


         if (!output) return null;
    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);
    }


         children = Array.prototype.slice.call(output.children || [])
    function getInitialNationsEra(manifest) {
            .filter(function (el) {
         var tasks = flattenInitialTasks(manifest);
                return el && el.nodeType === 1 &&
        var i;
                    el.id !== 'clbi-system-doc-indicator-row' &&
        for (i = 0; i < tasks.length; i += 1) {
                    el.id !== 'clbi-system-source-viewer' &&
            if (tasks[i] && tasks[i].type === 'nations-era' && String(tasks[i].level || '').toLowerCase() === 'full') {
                    !el.classList.contains('catlinks') &&
                return String(tasks[i].era || '1950');
                    (el.textContent || '').trim().length > 200;
             }
             });
         }
 
         return '1950';
        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() {
     function waitForNationsPanelReady(era) {
         var title = mw.config.get('wgPageName') || readCurrentPageNameForShell();
         return BootPerf.measure('wait nations panel api', { era: era }, function () {
 
            return waitUntil(function () { return window.NationsPanel && typeof window.NationsPanel.whenEraReady === 'function'; }, {
         if (window.mw && mw.util && typeof mw.util.getUrl === 'function') {
                timeoutMs: 8000,
             return mw.util.getUrl(title, {
                intervalMs: 50
                 action: 'raw',
            });
                 ctype: 'text/plain',
         }).then(function (result) {
                _: String(Date.now())
            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 });
             });
             });
         }
         });
 
        return '/index.php?title=' + encodeURIComponent(title) + '&action=raw&ctype=text/plain&_=' + Date.now();
     }
     }


     function removeSystemDocSourceViewerForShell() {
     function waitForNationsGlobeReady(options) {
         var viewer = document.getElementById('clbi-system-source-viewer');
         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 (viewer && viewer.parentNode) {
         if (!globe) {
             viewer.parentNode.removeChild(viewer);
             BootPerf.mark('wait nations globe skipped', { reason: 'no globe node', soft: soft });
            return Promise.resolve(null);
         }
         }


         document.querySelectorAll('.clbi-system-original-source-hidden').forEach(function (node) {
         return BootPerf.measure(soft ? 'wait nations globe warm attach' : 'wait nations globe ready contract', { soft: soft, timeoutMs: timeout }, function () {
            node.classList.remove('clbi-system-original-source-hidden');
            if (soft) {
             node.removeAttribute('data-clbi-system-source-hidden');
                /*
            node.style.removeProperty('display');
                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 });
         });
         });
    }


         cleanupLegacySystemDocCodeMutationsForShell();
    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 ensureSystemDocSourceViewerForShell() {
     function waitForCurrentEntrySurface(manifest, options) {
         var output = getSystemDocOutputForShell();
         var era = getInitialNationsEra(manifest);
         var source;
         var warmPack;
        var viewer;
        var fallbackText;


         if (!output || !isMediaWikiSystemAssetPageForShell()) return null;
         options = options || {};
        warmPack = !!options.warmPack;


         cleanupLegacySystemDocCodeMutationsForShell();
         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); });
    }


         source = findSystemDocSourceNodeForShell();
    function runDeferredEntryWarmups() {
         if (!source) return null;
         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);
    }


         viewer = document.getElementById('clbi-system-source-viewer');
    function runInitialLoad(options) {
 
         var done = 0;
         if (!viewer) {
        var manifestRef;
            viewer = document.createElement('pre');
         var tasks;
            viewer.id = 'clbi-system-source-viewer';
        var bootOptions;
            viewer.className = 'clbi-system-source-viewer';
        var timedOut = false;
            output.appendChild(viewer);
        var warmPack = false;
        }


         fallbackText = source.textContent || '';
         options = options || {};
        bootStartTime = window.__BootGatePrelude && window.__BootGatePrelude.startTime ? window.__BootGatePrelude.startTime : now();
        activateBootSurface();
        ensureBootScreen();
        updateBootProgress(0, 1, 'loading entry manifest');


         if (!viewer.textContent && fallbackText) {
         manifestRef = loadManifest().then(function (manifest) {
             viewer.textContent = fallbackText;
             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);


        source.classList.add('clbi-system-original-source-hidden');
            /*
        source.setAttribute('data-clbi-system-source-hidden', 'true');
            Full/half contract:
        source.style.setProperty('display', 'none', 'important');
            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 viewer;
            return new Promise(function (resolve) {
    }
                maxBlockingMs = Number(options.maxBlockingMs || bootOptions.maxBlockingMs || 30000);
                timeoutHandle = window.setTimeout(function () {
                    timedOut = true;
                    resolve();
                }, maxBlockingMs);


    function renderSystemDocSourceViewerForShell() {
                Promise.all(tasks.map(function (task) {
        var viewer;
                    var label = task.label || task.id || task.type || 'entry task';
        var pageName;
                    return BootPerf.measure('boot task: ' + label, { id: task.id || '', type: task.type || '', level: task.level || task.level === 0 ? task.level : '' }, function () {
        var token;
                        return prepareTask(task, task.level);
        var currentScrollTop;
                    }).catch(function () {
 
                        return null;
        if (!isMediaWikiSystemAssetPageForShell()) return;
                    }).then(function () {
 
                        done += 1;
        pageName = String(mw.config.get('wgPageName') || readCurrentPageNameForShell());
                        updateBootProgress(done, totalSteps, label);
        viewer = document.getElementById('clbi-system-source-viewer');
                    });
                })).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) {
        시스템 문서 뷰어가 이미 만들어져 있고 raw 원문도 로드된 상태라면
         if (BOOT_EXCLUDED_PAGE && !(options && options.force)) {
        다시 source 탐색/숨김/스타일 재적용을 하지 않는다.
             hideBootScreen();
        DevTools Elements 패널에서 body가 계속 파랗게 깜빡이던 원인은
             return Promise.resolve({ skipped: true, reason: 'developer-or-editing-page' });
        MutationObserver가 이 재적용을 반복해서 DOM attribute mutation을 만들었기 때문이다.
        */
         if (
            viewer &&
             viewer.getAttribute('data-clbi-raw-title') === pageName &&
             viewer.getAttribute('data-clbi-raw-loaded') === '1'
        ) {
            return;
         }
         }
        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;
    }


         viewer = ensureSystemDocSourceViewerForShell();
    function resetBoot() {
         if (!viewer) return;
         localStorage.removeItem(READY_KEY);
         bootStarted = false;
        bootPromise = null;
        loginGateLocked = false;
    }


        currentScrollTop = viewer.scrollTop || 0;
    /*
        viewer.setAttribute('data-clbi-raw-title', pageName);
    BootGate intentionally has no SPA hold/release API.
        token = ++systemDocRawFetchToken;
    Initial boot is the only blocking phase; later SPA routes must consume prepared
    EntryStore artifacts without reopening the loading surface.
    */


         fetch(getSystemDocRawUrlForShell(), { credentials: 'same-origin' })
    function buildBootReport() {
            .then(function (res) {
         return {
                 if (!res.ok) throw new Error('raw fetch failed ' + res.status);
            build: BUILD_ID,
                return res.text();
            state: {
             })
                started: bootStarted,
             .then(function (text) {
                excludedPage: BOOT_EXCLUDED_PAGE,
                if (token !== systemDocRawFetchToken) return;
                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
        };
    }


                currentScrollTop = viewer.scrollTop || currentScrollTop || 0;
    window.EntryLoader = window.EntryLoader || {
        loadManifest: loadManifest,
        prepareTask: prepareTask,
        prepareNationsEra: prepareNationsEra,
        prepareDecorationSet: prepareDecorationSet,
        prepareGlobeSharedAssets: prepareGlobeSharedAssets,
        prepareImageAssets: prepareImageAssets,
        prepareHtmlEntry: prepareHtmlEntry,
        runInitialLoad: runInitialLoad
    };


                if (text && viewer.textContent !== text) {
    function showBootPreview(options) {
                    viewer.textContent = text;
        var node;
                }
        options = options || {};
 
        /*
                viewer.setAttribute('data-clbi-raw-loaded', '1');
        * Boot preview is a design/editing surface, not a real boot gate.
                viewer.scrollTop = currentScrollTop;
        * The earlier preview reused activateBootSurface(), which applied
            })
        * html.boot-gate-active and hid the entire wiki shell, including
            .catch(function () {
        * DevTools.  That made it impossible to edit loading-screen
                viewer.setAttribute('data-clbi-raw-loaded', '0');
        * 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;
     }
     }


     function removeSystemDocIndicatorForShell() {
     window.BootGate = window.BootGate || {
         var existing = document.getElementById('clbi-system-doc-indicator-row');
        version: BUILD_ID,
 
        start: startBoot,
        if (document.body) {
        show: function (options) {
            document.body.classList.remove('clbi-system-doc-page');
            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
            };
         }
         }
    };


         if (existing && existing.parentNode) {
    function prime() {
             existing.parentNode.removeChild(existing);
         if (BOOT_EXCLUDED_PAGE) {
             hideBootScreen();
            return;
         }
         }
 
        activateBootSurface();
         removeSystemDocSourceViewerForShell();
        waitForBody().then(function () {
            ensureBootScreen();
            return waitForAnimationFrames(1);
         }).then(function () {
            startBoot();
        });
     }
     }


     function renderSystemDocIndicatorForShell() {
     waitForBody().then(function () {
         var pageName;
         if (!BOOT_EXCLUDED_PAGE) ensureBootScreen();
         var extMatch;
         else hideBootScreen();
        var ext;
    });
        var row;
    window.setTimeout(prime, 0);
        var box;
})(window, document, window.mediaWiki || window.mw);
        var meta;
        var label;
        var type;
        var title;
        var anchor;
        var main;


        if (!document.body || !isMediaWikiSystemAssetPageForShell()) return;


        pageName = readCurrentPageNameForShell();
loadClbiRawScript('MediaWiki:DevTools.js');
        extMatch = pageName.match(/\.(css|js)$/i);
loadClbiRawScript('MediaWiki:NationsPanel.js');
        ext = extMatch ? extMatch[1].toUpperCase() : 'DOC';
loadClbiRawScript('MediaWiki:NationsGlobe.js');


        document.body.classList.add('clbi-system-doc-page');
/* 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')) : [];


         row = document.getElementById('clbi-system-doc-indicator-row');
    if (newsBox) {
         newsBox.classList.remove('is-adaptive-constrained');
        newsBox.style.removeProperty('--adaptive-news-h');
    }


        if (!row) {
    if (list) {
            row = document.createElement('div');
        list.classList.remove('is-adaptive-faded');
            row.id = 'clbi-system-doc-indicator-row';
        list.removeAttribute('data-adaptive-limit');
            row.className = 'clbi-system-doc-indicator-row';
        list.style.removeProperty('--adaptive-recent-h');
    }


            box = document.createElement('div');
    items.forEach(function (item) {
            box.className = 'clbi-system-doc-indicator';
        item.classList.remove('is-adaptive-hidden');
    });
}


            meta = document.createElement('div');
function resetLeftBillboardAdaptiveState() {
            meta.className = 'clbi-system-doc-meta';
    var box = document.querySelector('#clbi-left-sidebar .left-billboard-box');


            label = document.createElement('span');
    if (!box) return;
            label.className = 'clbi-system-doc-label';
            label.textContent = 'SYSTEM DOCUMENT';


            type = document.createElement('span');
    box.classList.remove('is-left-ad-title-only', 'is-left-ad-extended');
            type.className = 'clbi-system-doc-type';
    box.style.removeProperty('--left-billboard-h');
    box.style.removeProperty('--left-billboard-finish-h');
}


            title = document.createElement('div');
window.resetLeftRecentAdaptiveState = resetLeftRecentAdaptiveState;
            title.className = 'clbi-system-doc-title';
window.resetLeftBillboardAdaptiveState = resetLeftBillboardAdaptiveState;


            meta.appendChild(label);
loadClbiRawScript('MediaWiki:AnecdoteViewer.js');
            meta.appendChild(type);
            box.appendChild(meta);
            box.appendChild(title);
            row.appendChild(box);


            anchor = getSystemDocOutputForShell();
            main = document.querySelector('.liberty-content-main');


            if (anchor && anchor.parentNode) {
(function () {
                anchor.parentNode.insertBefore(row, anchor);
    'use strict';
            } else if (main) {
                main.insertBefore(row, main.firstChild);
            }
        }


         type = row.querySelector('.clbi-system-doc-type');
    var SYSTEM_TITLE_NAMESPACES = {
         title = row.querySelector('.clbi-system-doc-title');
         '-1': true,
 
        '4': true,
         if (type) type.textContent = ext;
        '5': true,
        if (title) title.textContent = pageName;
        '6': true,
 
        '7': true,
        renderSystemDocSourceViewerForShell();
        '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();
     }
     }


     var PAGE_TITLE_TARGET_SELECTORS = [
     function readCurrentPageNameForShell() {
        '.liberty-content-header',
        var pageName = mw.config.get('wgPageName') || '';
        '.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;
        if (pageName) {
    var pageShellObserverTimer = null;
            return normalizePageNameForShell(pageName);
        }


    function setPageTitleDomHidden(hidden) {
        return normalizePageNameForShell(window.location.pathname || '');
        var nodes = document.querySelectorAll(PAGE_TITLE_TARGET_SELECTORS.join(','));
    }


         nodes.forEach(function (node) {
    function isAnecdoteNamespaceForShell() {
            if (!node || !node.style) return;
         var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
        var canonicalNamespace = String(mw.config.get('wgCanonicalNamespace') || '').toLowerCase();
        var pageName = readCurrentPageNameForShell();


            if (hidden) {
        return namespaceNumber === 3000 ||
                node.setAttribute('data-clbi-title-hidden', 'true');
             canonicalNamespace === 'anecdote' ||
                node.style.setProperty('display', 'none', 'important');
            /^(anecdote|에넥도트):/i.test(pageName);
             } else if (node.getAttribute('data-clbi-title-hidden') === 'true') {
                node.removeAttribute('data-clbi-title-hidden');
                node.style.removeProperty('display');
            }
        });
     }
     }


     function applyPageShellClasses() {
     function isBackendOrSystemPageForShell() {
         var body = document.body;
         var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
         var isSystemPage;
        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 (!body) return;
         if (action && action !== 'view') {
            return true;
        }


         isSystemPage = isBackendOrSystemPageForShell();
         if (pageName === '대문') {
            return false;
        }


         body.classList.remove('page-title-hidden', 'page-title-visible', 'backend-system-page', 'anecdote-namespace-page');
         if (SYSTEM_TITLE_NAMESPACES[String(namespaceNumber)]) {
            return true;
        }


         if (!isMediaWikiSystemAssetPageForShell()) {
         if (contentModel === 'css' || contentModel === 'javascript' || contentModel === 'json' || contentModel === 'sanitized-css') {
            body.classList.remove('clbi-system-doc-page');
             return true;
             removeSystemDocIndicatorForShell();
         }
         }


         if (isAnecdoteNamespaceForShell()) {
         if (/\.(css|js|json)$/i.test(pageName)) {
             body.classList.add('anecdote-namespace-page');
             return true;
         }
         }


         if (isMediaWikiSystemAssetPageForShell()) {
         if (/^(mediawiki|미디어위키|special|특수):/i.test(pageName)) {
            body.classList.add('page-title-hidden', 'backend-system-page', 'clbi-system-doc-page');
             return true;
            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 false;
     }
     }


     function applyPageShellClassesDeferred() {
     function isMediaWikiSystemAssetPageForShell() {
         applyPageShellClasses();
         var namespaceNumber = Number(mw.config.get('wgNamespaceNumber'));
         window.setTimeout(applyPageShellClasses, 0);
         var pageName = readCurrentPageNameForShell();
         window.setTimeout(applyPageShellClasses, 80);
         var contentModel = String(mw.config.get('wgPageContentModel') || '').toLowerCase();
         window.setTimeout(applyPageShellClasses, 250);
 
         return namespaceNumber === 8 &&
            (/\.(css|js)$/i.test(pageName) || contentModel === 'css' || contentModel === 'javascript' || contentModel === 'sanitized-css');
     }
     }


    function startPageShellObserver() {
        var observer;


         if (pageShellObserverStarted || !window.MutationObserver || !document.body) return;
    var systemDocRawFetchToken = 0;
 
    function cleanupLegacySystemDocCodeMutationsForShell() {
         document.querySelectorAll('.clbi-system-doc-codepane').forEach(function (pane) {
            var parent;


        pageShellObserverStarted = true;
            if (!pane || !pane.parentNode) return;
        observer = new MutationObserver(function (mutations) {
            var i;
            var target;


             /*
             parent = pane.parentNode;
            시스템 CSS/JS 문서는 applyPageShellClasses()가 초기에 한 번
             while (pane.firstChild) {
            인디케이터와 source viewer를 만든 뒤에는 MutationObserver가 다시
                 parent.insertBefore(pane.firstChild, pane);
            같은 렌더링을 반복할 필요가 없다. 이 반복이 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;
                }
             }
             }
 
             parent.removeChild(pane);
             if (pageShellObserverTimer) return;
 
            pageShellObserverTimer = window.setTimeout(function () {
                pageShellObserverTimer = null;
                applyPageShellClasses();
            }, 50);
         });
         });


         observer.observe(document.body, {
         document.querySelectorAll('.clbi-system-doc-codebox').forEach(function (node) {
             childList: true,
             node.classList.remove('clbi-system-doc-codebox');
             subtree: true
            node.removeAttribute('data-clbi-system-doc-codebox');
             node.removeAttribute('style');
         });
         });
     }
     }


     if (document.readyState === 'loading') {
     function getSystemDocOutputForShell() {
         document.addEventListener('DOMContentLoaded', function () {
         return document.querySelector('.liberty-content-main .mw-parser-output');
            applyPageShellClassesDeferred();
            startPageShellObserver();
        });
    } else {
        applyPageShellClassesDeferred();
        startPageShellObserver();
     }
     }


     if (mw.hook) {
     function findSystemDocSourceNodeForShell() {
         mw.hook('wikipage.content').add(applyPageShellClassesDeferred);
         var output = getSystemDocOutputForShell();
    }
        var children;
        var preferred;
 
        if (!output) return null;


    window.CLBI_PAGE_SHELL = {
        children = Array.prototype.slice.call(output.children || [])
        refresh: applyPageShellClasses,
            .filter(function (el) {
        isBackendOrSystemPage: isBackendOrSystemPageForShell,
                return el && el.nodeType === 1 &&
        isSystemAssetPage: isMediaWikiSystemAssetPageForShell,
                    el.id !== 'clbi-system-doc-indicator-row' &&
        renderSystemDocIndicator: renderSystemDocIndicatorForShell,
                    el.id !== 'clbi-system-source-viewer' &&
        removeSystemDocIndicator: removeSystemDocIndicatorForShell,
                    !el.classList.contains('catlinks') &&
        refreshSystemDocSourceViewer: renderSystemDocSourceViewerForShell
                    (el.textContent || '').trim().length > 200;
    };
            });
}());


function loadLangScript(done) {
        preferred = children.filter(function (el) {
    $.getScript('/index.php?title=미디어위키:Lang.js&action=raw&ctype=text/javascript')
             return el.matches && el.matches('.mw-highlight, .mw-code, pre');
        .done(function() {
         })[0];
             if (typeof done === 'function') done();
        })
        .fail(function(a, b, c) {
            console.error('Lang.js load failed:', b, c);
            if (typeof done === 'function') done();
         });
}


        return preferred || children.sort(function (a, b) {
            return (b.textContent || '').trim().length - (a.textContent || '').trim().length;
        })[0] || null;
    }


function initHalftoneBackground() {
    function getSystemDocRawUrlForShell() {
    try {
         var title = mw.config.get('wgPageName') || readCurrentPageNameForShell();
         initWebGLHalftoneBackground();
         var url;
    } catch (err) {
         console.error('WebGL halftone background failed:', err);
    }
}


function initWebGLHalftoneBackground() {
        if (window.mw && mw.util && typeof mw.util.getUrl === 'function') {
    var canvasId = 'site-halftone-bg';
            url = mw.util.getUrl(title, {
    var existing = document.getElementById(canvasId);
                action: 'raw',
    var canvas = existing || document.createElement('canvas');
                ctype: 'text/plain'
            });
        } else {
            url = '/index.php?title=' + encodeURIComponent(title) + '&action=raw&ctype=text/plain';
        }


    if (!existing) {
        if (window.RevisionManifest && typeof window.RevisionManifest.addRevisionParam === 'function') {
        canvas.id = canvasId;
            url = window.RevisionManifest.addRevisionParam(url, title);
        canvas.setAttribute('aria-hidden', 'true');
         }
         document.body.insertBefore(canvas, document.body.firstChild || null);
        return url;
     }
     }


     canvas.style.position = 'fixed';
     function removeSystemDocSourceViewerForShell() {
    canvas.style.inset = '0';
        var viewer = document.getElementById('clbi-system-source-viewer');
    canvas.style.width = '100vw';
    canvas.style.height = '100vh';
    canvas.style.pointerEvents = 'none';
    canvas.style.background = '#000000';


    var gl = canvas.getContext('webgl', {
        if (viewer && viewer.parentNode) {
        alpha: false,
            viewer.parentNode.removeChild(viewer);
         antialias: false,
         }
        depth: false,
 
         stencil: false,
         document.querySelectorAll('.clbi-system-original-source-hidden').forEach(function (node) {
        preserveDrawingBuffer: false,
            node.classList.remove('clbi-system-original-source-hidden');
        powerPreference: 'high-performance'
            node.removeAttribute('data-clbi-system-source-hidden');
    }) || canvas.getContext('experimental-webgl');
            node.style.removeProperty('display');
        });


    if (!gl) {
         cleanupLegacySystemDocCodeMutationsForShell();
         console.warn('WebGL background unavailable.');
        return;
     }
     }


     var vertexSrc = [
     function ensureSystemDocSourceViewerForShell() {
         'attribute vec2 a_position;',
        var output = getSystemDocOutputForShell();
         'void main() {',
         var source;
         '  gl_Position = vec4(a_position, 0.0, 1.0);',
        var viewer;
        '}'
        var fallbackText;
    ].join('\n');
 
        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 || '';


    var fragmentSrc = [
         if (!viewer.textContent && fallbackText) {
        'precision mediump float;',
            viewer.textContent = fallbackText;
        '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) {
        source.classList.add('clbi-system-original-source-hidden');
        var shader = gl.createShader(type);
         source.setAttribute('data-clbi-system-source-hidden', 'true');
         gl.shaderSource(shader, source);
         source.style.setProperty('display', 'none', 'important');
         gl.compileShader(shader);


         if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
         return viewer;
            console.error('WebGL shader compile error:', gl.getShaderInfoLog(shader));
            gl.deleteShader(shader);
            return null;
        }
 
        return shader;
     }
     }


     var vertexShader = compileShader(gl.VERTEX_SHADER, vertexSrc);
     function renderSystemDocSourceViewerForShell() {
    var fragmentShader = compileShader(gl.FRAGMENT_SHADER, fragmentSrc);
        var viewer;
        var pageName;
        var token;
        var currentScrollTop;


    if (!vertexShader || !fragmentShader) return;
        if (!isMediaWikiSystemAssetPageForShell()) return;


    var program = gl.createProgram();
        pageName = String(mw.config.get('wgPageName') || readCurrentPageNameForShell());
    gl.attachShader(program, vertexShader);
        viewer = document.getElementById('clbi-system-source-viewer');
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);


    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        /*
        console.error('WebGL program link error:', gl.getProgramInfoLog(program));
        시스템 문서 뷰어가 이미 만들어져 있고 raw 원문도 로드된 상태라면
        return;
        다시 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;
        }


    var positionLoc = gl.getAttribLocation(program, 'a_position');
        viewer = ensureSystemDocSourceViewerForShell();
    var resolutionLoc = gl.getUniformLocation(program, 'u_resolution');
        if (!viewer) return;
    var timeLoc = gl.getUniformLocation(program, 'u_time');


    var buffer = gl.createBuffer();
        currentScrollTop = viewer.scrollTop || 0;
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
        viewer.setAttribute('data-clbi-raw-title', pageName);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
         token = ++systemDocRawFetchToken;
        -1, -1,
        1, -1,
         -1,  1,
        -1,  1,
        1, -1,
        1,  1
    ]), gl.STATIC_DRAW);


    gl.useProgram(program);
        fetch(getSystemDocRawUrlForShell(), { credentials: 'same-origin' })
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
            .then(function (res) {
    gl.enableVertexAttribArray(positionLoc);
                if (!res.ok) throw new Error('raw fetch failed ' + res.status);
    gl.vertexAttribPointer(positionLoc, 2, gl.FLOAT, false, 0, 0);
                return res.text();
            })
            .then(function (text) {
                if (token !== systemDocRawFetchToken) return;
 
                currentScrollTop = viewer.scrollTop || currentScrollTop || 0;


    function resize() {
                if (text && viewer.textContent !== text) {
        var dpr = Math.min(window.devicePixelRatio || 1, 1.5);
                    viewer.textContent = text;
        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) {
                viewer.setAttribute('data-clbi-raw-loaded', '1');
            canvas.width = w;
                viewer.scrollTop = currentScrollTop;
             canvas.height = h;
             })
             canvas.style.width = cssW + 'px';
             .catch(function () {
            canvas.style.height = cssH + 'px';
                viewer.setAttribute('data-clbi-raw-loaded', '0');
             gl.viewport(0, 0, w, h);
             });
        }
     }
     }


     var prefersReducedMotion = false;
     function removeSystemDocIndicatorForShell() {
    try {
         var existing = document.getElementById('clbi-system-doc-indicator-row');
         prefersReducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    } catch (err) {}


    var lastFrame = 0;
        if (document.body) {
    var frameInterval = prefersReducedMotion ? 1000 : 66;
            document.body.classList.remove('clbi-system-doc-page');
    var startTime = performance.now();
        }


    function render(now) {
        if (existing && existing.parentNode) {
        requestAnimationFrame(render);
            existing.parentNode.removeChild(existing);
         if (document.hidden) return;
         }
        if (now - lastFrame < frameInterval) return;


         lastFrame = now;
         removeSystemDocSourceViewerForShell();
        resize();
    }


        gl.clearColor(0, 0, 0, 1);
    function renderSystemDocIndicatorForShell() {
         gl.clear(gl.COLOR_BUFFER_BIT);
        var pageName;
         gl.uniform2f(resolutionLoc, canvas.width, canvas.height);
        var extMatch;
         gl.uniform1f(timeLoc, now - startTime);
        var ext;
         gl.drawArrays(gl.TRIANGLES, 0, 6);
        var row;
    }
        var box;
        var meta;
         var label;
         var type;
         var title;
         var anchor;
        var main;


    resize();
        if (!document.body || !isMediaWikiSystemAssetPageForShell()) return;
    requestAnimationFrame(render);
}


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>';
        pageName = readCurrentPageNameForShell();
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>';
        extMatch = pageName.match(/\.(css|js)$/i);
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>';
        ext = extMatch ? extMatch[1].toUpperCase() : 'DOC';
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;
        document.body.classList.add('clbi-system-doc-page');


function invalidateProfileRender() {
        row = document.getElementById('clbi-system-doc-indicator-row');
    PROFILE_RENDER_TOKEN++;
}


$(function() {
        if (!row) {
    initHalftoneBackground();
            row = document.createElement('div');
            row.id = 'clbi-system-doc-indicator-row';
            row.className = 'clbi-system-doc-indicator-row';


// ── 하단 Plank 단축키 가이드 ──
            box = document.createElement('div');
function escapeClbiBottomGuideHtml(value) {
            box.className = 'clbi-system-doc-indicator';
    return String(value == null ? '' : value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}


function readClbiBottomGuidePageName() {
            meta = document.createElement('div');
    var pageName = window.mw && mw.config ? (mw.config.get('wgPageName') || '') : '';
            meta.className = 'clbi-system-doc-meta';


    if (!pageName) {
            label = document.createElement('span');
        pageName = window.location.pathname || '';
            label.className = 'clbi-system-doc-label';
    }
            label.textContent = 'SYSTEM DOCUMENT';


    return String(pageName)
            type = document.createElement('span');
        .split('?')[0]
            type.className = 'clbi-system-doc-type';
        .replace(/^\/index\.php\//, '')
        .replace(/_/g, ' ')
        .trim();
}


function isClbiNationsShortcutContext() {
            title = document.createElement('div');
    var pageName = readClbiBottomGuidePageName();
            title.className = 'clbi-system-doc-title';


    return pageName === '국가 및 조합' ||
            meta.appendChild(label);
        pageName === 'Nations & Factions' ||
            meta.appendChild(type);
        !!document.querySelector('.clbi-nations-panel-stack, .clbi-nations-globe-window, .clbi-nations-tabpanel');
            box.appendChild(meta);
}
            box.appendChild(title);
            row.appendChild(box);


function isClbiWikiEditShortcutContext() {
            anchor = getSystemDocOutputForShell();
    var action = window.mw && mw.config ? String(mw.config.get('wgAction') || '') : '';
            main = document.querySelector('.liberty-content-main');
    var search = String(window.location.search || '');


    return action === 'edit' ||
            if (anchor && anchor.parentNode) {
        action === 'submit' ||
                anchor.parentNode.insertBefore(row, anchor);
        /(?:^|[?&])action=(?:edit|submit)(?:&|$)/.test(search) ||
            } else if (main) {
        !!document.querySelector('#editform, #wpSave, input[name="wpSave"], button[name="wpSave"]');
                main.insertBefore(row, main.firstChild);
}
            }
        }


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


function isClbiNationListManagerShortcutContext() {
        if (type) type.textContent = ext;
    return !!document.querySelector('.nation-list-manager');
        if (title) title.textContent = pageName;
}


function getClbiBottomShortcutItems() {
        renderSystemDocSourceViewerForShell();
    if (isClbiWikiEditShortcutContext()) {
        return [
            { key: 'Ctrl+S', label: '변경사항 저장' }
        ];
     }
     }


    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'
    ];


     if (isClbiNationListManagerShortcutContext()) {
     var pageShellObserverStarted = false;
        return [
     var pageShellObserverTimer = null;
            { key: 'Ctrl+S', label: '국가 목록 저장' }
        ];
     }


     if (isClbiNationsShortcutContext()) {
     function setPageTitleDomHidden(hidden) {
         return [
         var nodes = document.querySelectorAll(PAGE_TITLE_TARGET_SELECTORS.join(','));
            { key: 'Q', label: '이전 시대' },
            { key: 'E', label: '다음 시대' },
            { key: 'Shift+Q', label: '이전 연도' },
            { key: 'Shift+E', label: '다음 연도' },
            { key: 'Ctrl+Q', label: '이전 대륙' },
            { key: 'Ctrl+E', label: '다음 대륙' }
        ];
    }


    return [];
        nodes.forEach(function (node) {
}
            if (!node || !node.style) return;


function renderClbiBottomShortcutGuide() {
            if (hidden) {
    var guide = document.getElementById('clbi-bottom-shortcut-guide');
                node.setAttribute('data-clbi-title-hidden', 'true');
     var items;
                node.style.setProperty('display', 'none', 'important');
    var html;
            } 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 (!guide) return;
        if (!isMediaWikiSystemAssetPageForShell()) {
            body.classList.remove('clbi-system-doc-page');
            removeSystemDocIndicatorForShell();
        }


    items = getClbiBottomShortcutItems();
        if (isAnecdoteNamespaceForShell()) {
            body.classList.add('anecdote-namespace-page');
        }


    if (!items.length) {
        if (isMediaWikiSystemAssetPageForShell()) {
        guide.classList.add('is-empty');
            body.classList.add('page-title-hidden', 'backend-system-page', 'clbi-system-doc-page');
         guide.innerHTML = '';
            setPageTitleDomHidden(true);
         return;
            renderSystemDocIndicatorForShell();
        } else if (isSystemPage) {
            body.classList.add('page-title-visible', 'backend-system-page');
            setPageTitleDomHidden(false);
         } else {
            body.classList.add('page-title-hidden');
            setPageTitleDomHidden(true);
         }
     }
     }


     guide.classList.remove('is-empty');
     function applyPageShellClassesDeferred() {
        applyPageShellClasses();
        window.setTimeout(applyPageShellClasses, 0);
        window.setTimeout(applyPageShellClasses, 80);
        window.setTimeout(applyPageShellClasses, 250);
    }


     html = '<div class="clbi-bottom-shortcut-list">';
     function startPageShellObserver() {
        var observer;


    items.forEach(function (item) {
         if (pageShellObserverStarted || !window.MutationObserver || !document.body) return;
         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>';
        pageShellObserverStarted = true;
    guide.innerHTML = html;
        observer = new MutationObserver(function (mutations) {
}
            var i;
            var target;


function buildClbiBottomPlankHtml(wrapId, navId, mainId) {
            /*
    return '' +
            시스템 CSS/JS 문서는 applyPageShellClasses()가 초기에 한 번
        '<div id="' + wrapId + '">' +
            인디케이터와 source viewer를 만든 뒤에는 MutationObserver가 다시
             '<div id="' + navId + '">' +
            같은 렌더링을 반복할 필요가 없다. 이 반복이 DevTools에서 body/요소가
                '<div id="' + mainId + '">' +
             계속 플래시되는 직접 원인이다.
                    '<div id="clbi-bottom-shortcut-guide" class="is-empty" aria-label="단축키 안내"></div>' +
            SPA 전환 뒤의 처리는 loadPage()와 wikipage.content hook에서 따로 호출된다.
                 '</div>' +
            */
            '</div>' +
            if (isMediaWikiSystemAssetPageForShell()) {
        '</div>';
                 for (i = 0; i < mutations.length; i += 1) {
}
                    target = mutations[i] && mutations[i].target;


var CLBI_NATIONS_LAST_POINTER_X = null;
                    if (
var CLBI_NATIONS_LAST_POINTER_Y = null;
                        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;
                    }
                }


function getClbiNationsTabAtPointer(tabpanel) {
                if (
    var element;
                    document.getElementById('clbi-system-doc-indicator-row') &&
    var tab;
                    document.getElementById('clbi-system-source-viewer')
                ) {
                    return;
                }
            }


    if (!tabpanel) return null;
            if (pageShellObserverTimer) return;
    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);
            pageShellObserverTimer = window.setTimeout(function () {
    if (!element) return null;
                pageShellObserverTimer = null;
                applyPageShellClasses();
            }, 50);
        });


    tab = element.closest ? element.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;
        /*
        SPA 본문 교체는 wikipage.content 훅이 담당한다.
        body 전체 subtree를 감시하면 대문 SVG·장식·DevTools 내부 변경까지
        페이지 셸 재판정으로 증폭되므로 body 직계 자식 변화만 감시한다.
        */
        observer.observe(document.body, {
            childList: true,
            subtree: false
        });
    }


     if (!tab || !tabpanel.contains(tab)) return null;
     if (document.readyState === 'loading') {
 
        document.addEventListener('DOMContentLoaded', function () {
     return tab;
            applyPageShellClassesDeferred();
}
            startPageShellObserver();
        });
     } else {
        applyPageShellClassesDeferred();
        startPageShellObserver();
    }


function validateClbiNationsPointerHover(tabpanel, forceSuppress) {
     if (mw.hook) {
    var tab = getClbiNationsTabAtPointer(tabpanel);
        mw.hook('wikipage.content').add(applyPageShellClassesDeferred);
    var suppressContinent;
    var tabContinent;
    var tabIsActive;
 
     if (!tabpanel) return;
 
    if (!tab) {
        clearClbiNationsKeyboardHoverSuppressed(tabpanel);
        return;
     }
     }


     tabContinent = tab.getAttribute('data-continent') || '';
     window.CLBI_PAGE_SHELL = {
    tabIsActive = tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';
        refresh: applyPageShellClasses,
        isBackendOrSystemPage: isBackendOrSystemPageForShell,
        isSystemAssetPage: isMediaWikiSystemAssetPageForShell,
        renderSystemDocIndicator: renderSystemDocIndicatorForShell,
        removeSystemDocIndicator: removeSystemDocIndicatorForShell,
        refreshSystemDocSourceViewer: renderSystemDocSourceViewerForShell
    };
}());


     if (tabIsActive) {
function loadLangScript(done) {
        clearClbiNationsKeyboardHoverSuppressed(tabpanel);
     $.getScript('/index.php?title=미디어위키:Lang.js&action=raw&ctype=text/javascript')
         return;
        .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();
         });
}


    suppressContinent = tabpanel.getAttribute('data-clbi-hover-suppress-continent') || '';


    if (forceSuppress || !suppressContinent) {
/*
        tabpanel.classList.add('is-keyboard-switching');
DevTools 같은 내부 스크롤은 셸 레이아웃을 바꾸지 않는다. 이 짧은 상호작용 동안
        tabpanel.setAttribute('data-clbi-hover-suppress-continent', tabContinent);
전체 화면 WebGL/CRT가 새 GPU 프레임을 계속 제출하면, transform 셸과 고정 네비의
        return;
합성 타일 갱신이 서로 경합한다. 마지막 정상 프레임은 그대로 유지하고 시각 시계도
    }
정지시켜, 스크롤 종료 후 끊김 없이 이어지게 한다.
*/
var CLBI_COMPOSITOR_BUSY_UNTIL = 0;


    if (suppressContinent === tabContinent) {
function markClbiCompositorBusy(duration) {
        tabpanel.classList.add('is-keyboard-switching');
    var now = window.performance && performance.now ? performance.now() : Date.now();
        return;
    CLBI_COMPOSITOR_BUSY_UNTIL = Math.max(CLBI_COMPOSITOR_BUSY_UNTIL, now + Math.max(80, Number(duration) || 140));
    }
}


     /*
function isClbiCompositorBusy() {
    * The pointer actually moved onto another tab after the keyboard switch.
     var now = window.performance && performance.now ? performance.now() : Date.now();
    * At that point this is no longer stale browser :hover; let normal hover work.
     return now < CLBI_COMPOSITOR_BUSY_UNTIL;
    */
     clearClbiNationsKeyboardHoverSuppressed(tabpanel);
}
}


function validateAllClbiNationsPointerHovers() {
window.markClbiCompositorBusy = markClbiCompositorBusy;
     var panels = document.querySelectorAll('.clbi-nations-tabpanel.is-keyboard-switching');
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);


     Array.prototype.forEach.call(panels, function (tabpanel) {
     document.addEventListener('wheel', function (event) {
         if (isClbiNationsPanelOwnedTabpanel(tabpanel)) return;
        var target = event.target && event.target.nodeType === 1 ? event.target : null;
        validateClbiNationsPointerHover(tabpanel, false);
         if (target && target.closest && target.closest('#dev-tools-panel')) {
     });
            markClbiCompositorBusy(160);
        }
     }, { capture:true, passive:true });
}
}


function isClbiNationsPanelOwnedTabpanel(tabpanel) {
function initHalftoneBackground() {
     return !!(tabpanel && (
     try {
         tabpanel.CLBI_NationsPanelOwned ||
         initWebGLHalftoneBackground();
        tabpanel.getAttribute('data-nations-tabpanel-ready') === '1' ||
    } catch (err) {
         tabpanel.classList.contains('clbi-nations-continent-cache')
         console.error('WebGL halftone background failed:', err);
     ));
     }
}
}


function activateClbiNationsContinent(tabpanel, targetContinent) {
function initWebGLHalftoneBackground() {
     var tabs;
     var canvasId = 'site-halftone-bg';
     var panels;
     var existing = document.getElementById(canvasId);
    var canvas = existing || document.createElement('canvas');
    var halftoneState = window.SiteHalftoneBackgroundState || (window.SiteHalftoneBackgroundState = { runId: 0 });
    var runId = halftoneState.runId + 1;


     if (!tabpanel || !targetContinent) return false;
     halftoneState.runId = runId;


     if (isClbiNationsPanelOwnedTabpanel(tabpanel)) {
     if (!existing) {
         if (window.CLBI_NATIONS_PANEL && typeof window.CLBI_NATIONS_PANEL.activateContinent === 'function') {
         canvas.id = canvasId;
            return !!window.CLBI_NATIONS_PANEL.activateContinent(targetContinent, { source: 'common-legacy-click' });
        canvas.setAttribute('aria-hidden', 'true');
         }
         document.body.insertBefore(canvas, document.body.firstChild || null);
        return false;
     }
     }


     tabs = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]'));
     canvas.style.position = 'fixed';
     panels = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-continent[data-continent-panel]'));
    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 (!tabs.length || !panels.length) return false;
     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);
    }


     tabs.forEach(function (tab) {
     var gl = canvas.getContext('webgl', {
        var active = tab.getAttribute('data-continent') === targetContinent;
        alpha: false,
         tab.classList.toggle('is-active', active);
         antialias: false,
         tab.setAttribute('aria-selected', active ? 'true' : 'false');
         depth: false,
         tab.setAttribute('tabindex', active ? '0' : '-1');
        stencil: false,
     });
         preserveDrawingBuffer: false,
        powerPreference: 'low-power'
     }) || canvas.getContext('experimental-webgl');


     panels.forEach(function (panel) {
     if (!gl) {
         var active = panel.getAttribute('data-continent-panel') === targetContinent;
         canvas.style.display = 'none';
         panel.classList.toggle('is-active', active);
         console.warn('WebGL background unavailable.');
        return;
    }


         if (active) {
    var vertexSrc = [
            panel.removeAttribute('hidden');
        'attribute vec2 a_position;',
         } else {
         'void main() {',
            panel.setAttribute('hidden', 'hidden');
        '  gl_Position = vec4(a_position, 0.0, 1.0);',
        }
         '}'
    });
    ].join('\n');


     try {
     var fragmentSrc = [
         if (window.Decorations && typeof window.Decorations.sync === 'function') window.Decorations.sync();
        'precision mediump float;',
         else if (window.CLBI_DECORATIONS && typeof window.CLBI_DECORATIONS.sync === 'function') window.CLBI_DECORATIONS.sync();
        'uniform vec2 u_resolution;',
    } catch (err) {}
        'uniform float u_time;',
 
        'const float TAU = 6.28318530718;',
    return true;
        'float gaussian(float v, float r) {',
}
        '  return exp(-((v * v) / max(0.0001, r * r)));',
 
        '}',
function setClbiNationsKeyboardHoverSuppressed(tabpanel) {
        'float hash(vec2 p) {',
    validateClbiNationsPointerHover(tabpanel, true);
         '  return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123);',
}
        '}',
 
        'float bucketAlpha(float a) {',
function clearClbiNationsKeyboardHoverSuppressed(tabpanel) {
        '  float i = floor(a * 9.0);',
    if (!tabpanel) return;
        ' if (i < 1.0) return 0.040;',
    tabpanel.classList.remove('is-keyboard-switching');
        '  if (i < 2.0) return 0.080;',
    tabpanel.removeAttribute('data-clbi-hover-suppress-continent');
        '  if (i < 3.0) return 0.135;',
}
         if (i < 4.0) return 0.210;',
 
        '  if (i < 5.0) return 0.310;',
function moveClbiNationsContinent(direction) {
        ' if (i < 6.0) return 0.430;',
    var tabpanel = document.querySelector('.clbi-nations-tabpanel');
        '  if (i < 7.0) return 0.580;',
    var tabs;
        '  if (i < 8.0) return 0.760;',
    var activeIndex;
        '  return 0.920;',
    var nextIndex;
        '}',
    var target;
        'void main() {',
 
        '  vec2 frag = gl_FragCoord.xy;',
    if (!tabpanel) return false;
        '  float spacing = 5.0;',
 
        '  float dotSize = 1.08;',
    if (isClbiNationsPanelOwnedTabpanel(tabpanel) &&
        '  vec2 grid = floor(frag / spacing);',
         window.CLBI_NATIONS_PANEL &&
        '  vec2 inCell = mod(frag, spacing);',
         typeof window.CLBI_NATIONS_PANEL.moveContinent === 'function') {
        '  vec2 dotOrigin = vec2(1.0, 1.0);',
         return !!window.CLBI_NATIONS_PANEL.moveContinent(direction, { source: 'common-legacy-keyboard' });
        '  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');


     tabs = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]'));
     function compileShader(type, source) {
    if (!tabs.length) return false;
        var shader = gl.createShader(type);
        gl.shaderSource(shader, source);
        gl.compileShader(shader);


    activeIndex = tabs.findIndex(function (tab) {
        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        return tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';
            console.error('WebGL shader compile error:', gl.getShaderInfoLog(shader));
    });
            gl.deleteShader(shader);
            return null;
        }


     if (activeIndex < 0) activeIndex = 0;
        return shader;
     }


     nextIndex = (activeIndex + direction + tabs.length) % tabs.length;
     var vertexShader = compileShader(gl.VERTEX_SHADER, vertexSrc);
     target = tabs[nextIndex].getAttribute('data-continent');
     var fragmentShader = compileShader(gl.FRAGMENT_SHADER, fragmentSrc);


     if (activateClbiNationsContinent(tabpanel, target)) {
     if (!vertexShader || !fragmentShader) return;
        setClbiNationsKeyboardHoverSuppressed(tabpanel);
        window.setTimeout(function () {
            validateClbiNationsPointerHover(tabpanel, false);
        }, 0);
        return true;
    }


     return false;
     var program = gl.createProgram();
}
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);


function initClbiNationsTabpanelControls(root) {
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
    var scope = root && root.querySelectorAll ? root : document;
        console.error('WebGL program link error:', gl.getProgramInfoLog(program));
    var panels = scope.querySelectorAll('.clbi-nations-tabpanel');
        return;
    }


     Array.prototype.forEach.call(panels, function (tabpanel) {
     var positionLoc = gl.getAttribLocation(program, 'a_position');
        if (tabpanel.getAttribute('data-clbi-nations-tabs-ready') === '1') return;
    var resolutionLoc = gl.getUniformLocation(program, 'u_resolution');
    var timeLoc = gl.getUniformLocation(program, 'u_time');


        tabpanel.setAttribute('data-clbi-nations-tabs-ready', '1');
    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);


        tabpanel.addEventListener('pointerdown', function () {
    gl.useProgram(program);
            clearClbiNationsKeyboardHoverSuppressed(tabpanel);
    gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
        });
    gl.enableVertexAttribArray(positionLoc);
    gl.vertexAttribPointer(positionLoc, 2, gl.FLOAT, false, 0, 0);


         tabpanel.addEventListener('pointerleave', function () {
    function resize() {
            clearClbiNationsKeyboardHoverSuppressed(tabpanel);
         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));


         tabpanel.addEventListener('click', function (event) {
         if (canvas.width !== w || canvas.height !== h) {
             var tab = event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;
             canvas.width = w;
            canvas.height = h;
            canvas.style.width = cssW + 'px';
            canvas.style.height = cssH + 'px';
            gl.viewport(0, 0, w, h);
        }
    }


            if (!tab || !tabpanel.contains(tab)) return;
    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;


            clearClbiNationsKeyboardHoverSuppressed(tabpanel);
        if (!globe) {
            return 'none';
        }


            if (activateClbiNationsContinent(tabpanel, tab.getAttribute('data-continent'))) {
        if (globe.classList && globe.classList.contains('is-dragging')) {
                event.preventDefault();
            return 'active';
            }
         }
         });


         tabpanel.addEventListener('keydown', function (event) {
         instance = globe.CLBI_NationsGlobeInstance || null;
             var tab = event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;
        if (instance && typeof instance.isHalftoneBackgroundBusy === 'function' && instance.isHalftoneBackgroundBusy()) {
            var handled = false;
             return 'busy';
        }


            if (!tab || !tabpanel.contains(tab)) return;
        if (globe.getAttribute && globe.getAttribute('data-clbi-globe-bg-busy') === '1') {
            return 'busy';
        }


            if (event.key === 'ArrowLeft') handled = moveClbiNationsContinent(-1);
        return 'present';
            else if (event.key === 'ArrowRight') handled = moveClbiNationsContinent(1);
    }


            if (handled) {
    function shouldSkipHalftoneDrawForGlobe() {
                event.preventDefault();
        var globe = getNationsGlobeHalftoneNode();
                event.stopPropagation();
         var instance;
            }
         });
    });
}


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


    document.body.setAttribute('data-clbi-nations-pointer-hover-ready', '1');
        instance = globe.CLBI_NationsGlobeInstance || null;


    document.addEventListener('pointermove', function (event) {
        /*
        CLBI_NATIONS_LAST_POINTER_X = event.clientX;
        * Background pause/resume — 20260710.
         CLBI_NATIONS_LAST_POINTER_Y = event.clientY;
        *
         validateAllClbiNationsPointerHovers();
        * While the nations globe is being held, keep the last rendered halftone
    }, true);
        * 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;


    document.addEventListener('pointerleave', function () {
        if (instance && typeof instance.isHalftoneBackgroundHardBusy === 'function') {
        CLBI_NATIONS_LAST_POINTER_X = null;
            return instance.isHalftoneBackgroundHardBusy();
        CLBI_NATIONS_LAST_POINTER_Y = null;
        }
        validateAllClbiNationsPointerHovers();
    }, true);


    window.addEventListener('blur', function () {
        if (globe.getAttribute && globe.getAttribute('data-clbi-globe-bg-busy') === '1') return true;
        CLBI_NATIONS_LAST_POINTER_X = null;
        CLBI_NATIONS_LAST_POINTER_Y = null;
        validateAllClbiNationsPointerHovers();
    });
}


        return false;
    }


function initClbiBottomShortcutSystem(root) {
    function getFrameInterval() {
    renderClbiBottomShortcutGuide();
        if (prefersReducedMotion) {
    initClbiNationsTabpanelControls(root || document);
            return 1000;
    initClbiNationsPointerHoverValidation();
        }
}


// ── 상·하단 네비게이션 바 ──
        /*
function buildClbiNavHtml(position) {
        * Nations background parity — 20260710.
     var isBottom = position === 'bottom';
        *
     var base = isBottom ? 'clbi-bottom' : 'clbi-top';
        * The nations page used to permanently lower the halftone cadence while
     var shortBase = isBottom ? 'clbi-bnav' : 'clbi-tnav';
        * the globe existed.  Profiling showed that the steady halftone draw is
     var wrapId = base + '-nav-wrap';
        * normally cheap; the real contention happens during globe drag, first
     var navId = base + '-nav';
        * WebGL texture upload, and long layout/render tasks.  Keep the same
    var mainId = base + '-nav-main';
        * full-quality cadence as ordinary pages, and skip only the frames that
    var tabsId = base + '-nav-tabs';
        * would directly collide with an active/busy globe moment.
    var searchId = base + '-nav-search';
        */
    var inputId = isBottom ? 'clbi-bottom-search-input' : 'clbi-top-search-input';
        return 66;
    var rightId = base + '-nav-right';
    }
    var worldId = shortBase + '-worldbuilding';
 
    var infoId = shortBase + '-info';
     var lastFrame = 0;
    var subId = isBottom ? 'clbi-bottom-sub-worldbuilding' : 'clbi-sub-worldbuilding';
     var startTime = performance.now();
    var subInnerId = subId + '-inner';
     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 (isBottom) {
        if (perf && typeof perf.measureSync === 'function') {
        return buildClbiBottomPlankHtml(wrapId, navId, mainId);
            return perf.measureSync('background halftone draw', { globeState: state, interval: interval }, runDraw);
        }
        return runDraw();
     }
     }


     return '' +
     var frameTimer = 0;
        '<div id="' + wrapId + '">' +
    var frameRaf = 0;
            '<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 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() {
    function scheduleNextFrame(delay) {
    var contentWrapper = document.querySelector('.content-wrapper');
        window.clearTimeout(frameTimer);
    var topNav = document.getElementById('clbi-top-nav-wrap');
        frameTimer = window.setTimeout(function () {
    var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
            frameTimer = 0;
    var canvas = document.getElementById('site-halftone-bg');
            if (halftoneState.runId !== runId || halftoneState.contextLost) return;
    var anchor;
            if (window.requestAnimationFrame) {
    var viewportH;
                frameRaf = window.requestAnimationFrame(render);
    var topRect;
            } else {
    var wrapperRect;
                render(performance.now());
    var needsRecovery;
            }
    var expectedWrapperTop;
         }, Math.max(16, Number(delay) || getFrameInterval()));
    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;
     function render(now) {
    topRect = topNav.getBoundingClientRect();
        var interval = getFrameInterval();
    wrapperRect = contentWrapper.getBoundingClientRect();
    expectedWrapperTop = topRect.bottom + 8;


    needsRecovery = false;
        frameRaf = 0;
        if (halftoneState.runId !== runId || halftoneState.contextLost) return;


    if (viewportH > 0) {
        if (document.hidden) {
        if (topRect.top >= viewportH * 0.55) needsRecovery = true;
            lastVisualNow = now;
        if (wrapperRect.top >= viewportH * 0.60) needsRecovery = true;
            scheduleNextFrame(250);
    }
            return;
        }


    if (topRect.top > 240 || wrapperRect.top > 320) {
        if (isClbiCompositorBusy()) {
        needsRecovery = true;
            lastFrame = now;
    }
            lastVisualNow = now;
            scheduleNextFrame(interval);
            return;
        }


    if (wrapperRect.top < expectedWrapperTop - 1) {
        if (shouldSkipHalftoneDrawForGlobe()) {
        needsRecovery = true;
            lastFrame = now;
    }
            halftoneState.lastGlobeBusySkipAt = now;
            lastVisualNow = now;
            scheduleNextFrame(interval);
            return;
        }


    if (!needsRecovery) {
        lastFrame = now;
         document.body.classList.add('clbi-shell-ready');
         draw(now);
         return;
         scheduleNextFrame(interval);
     }
     }


     anchor = canvas && canvas.parentNode === document.body
     draw(performance.now());
        ? canvas.nextSibling
    scheduleNextFrame(getFrameInterval());
        : document.body.firstChild;


     document.body.insertBefore(topNav, anchor);
     document.addEventListener('visibilitychange', function () {
    document.body.insertBefore(contentWrapper, topNav.nextSibling);
        if (!document.hidden && halftoneState.runId === runId && !halftoneState.contextLost) {
    document.body.insertBefore(bottomNav, contentWrapper.nextSibling);
            window.clearTimeout(frameTimer);
            if (frameRaf && window.cancelAnimationFrame) window.cancelAnimationFrame(frameRaf);
            frameRaf = 0;
            scheduleNextFrame(16);
        }
    });


    document.body.classList.add('clbi-shell-ready');
}
}


window.normalizeClbiShellDomOrder = normalizeClbiShellDomOrder;
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 ensureClbiVerticalScaleHost() {
function invalidateProfileRender() {
     var topNav = document.getElementById('clbi-top-nav-wrap');
     PROFILE_RENDER_TOKEN++;
    var contentWrapper = document.querySelector('.content-wrapper');
}
     var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
 
    var host;
$(function() {
    var existing;
     initHalftoneBackground();
    var parent;


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


     existing = document.getElementById('clbi-shell-scale-host');
function readClbiBottomGuidePageName() {
     var pageName = window.mw && mw.config ? (mw.config.get('wgPageName') || '') : '';


     if (existing && existing.contains(topNav) && existing.contains(contentWrapper) && existing.contains(bottomNav)) {
     if (!pageName) {
         existing.classList.add('clbi-shell-host');
         pageName = window.location.pathname || '';
        return existing;
     }
     }


     parent = topNav.parentElement === contentWrapper.parentElement && contentWrapper.parentElement === bottomNav.parentElement
     return String(pageName)
         ? topNav.parentElement
        .split('?')[0]
         : null;
        .replace(/^\/index\.php\//, '')
         .replace(/_/g, ' ')
         .trim();
}


    if (parent && parent !== document.body) {
function isClbiNationsShortcutContext() {
        parent.classList.add('clbi-shell-host');
    var pageName = readClbiBottomGuidePageName();
        parent.id = parent.id || 'clbi-shell-scale-host';
        return parent;
    }


     host = existing || document.createElement('div');
     return pageName === '시대' ||
    host.id = 'clbi-shell-scale-host';
        pageName === 'Era' ||
    host.className = 'clbi-shell-host';
        !!document.querySelector('.clbi-nations-panel-stack, .clbi-nations-globe-window, .clbi-nations-tabpanel');
}


    if (!host.parentNode) {
function isClbiWikiEditShortcutContext() {
        document.body.insertBefore(host, topNav);
    var action = window.mw && mw.config ? String(mw.config.get('wgAction') || '') : '';
     }
     var search = String(window.location.search || '');


     host.appendChild(topNav);
     return action === 'edit' ||
    host.appendChild(contentWrapper);
        action === 'submit' ||
    host.appendChild(bottomNav);
        /(?:^|[?&])action=(?:edit|submit)(?:&|$)/.test(search) ||
 
        !!document.querySelector('#editform, #wpSave, input[name="wpSave"], button[name="wpSave"]');
    return host;
}
}


function readClbiRootPx(name, fallback) {
    var raw = '';
    var value;


    try {
function isClbiNationListManagerShortcutContext() {
        raw = getComputedStyle(document.documentElement).getPropertyValue(name);
    return !!document.querySelector('.nation-list-manager');
    } catch (err) {}
}


    value = parseFloat(raw);
function getClbiBottomShortcutItems() {
     return isFinite(value) && value > 0 ? value : fallback;
     if (isClbiWikiEditShortcutContext()) {
}
        return [
            { key: 'Ctrl+S', label: '변경사항 저장' }
        ];
    }


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) {
     if (isClbiNationListManagerShortcutContext()) {
         newsBox.classList.remove('is-adaptive-constrained');
         return [
         newsBox.style.removeProperty('--adaptive-news-h');
            { key: 'Ctrl+S', label: '국가 목록 저장' }
         ];
     }
     }


     if (list) {
     if (isClbiNationsShortcutContext()) {
         list.classList.remove('is-adaptive-faded');
         return [
        list.removeAttribute('data-adaptive-limit');
            { key: 'Q', label: '이전 시대' },
        list.style.removeProperty('--adaptive-recent-h');
            { key: 'E', label: '다음 시대' },
            { key: 'Shift+Q', label: '이전 연도' },
            { key: 'Shift+E', label: '다음 연도' },
            { key: 'Ctrl+Q', label: '이전 대륙' },
            { key: 'Ctrl+E', label: '다음 대륙' }
        ];
     }
     }


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


function resetLeftBillboardAdaptiveState() {
function renderClbiBottomShortcutGuide() {
     var box = document.querySelector('#clbi-left-sidebar .left-billboard-box');
     var guide = document.getElementById('clbi-bottom-shortcut-guide');
    var items;
    var html;


     if (!box) return;
     if (!guide) return;


     box.classList.remove('is-left-ad-title-only', 'is-left-ad-extended');
     items = getClbiBottomShortcutItems();
    box.style.removeProperty('--left-billboard-h');
    box.style.removeProperty('--left-billboard-finish-h');
}


function updateClbiShellVerticalScale() {
    if (!items.length) {
    var root = document.documentElement;
        guide.classList.add('is-empty');
    var body = document.body;
        guide.innerHTML = '';
    var host;
        return;
    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;
     guide.classList.remove('is-empty');


     host = ensureClbiVerticalScaleHost();
     html = '<div class="clbi-bottom-shortcut-list">';
    if (!host) return;


     thresholdH = readClbiRootPx('--clbi-vertical-scale-threshold-h', 1080);
     items.forEach(function (item) {
    gap = readClbiRootPx('--layout-gap', 8);
        html += '<div class="clbi-bottom-shortcut-item">' +
    outerGapTotal = gap * 2;
            '<span class="clbi-bottom-shortcut-key">' + escapeClbiBottomGuideHtml(item.key) + '</span>' +
    baseStageH = Math.max(420, thresholdH - outerGapTotal);
            '<span class="clbi-bottom-shortcut-label">' + escapeClbiBottomGuideHtml(item.label) + '</span>' +
     stageW = readClbiRootPx('--layout-shell-w', 1880);
        '</div>';
     });


     viewportW = Math.max(320, window.innerWidth || document.documentElement.clientWidth || stageW);
     html += '</div>';
     viewportH = Math.max(320, window.innerHeight || document.documentElement.clientHeight || thresholdH);
     guide.innerHTML = html;
    availableW = Math.max(240, viewportW - outerGapTotal);
}
    availableH = Math.max(240, viewportH - outerGapTotal);


     /*
function buildClbiBottomPlankHtml(wrapId, navId, mainId) {
    평상시에는 기존 세로 채움 레이아웃을 기준으로 삼는다.
     return '' +
    세로가 기준점보다 작아지는 경우에는 기준 높이를 고정점으로 삼고,
        '<div id="' + wrapId + '">' +
    가로만 부족한 경우에는 현재 사용 가능한 세로 높이를 고정점으로 삼는다.
            '<div id="' + navId + '">' +
    이렇게 해야 가로 부족으로 scale에 들어갈 때 본문 높이가 갑자기 접히지 않는다.
                '<div id="' + mainId + '">' +
    */
                    '<div id="clbi-bottom-shortcut-guide" class="is-empty" aria-label="단축키 안내"></div>' +
    stageH = availableH >= baseStageH ? availableH : baseStageH;
                '</div>' +
            '</div>' +
        '</div>';
}


    topInner = document.getElementById('clbi-top-nav');
var CLBI_NATIONS_LAST_POINTER_X = null;
    bottomInner = document.getElementById('clbi-bottom-nav');
var CLBI_NATIONS_LAST_POINTER_Y = null;


    topH = topInner ? Math.ceil(topInner.offsetHeight || topInner.getBoundingClientRect().height || 38) : 38;
function getClbiNationsTabAtPointer(tabpanel) {
     bottomH = bottomInner ? Math.ceil(bottomInner.offsetHeight || bottomInner.getBoundingClientRect().height || 38) : 38;
     var element;
     contentH = Math.max(360, Math.floor(stageH - topH - bottomH - (gap * 2)));
     var tab;


     widthScale = availableW < stageW ? availableW / stageW : 1;
     if (!tabpanel) return null;
     heightScale = availableH < baseStageH ? availableH / baseStageH : 1;
     if (CLBI_NATIONS_LAST_POINTER_X === null || CLBI_NATIONS_LAST_POINTER_Y === null) return null;
    scale = Math.min(1, widthScale, heightScale);
     if (typeof document.elementFromPoint !== 'function') return null;
     scale = Math.max(0.50, Math.min(1, Math.floor(scale * 1000) / 1000));
    shouldScale = scale < 0.999;


     root.style.setProperty('--clbi-stage-design-w', stageW + 'px');
     element = document.elementFromPoint(CLBI_NATIONS_LAST_POINTER_X, CLBI_NATIONS_LAST_POINTER_Y);
     root.style.setProperty('--clbi-stage-design-h', Math.floor(stageH) + 'px');
     if (!element) return null;
    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);
     tab = element.closest ? element.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;


     if (shouldScale) {
     if (!tab || !tabpanel.contains(tab)) return null;
        resetLeftRecentAdaptiveState();
        resetLeftBillboardAdaptiveState();
    }
}
window.updateClbiShellVerticalScale = updateClbiShellVerticalScale;


var $contentWrapper = $('.content-wrapper').first();
     return tab;
 
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;
function validateClbiNationsPointerHover(tabpanel, forceSuppress) {
    var tab = getClbiNationsTabAtPointer(tabpanel);
    var suppressContinent;
    var tabContinent;
    var tabIsActive;


function runClbiShellMetricsBatch() {
     if (!tabpanel) 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;
     if (!tab) {
        clearClbiNationsKeyboardHoverSuppressed(tabpanel);
        return;
    }


     if (!root) return;
     tabContinent = tab.getAttribute('data-continent') || '';
    tabIsActive = tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';


     if (top) {
     if (tabIsActive) {
         topH = Math.ceil(top.getBoundingClientRect().height || top.offsetHeight || 0);
         clearClbiNationsKeyboardHoverSuppressed(tabpanel);
        return;
     }
     }


     if (bottom) {
     suppressContinent = tabpanel.getAttribute('data-clbi-hover-suppress-continent') || '';
        bottomH = Math.ceil(bottom.getBoundingClientRect().height || bottom.offsetHeight || 0);
    }


     root.style.setProperty('--clbi-top-nav-outer-h', topH + 'px');
     if (forceSuppress || !suppressContinent) {
    root.style.setProperty('--clbi-bottom-nav-outer-h', bottomH + 'px');
        tabpanel.classList.add('is-keyboard-switching');
 
        tabpanel.setAttribute('data-clbi-hover-suppress-continent', tabContinent);
    if (typeof updateClbiShellVerticalScale === 'function') {
         return;
         updateClbiShellVerticalScale();
     }
     }


     if (typeof scheduleAdaptiveLeftRecentItems === 'function') {
     if (suppressContinent === tabContinent) {
         scheduleAdaptiveLeftRecentItems();
         tabpanel.classList.add('is-keyboard-switching');
        return;
     }
     }


     if (typeof scheduleClbiContentBottomGap === 'function') {
     /*
        scheduleClbiContentBottomGap();
    * 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 requestClbiShellMetricsFrame() {
function validateAllClbiNationsPointerHovers() {
     if (CLBI_SHELL_METRICS_RAF !== null) return;
     var panels = document.querySelectorAll('.clbi-nations-tabpanel.is-keyboard-switching');
 
    Array.prototype.forEach.call(panels, function (tabpanel) {
        if (isClbiNationsPanelOwnedTabpanel(tabpanel)) return;
        validateClbiNationsPointerHover(tabpanel, false);
    });
}


     CLBI_SHELL_METRICS_RAF = window.requestAnimationFrame
function isClbiNationsPanelOwnedTabpanel(tabpanel) {
        ? window.requestAnimationFrame(runClbiShellMetricsBatch)
     /*
        : window.setTimeout(runClbiShellMetricsBatch, 16);
    * 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 scheduleClbiShellMetrics() {
function isClbiNationsLiveContinentActive(tabpanel, continent) {
     requestClbiShellMetricsFrame();
     var tab;
    var panel;


     window.setTimeout(requestClbiShellMetricsFrame, 0);
     if (!tabpanel || !continent) return false;
    window.setTimeout(requestClbiShellMetricsFrame, 80);
    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();
     tab = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]')).find(function (candidate) {
        return candidate.getAttribute('data-continent') === continent;
    });


     $(window).on('resize orientationchange', scheduleClbiShellMetrics);
     panel = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-continent[data-continent-panel]')).find(function (candidate) {
    $(window).on('pageshow.clbiShellScale focus.clbiShellScale', scheduleClbiShellMetrics);
         return candidate.getAttribute('data-continent-panel') === continent;
    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) {
     return !!(
         observer = new ResizeObserver(scheduleClbiShellMetrics);
         tab &&
         if (top) observer.observe(top);
        panel &&
         if (bottom) observer.observe(bottom);
         (tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true') &&
         window.CLBI_SHELL_RESIZE_OBSERVER = observer;
         panel.classList.contains('is-active') &&
     }
        panel.getAttribute('aria-hidden') !== 'true' &&
         !panel.hasAttribute('hidden')
     );
}
}


function bindClbiWorldbuildingToggle(buttonSelector, menuSelector) {
function activateClbiNationsContinent(tabpanel, targetContinent, options) {
     $(buttonSelector).on('click', function() {
     var tabs;
        var $menu = $(menuSelector);
    var panels;
        var $btn = $(this);
    var skipOwner = !!(options && options.skipOwner);
 
    if (!tabpanel || !targetContinent) return false;


        $menu.toggleClass('worldbuilding-open');
    if (!skipOwner && isClbiNationsPanelOwnedTabpanel(tabpanel)) {
         $btn.toggleClass('clbi-tnav-active', $menu.hasClass('worldbuilding-open'));
         var owner = window.NationsPanel || window.CLBI_NATIONS_PANEL || null;
        scheduleClbiShellMetrics();
    });
}


bindClbiWorldbuildingToggle('#clbi-tnav-worldbuilding', '#clbi-sub-worldbuilding');
        if (owner && typeof owner.activateContinent === 'function') {
bindClbiWorldbuildingToggle('#clbi-bnav-worldbuilding', '#clbi-bottom-sub-worldbuilding');
            try {
                if (owner.activateContinent(targetContinent, {
                    source: 'common-legacy-click',
                    panel: tabpanel
                })) {
                    return true;
                }
            } catch (err) {}
        }


$('#clbi-top-search-input, #clbi-bottom-search-input').on('keydown', function(e) {
        /*
    if (e.key === 'Enter') {
        * Ownership markers can be stale during SPA/hydration edge cases. If
        var q = $(this).val().trim();
        * the owner API is missing or refuses the live panel, do not drop the
        if (q) window.location.href = '/index.php?search=' + encodeURIComponent(q);
        * mouse click. Fall through to the local fallback so pointer users are
        * never left with keyboard-only continent tabs.
        */
     }
     }
});


if (window.mw && mw.hook) {
    tabs = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]'));
     mw.hook('wikipage.content').add(function ($content) {
     panels = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-continent[data-continent-panel]'));
         initClbiBottomShortcutSystem($content && $content[0] ? $content[0] : document);
 
    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');
     });
     });
}


watchClbiShellMetrics();
    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 {
var transitionSound = new Audio('/index.php?title=특수:Redirect/file/Sfx-ui-001.mp3');
        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() {
     return true;
    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() {
function setClbiNationsKeyboardHoverSuppressed(tabpanel) {
     var master = parseFloat(localStorage.getItem('clbi-audio-master') || 80) / 100;
     validateClbiNationsPointerHover(tabpanel, true);
    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 clearClbiNationsKeyboardHoverSuppressed(tabpanel) {
function getCurrentLang() {
     if (!tabpanel) return;
     var langData = document.getElementById('clbi-lang-data');
    tabpanel.classList.remove('is-keyboard-switching');
     return langData ? (langData.getAttribute('data-lang') || 'ko') : 'ko';
     tabpanel.removeAttribute('data-clbi-hover-suppress-continent');
}
}


function normalizePageName(value) {
function moveClbiNationsContinent(direction) {
     return String(value || '')
     var tabpanel = document.querySelector('.clbi-nations-tabpanel');
        .split('?')[0]
    var tabs;
        .replace(/^\/index\.php\//, '')
    var activeIndex;
        .replace(/_/g, ' ')
    var nextIndex;
        .trim();
    var target;
}


function buildWikiPath(title) {
    if (!tabpanel) return false;
    return '/index.php/' + encodeURI(String(title || '').replace(/ /g, '_'));
}


function getLangShortCode(lang) {
    if (isClbiNationsPanelOwnedTabpanel(tabpanel) &&
    var map = { ko: 'KR', en: 'EN', zh: 'ZH', ja: 'JA', ru: 'RU', es: 'ES' };
        window.CLBI_NATIONS_PANEL &&
     return map[lang] || String(lang || '').toUpperCase();
        typeof window.CLBI_NATIONS_PANEL.moveContinent === 'function') {
}
        return !!window.CLBI_NATIONS_PANEL.moveContinent(direction, {
            source: 'common-legacy-keyboard',
            panel: tabpanel
        });
     }


function getLanguageTargetTitle(lang) {
     tabs = Array.prototype.slice.call(tabpanel.querySelectorAll('.clbi-nations-tabpanel-tab[data-continent]'));
     var data = document.getElementById('clbi-lang-data');
     if (!tabs.length) return false;
     if (!data || !lang) return '';


     var keys = [
     activeIndex = tabs.findIndex(function (tab) {
         'data-' + lang,
         return tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';
        'data-page-' + lang,
     });
        'data-title-' + lang,
        'data-target-' + lang,
        'data-lang-' + lang
     ];


     for (var i = 0; i < keys.length; i++) {
     if (activeIndex < 0) activeIndex = 0;
        var value = data.getAttribute(keys[i]);
        if (value) return value;
    }


     return '';
     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 escapeClbiHtml(value) {
function initClbiNationsTabpanelControls(root) {
     return String(value == null ? '' : value)
     var scope = root && root.querySelectorAll ? root : document;
        .replace(/&/g, '&amp;')
    var panels = scope.querySelectorAll('.clbi-nations-tabpanel');
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}


    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');


var SIDEBAR_LANG_SVG_NS = 'http://www.w3.org/2000/svg';
        tabpanel.addEventListener('pointerdown', function () {
var SIDEBAR_LANGUAGE_STATUS_TITLE = 'MediaWiki:LanguageStatus.json';
            clearClbiNationsKeyboardHoverSuppressed(tabpanel);
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 = {};
        tabpanel.addEventListener('pointerleave', function () {
var sidebarLanguageStatusLoaded = false;
            clearClbiNationsKeyboardHoverSuppressed(tabpanel);
var sidebarLanguageStatusLoading = false;
        });
var sidebarLanguageStatusCallbacks = [];


var sidebarLanguageState = {
        tabpanel.addEventListener('click', function (event) {
    order: ['ko', 'en', 'zh', 'ja', 'ru', 'es'],
            var tab = event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;
    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) {
            if (!tab || !tabpanel.contains(tab)) return;
    return document.createElementNS(SIDEBAR_LANG_SVG_NS, tag);
}


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


function getSidebarLanguageName(lang) {
            if (activateClbiNationsContinent(tabpanel, tab.getAttribute('data-continent'))) {
    return SIDEBAR_LANGUAGE_LABELS[lang] || String(lang || '').toUpperCase();
                event.preventDefault();
}
            }
        });


function getSidebarLanguageDialName(lang) {
        tabpanel.addEventListener('keydown', function (event) {
    return SIDEBAR_LANGUAGE_DIAL_LABELS[lang] || getSidebarLanguageName(lang);
            var tab = event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent]') : null;
}
            var handled = false;


function normalizeSidebarLanguageStatusValue(value) {
            if (!tab || !tabpanel.contains(tab)) return;
    value = String(value == null ? '' : value).toLowerCase().trim();
    return SIDEBAR_LANGUAGE_STATUS_VALUES[value] ? value : '';
}


function getSidebarLanguageStatusPageKey() {
            if (event.key === 'ArrowLeft') handled = moveClbiNationsContinent(-1);
    var raw = String(mw.config.get('wgPageName') || '').trim();
            else if (event.key === 'ArrowRight') handled = moveClbiNationsContinent(1);
    var normalized = normalizePageName(raw);


     return normalized || raw || '대문';
            if (handled) {
                event.preventDefault();
                event.stopPropagation();
            }
        });
     });
}
}


function getSidebarLanguageStatusEntry() {
function handleClbiNationsContinentDocumentClick(event) {
     var registry = sidebarLanguageStatusRegistry || {};
     var target;
     var pages = registry.pages && typeof registry.pages === 'object' ? registry.pages : registry;
    var tab;
     var raw = String(mw.config.get('wgPageName') || '').trim();
     var tabpanel;
     var normalized = normalizePageName(raw);
     var continent;
     var title = String(mw.config.get('wgTitle') || '').trim();
     var owner;
     var keys = [
     var handled = false;
        normalized,
 
        raw,
    if (!event || event.__clbiNationsContinentHandled) return;
        raw.replace(/_/g, ' '),
     target = event.target;
        normalized.replace(/ /g, '_'),
    if (!target || !target.closest) return;
        title,
        title.replace(/_/g, ' ')
    ];
    var i;


     for (i = 0; i < keys.length; i += 1) {
     tab = target.closest('.clbi-nations-tabpanel-tab[data-continent]');
        if (keys[i] && pages[keys[i]] && typeof pages[keys[i]] === 'object') {
    if (!tab) return;
            return pages[keys[i]];
        }
    }


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


function getSidebarLanguageStatusOverride(lang) {
     continent = tab.getAttribute('data-continent') || '';
     var entry = getSidebarLanguageStatusEntry();
     if (!continent) return;
     return normalizeSidebarLanguageStatusValue(entry[lang]);
}


function flushSidebarLanguageStatusCallbacks() {
    /*
     var callbacks = sidebarLanguageStatusCallbacks.slice();
    * Final live-DOM mouse delegate.
     sidebarLanguageStatusCallbacks.length = 0;
    * --------------------------------
    * 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);


     callbacks.forEach(function(callback) {
     owner = window.NationsPanel || window.CLBI_NATIONS_PANEL || null;
        if (typeof callback === 'function') {
    if (owner && typeof owner.activateContinent === 'function') {
             callback(sidebarLanguageStatusRegistry);
        try {
             handled = !!owner.activateContinent(continent, {
                source: 'mouse-click-live-delegate',
                panel: tabpanel
            });
        } catch (err) {
            handled = false;
         }
         }
    });
}


function loadSidebarLanguageStatusRegistry(callback, force) {
        /*
    if (typeof callback === 'function') {
        * Owner API stale-cache guard.
         sidebarLanguageStatusCallbacks.push(callback);
        *
        * 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 (sidebarLanguageStatusLoaded && !force) {
     if (!handled) {
         flushSidebarLanguageStatusCallbacks();
         handled = activateClbiNationsContinent(tabpanel, continent, { skipOwner: true });
        return;
     }
     }


     if (sidebarLanguageStatusLoading) return;
     if (handled) {
        try { playStaticSound(); } catch (err2) {}
        event.preventDefault();
        event.stopPropagation();
        if (typeof event.stopImmediatePropagation === 'function') event.stopImmediatePropagation();
    }
}


     sidebarLanguageStatusLoading = true;
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);
}


    $.ajax({
        url: mw.util.getUrl(SIDEBAR_LANGUAGE_STATUS_TITLE, {
            action: 'raw',
            ctype: 'application/json',
            _: String(Date.now())
        }),
        dataType: 'text',
        cache: false
    }).done(function(text) {
        var parsed = {};


        try {
function initClbiNationsPointerHoverValidation() {
            parsed = text ? JSON.parse(text) : {};
    if (document.body.getAttribute('data-clbi-nations-pointer-hover-ready') === '1') return;
        } catch (err) {
            console.error('LanguageStatus.json parse failed:', err);
            parsed = {};
        }


        sidebarLanguageStatusRegistry = parsed && typeof parsed === 'object' ? parsed : {};
     document.body.setAttribute('data-clbi-nations-pointer-hover-ready', '1');
     }).fail(function() {
        sidebarLanguageStatusRegistry = {};
    }).always(function() {
        sidebarLanguageStatusLoaded = true;
        sidebarLanguageStatusLoading = false;
        flushSidebarLanguageStatusCallbacks();
    });
}


window.CLBI_LANGUAGE_STATUS = {
     document.addEventListener('pointermove', function (event) {
    title: SIDEBAR_LANGUAGE_STATUS_TITLE,
         CLBI_NATIONS_LAST_POINTER_X = event.clientX;
     languages: sidebarLanguageState.order.slice(),
         CLBI_NATIONS_LAST_POINTER_Y = event.clientY;
    labels: SIDEBAR_LANGUAGE_LABELS,
         validateAllClbiNationsPointerHovers();
    dialLabels: SIDEBAR_LANGUAGE_DIAL_LABELS,
    }, true);
    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) {
    document.addEventListener('pointerleave', function () {
    var currentLang = getCurrentLang();
        CLBI_NATIONS_LAST_POINTER_X = null;
    var targetTitle = getLanguageTargetTitle(lang);
        CLBI_NATIONS_LAST_POINTER_Y = null;
     var isCurrent = lang === currentLang;
        validateAllClbiNationsPointerHovers();
     }, true);


     return {
     window.addEventListener('blur', function () {
        lang: lang,
         CLBI_NATIONS_LAST_POINTER_X = null;
        code: getLangShortCode(lang),
         CLBI_NATIONS_LAST_POINTER_Y = null;
        name: getSidebarLanguageName(lang),
         validateAllClbiNationsPointerHovers();
         dialName: getSidebarLanguageDialName(lang),
     });
         targetTitle: targetTitle,
         isCurrent: isCurrent,
        canMove: !!targetTitle && !isCurrent
     };
}
}


function getSidebarLanguageStatus(meta) {
    var override;


    if (!meta) {
function initClbiBottomShortcutSystem(root) {
        return {
    renderClbiBottomShortcutGuide();
            className: 'is-locked',
    initClbiNationsGlobalClickDelegate();
            label: 'UNAVAILABLE',
    initClbiNationsTabpanelControls(root || document);
            canApply: false
    initClbiNationsPointerHoverValidation();
        };
}
    }


    if (meta.isCurrent) {
// ── 상·하단 네비게이션 바 ──
        return {
function buildClbiNavHtml(position) {
            className: 'is-current',
    var isBottom = position === 'bottom';
            label: 'CURRENT',
    var base = isBottom ? 'clbi-bottom' : 'clbi-top';
            canApply: false
    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';


    override = getSidebarLanguageStatusOverride(meta.lang);
     if (isBottom) {
 
         return buildClbiBottomPlankHtml(wrapId, navId, mainId);
     if (override === 'wip') {
         return {
            className: 'is-locked',
            label: 'WIP',
            canApply: false
        };
     }
     }


     if (override === 'unavailable') {
     return '' +
        return {
        '<div id="' + wrapId + '">' +
            className: 'is-locked',
            '<div id="' + navId + '">' +
            label: 'UNAVAILABLE',
                '<div id="' + mainId + '">' +
            canApply: false
                    '<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>' +
    if (override === 'available' || meta.targetTitle) {
                        '</a>' +
        return {
                        '<a class="clbi-top-nav-item" href="/index.php/프로젝트:소개">' +
            className: meta.targetTitle ? 'is-ready' : 'is-locked',
                            '<img class="clbi-tnav-icon" src="/index.php?title=특수:Redirect/file/Ic-project-001.png" alt="">' +
            label: meta.targetTitle ? 'AVAILABLE' : 'UNAVAILABLE',
                            '<span class="clbi-tnav-label">프로젝트</span>' +
            canApply: !!meta.targetTitle
                        '</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>' +
    return {
                            '<span class="clbi-tnav-arrow">▾</span>' +
        className: 'is-locked',
                        '</div>' +
         label: 'UNAVAILABLE',
                    '</div>' +
        canApply: false
                    (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 sidebarLanguageRad(deg) {
function normalizeClbiShellDomOrder() {
     return (deg * Math.PI) / 180;
     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;


function sidebarLanguagePointAt(radius, deg) {
     if (!contentWrapper || !topNav || !bottomNav || !document.body) return;
    var state = sidebarLanguageState;
     var angle = sidebarLanguageRad(deg);


     return {
     /*
        x: state.cx + Math.sin(angle) * radius,
    CLBI shell can live inside a Liberty <section>.  Some skins/layouts give that
         y: state.cy - Math.cos(angle) * radius
    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;


function getSidebarLanguageSectorPath(start, end) {
    if (host) {
     var state = sidebarLanguageState;
        host.classList.add('clbi-shell-host');
     var p1 = sidebarLanguagePointAt(state.outerR, start);
    }
     var p2 = sidebarLanguagePointAt(state.outerR, end);
 
     var p3 = sidebarLanguagePointAt(state.innerR, end);
     viewportH = window.innerHeight || document.documentElement.clientHeight || 0;
     var p4 = sidebarLanguagePointAt(state.innerR, start);
     topRect = topNav.getBoundingClientRect();
    var largeArc = Math.abs(end - start) > 180 ? 1 : 0;
     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;
    }


     return [
     if (topRect.top > 240 || wrapperRect.top > 320) {
        'M', p1.x.toFixed(3), p1.y.toFixed(3),
         needsRecovery = true;
         '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() {
    if (wrapperRect.top < expectedWrapperTop - 1) {
    return getSidebarLanguageSectorPath(-68, 68);
        needsRecovery = true;
}
    }


function getSidebarLanguageByStep(step) {
    if (!needsRecovery) {
    var state = sidebarLanguageState;
        document.body.classList.add('clbi-shell-ready');
     var index = normalizeSidebarLanguageIndex(state.baseIndex + step);
        return;
     }


     return {
     anchor = canvas && canvas.parentNode === document.body
         index: index,
         ? canvas.nextSibling
         meta: getSidebarLanguageMeta(state.order[index])
         : document.body.firstChild;
    };
}


function getSidebarLanguagePreviewIndex() {
    document.body.insertBefore(topNav, anchor);
    var state = sidebarLanguageState;
     document.body.insertBefore(contentWrapper, topNav.nextSibling);
     var step = Math.round(-state.rotation / state.sectorAngle);
     document.body.insertBefore(bottomNav, contentWrapper.nextSibling);
     return normalizeSidebarLanguageIndex(state.baseIndex + step);
}


function getSidebarLanguagePreviewMeta() {
     document.body.classList.add('clbi-shell-ready');
     var state = sidebarLanguageState;
    return getSidebarLanguageMeta(state.order[getSidebarLanguagePreviewIndex()]);
}
}


function makeSidebarLanguageSector(step) {
window.normalizeClbiShellDomOrder = normalizeClbiShellDomOrder;
     var state = sidebarLanguageState;
 
    var item = getSidebarLanguageByStep(step);
 
     var group = createSidebarLanguageSvgEl('g');
function ensureClbiVerticalScaleHost() {
     var path = createSidebarLanguageSvgEl('path');
     var topNav = document.getElementById('clbi-top-nav-wrap');
     var label = createSidebarLanguageSvgEl('text');
     var contentWrapper = document.querySelector('.content-wrapper');
     var labelY = state.cy - 78;
     var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
     var angle = step * state.sectorAngle;
     var host;
     var existing;
     var parent;
 
    if (!topNav || !contentWrapper || !bottomNav || !document.body) return null;


     group.setAttribute('class', 'sidebar-lang-sector-group');
     existing = document.getElementById('clbi-shell-scale-host');
    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');
     if (existing && existing.contains(topNav) && existing.contains(contentWrapper) && existing.contains(bottomNav)) {
     path.setAttribute('d', getSidebarLanguageSectorPath(-state.halfSector, state.halfSector));
        existing.classList.add('clbi-shell-host');
        return existing;
     }


     label.setAttribute('class', 'sidebar-lang-sector-label');
     parent = topNav.parentElement === contentWrapper.parentElement && contentWrapper.parentElement === bottomNav.parentElement
    label.setAttribute('x', String(state.cx));
        ? topNav.parentElement
    label.setAttribute('y', String(labelY + 5));
        : null;
    label.textContent = item.meta.dialName || item.meta.name;


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


     group.addEventListener('click', function(e) {
     host = existing || document.createElement('div');
        if (sidebarLanguageState.dragging || performance.now() < sidebarLanguageState.suppressClickUntil) return;
    host.id = 'clbi-shell-scale-host';
    host.className = 'clbi-shell-host';


        e.preventDefault();
    if (!host.parentNode) {
         e.stopPropagation();
         document.body.insertBefore(host, topNav);
    }


        cancelSidebarLanguageSpin();
    host.appendChild(topNav);
        snapSidebarLanguageToStep(parseInt(group.getAttribute('data-step') || '0', 10), true);
    host.appendChild(contentWrapper);
     });
     host.appendChild(bottomNav);


     return group;
     return host;
}
}


function renderSidebarLanguageWheel() {
function readClbiRootPx(name, fallback) {
     var state = sidebarLanguageState;
     var raw = '';
    var fan = document.getElementById('clbi-sidebar-lang-fan');
     var value;
     var svg;
 
    var defs;
     try {
     var clip;
        raw = getComputedStyle(document.documentElement).getPropertyValue(name);
    var clipPath;
     } catch (err) {}
     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;
     value = parseFloat(raw);
    return isFinite(value) && value > 0 ? value : fallback;
}


     fan.innerHTML = '';
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')) : [];


     svg = createSidebarLanguageSvgEl('svg');
     if (newsBox) {
    svg.setAttribute('class', 'sidebar-lang-fan-svg');
        newsBox.classList.remove('is-adaptive-constrained');
    svg.setAttribute('viewBox', '0 0 202 150');
        newsBox.style.removeProperty('--adaptive-news-h');
    svg.setAttribute('preserveAspectRatio', 'xMidYMid meet');
     }
     svg.setAttribute('role', 'img');
    svg.setAttribute('aria-label', '언어 선택 다이얼');


     defs = createSidebarLanguageSvgEl('defs');
     if (list) {
        list.classList.remove('is-adaptive-faded');
        list.removeAttribute('data-adaptive-limit');
        list.style.removeProperty('--adaptive-recent-h');
    }


     clip = createSidebarLanguageSvgEl('clipPath');
     items.forEach(function (item) {
    clip.setAttribute('id', 'clbi-sidebar-language-fan-clip');
        item.classList.remove('is-adaptive-hidden');
     clipPath = createSidebarLanguageSvgEl('path');
     });
    clipPath.setAttribute('d', getSidebarLanguageShellPath());
}
    clip.appendChild(clipPath);


    shadowBlur = createSidebarLanguageSvgEl('filter');
function resetLeftBillboardAdaptiveState() {
     shadowBlur.setAttribute('id', 'clbi-sidebar-language-shadow-blur');
     var box = document.querySelector('#clbi-left-sidebar .left-billboard-box');
    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');
     if (!box) return;
    fixedDepthGradient.setAttribute('id', 'clbi-sidebar-language-fixed-depth');
    fixedDepthGradient.setAttribute('x1', '0');
    fixedDepthGradient.setAttribute('y1', '0');
    fixedDepthGradient.setAttribute('x2', '0');
    fixedDepthGradient.setAttribute('y2', '1');


     [
     box.classList.remove('is-left-ad-title-only', 'is-left-ad-extended');
        ['0%', '#ffffff', '0.030'],
    box.style.removeProperty('--left-billboard-h');
        ['34%', '#ffffff', '0.006'],
    box.style.removeProperty('--left-billboard-finish-h');
        ['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);
function updateClbiShellVerticalScale() {
     defs.appendChild(shadowBlur);
     var root = document.documentElement;
     defs.appendChild(fixedDepthGradient);
     var body = document.body;
     svg.appendChild(defs);
    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;


     shell = createSidebarLanguageSvgEl('path');
     if (!root || !body) return;
    shell.setAttribute('class', 'sidebar-lang-shell');
    shell.setAttribute('d', getSidebarLanguageShellPath());
    svg.appendChild(shell);


     clipped = createSidebarLanguageSvgEl('g');
     host = ensureClbiVerticalScaleHost();
     clipped.setAttribute('clip-path', 'url(#clbi-sidebar-language-fan-clip)');
     if (!host) return;


     rotor = createSidebarLanguageSvgEl('g');
     thresholdH = readClbiRootPx('--clbi-vertical-scale-threshold-h', 1080);
     rotor.setAttribute('id', 'clbi-sidebar-lang-wheel-rotor');
     gap = readClbiRootPx('--layout-gap', 8);
     rotor.setAttribute('class', 'sidebar-lang-wheel-rotor');
    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);


     for (step = -state.repeats; step <= state.repeats; step += 1) {
     /*
        rotor.appendChild(makeSidebarLanguageSector(step));
    평상시에는 기존 세로 채움 레이아웃을 기준으로 삼는다.
     }
    세로가 기준점보다 작아지는 경우에는 기준 높이를 고정점으로 삼고,
    가로만 부족한 경우에는 현재 사용 가능한 세로 높이를 고정점으로 삼는다.
    이렇게 해야 가로 부족으로 scale에 들어갈 때 본문 높이가 갑자기 접히지 않는다.
     */
    stageH = availableH >= baseStageH ? availableH : baseStageH;


     clipped.appendChild(rotor);
     topInner = document.getElementById('clbi-top-nav');
     svg.appendChild(clipped);
     bottomInner = document.getElementById('clbi-bottom-nav');


     fixedDepthPath = createSidebarLanguageSvgEl('path');
     topH = topInner ? Math.ceil(topInner.offsetHeight || topInner.getBoundingClientRect().height || 38) : 38;
     fixedDepthPath.setAttribute('class', 'sidebar-lang-fixed-depth');
     bottomH = bottomInner ? Math.ceil(bottomInner.offsetHeight || bottomInner.getBoundingClientRect().height || 38) : 38;
     fixedDepthPath.setAttribute('d', getSidebarLanguageShellPath());
     contentH = Math.max(360, Math.floor(stageH - topH - bottomH - (gap * 2)));
    svg.appendChild(fixedDepthPath);


     fixedFocus = createSidebarLanguageSvgEl('path');
     widthScale = availableW < stageW ? availableW / stageW : 1;
     fixedFocus.setAttribute('class', 'sidebar-lang-fixed-focus');
    heightScale = availableH < baseStageH ? availableH / baseStageH : 1;
     fixedFocus.setAttribute('d', getSidebarLanguageSectorPath(-state.halfSector, state.halfSector));
     scale = Math.min(1, widthScale, heightScale);
     svg.appendChild(fixedFocus);
     scale = Math.max(0.50, Math.min(1, Math.floor(scale * 1000) / 1000));
     shouldScale = scale < 0.999;


     shadowSoft = createSidebarLanguageSvgEl('path');
     setClbiRootMetric(root, '--clbi-stage-design-w', stageW + 'px');
     shadowSoft.setAttribute('class', 'sidebar-lang-inner-shadow-soft');
     setClbiRootMetric(root, '--clbi-stage-design-h', Math.floor(stageH) + 'px');
     shadowSoft.setAttribute('d', getSidebarLanguageShellPath());
    setClbiRootMetric(root, '--clbi-stage-content-h', contentH + 'px');
    svg.appendChild(shadowSoft);
     setClbiRootMetric(root, '--clbi-shell-scale', String(scale));


     shadowHard = createSidebarLanguageSvgEl('path');
     if (body.classList.contains('clbi-shell-vertical-scale') !== shouldScale) {
    shadowHard.setAttribute('class', 'sidebar-lang-inner-shadow-hard');
        body.classList.toggle('clbi-shell-vertical-scale', shouldScale);
    shadowHard.setAttribute('d', getSidebarLanguageShellPath());
     }
     svg.appendChild(shadowHard);


     rim = createSidebarLanguageSvgEl('path');
     if (shouldScale) {
    rim.setAttribute('class', 'sidebar-lang-rim');
        resetLeftRecentAdaptiveState();
    rim.setAttribute('d', getSidebarLanguageShellPath());
        resetLeftBillboardAdaptiveState();
     svg.appendChild(rim);
     }
}
window.updateClbiShellVerticalScale = updateClbiShellVerticalScale;


    pointer = createSidebarLanguageSvgEl('g');
var $contentWrapper = $('.content-wrapper').first();
    pointer.setAttribute('class', 'sidebar-lang-fixed-pointer');
    pointer.setAttribute('clip-path', 'url(#clbi-sidebar-language-fan-clip)');


    tri = createSidebarLanguageSvgEl('path');
if ($contentWrapper.length) {
     tri.setAttribute('class', 'sidebar-lang-pointer-triangle');
     $('#clbi-top-nav-wrap, #clbi-bottom-nav-wrap').remove();
     tri.setAttribute('d', 'M ' + (state.cx - 10) + ' 10 L ' + (state.cx + 10) + ' 10 L ' + state.cx + ' 26 Z');
     $contentWrapper.before(buildClbiNavHtml('top'));
    pointer.appendChild(tri);
    $contentWrapper.after(buildClbiNavHtml('bottom'));
    renderClbiBottomShortcutGuide();
    initClbiNationsTabpanelControls(document);
    if (typeof window.normalizeClbiShellDomOrder === 'function') window.normalizeClbiShellDomOrder();
}


    line = createSidebarLanguageSvgEl('line');
var CLBI_SHELL_METRICS_RAF = null;
    line.setAttribute('class', 'sidebar-lang-pointer-line');
var CLBI_SHELL_METRICS_SETTLE_TIMER = null;
    line.setAttribute('x1', String(state.cx));
var CLBI_SHELL_METRICS_LAST = { topH:-1, bottomH:-1 };
    line.setAttribute('x2', String(state.cx));
    line.setAttribute('y1', '24');
    line.setAttribute('y2', '112');
    pointer.appendChild(line);


    svg.appendChild(pointer);
function setClbiRootMetric(root, name, value) {
     fan.appendChild(svg);
     var next = String(value);
 
     if (root.style.getPropertyValue(name) === next) return false;
     state.rotor = rotor;
     root.style.setProperty(name, next);
     setSidebarLanguageRotation(state.rotation, false);
    return true;
}
}


function updateSidebarLanguageDial() {
function runClbiShellMetricsBatch() {
     var state = sidebarLanguageState;
     var top = document.getElementById('clbi-top-nav-wrap');
    var meta = getSidebarLanguagePreviewMeta();
     var bottom = document.getElementById('clbi-bottom-nav-wrap');
    var status = getSidebarLanguageStatus(meta);
     var root = document.documentElement;
    var selector = document.getElementById('clbi-sidebar-lang-selector');
     var topH = 0;
     var apply = document.getElementById('clbi-sidebar-lang-apply');
     var bottomH = 0;
     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) {
    CLBI_SHELL_METRICS_RAF = null;
        selectedValue.textContent = meta.name;
     if (!root) return;
    }


     if (availabilityPanel) {
     if (top) topH = Math.ceil(top.offsetHeight || top.getBoundingClientRect().height || 0);
        availabilityPanel.classList.remove('is-ready', 'is-current', 'is-locked');
    if (bottom) bottomH = Math.ceil(bottom.offsetHeight || bottom.getBoundingClientRect().height || 0);
        availabilityPanel.classList.add(status.className);
    }


     if (availabilityValue) {
     if (topH !== CLBI_SHELL_METRICS_LAST.topH) {
         availabilityValue.textContent = status.label;
         CLBI_SHELL_METRICS_LAST.topH = topH;
        setClbiRootMetric(root, '--clbi-top-nav-outer-h', topH + 'px');
     }
     }
 
     if (bottomH !== CLBI_SHELL_METRICS_LAST.bottomH) {
     if (apply) {
         CLBI_SHELL_METRICS_LAST.bottomH = bottomH;
         apply.classList.toggle('is-disabled', !status.canApply);
         setClbiRootMetric(root, '--clbi-bottom-nav-outer-h', bottomH + 'px');
         apply.setAttribute('aria-disabled', status.canApply ? 'false' : 'true');
        apply.setAttribute('aria-label', status.canApply ? (meta.name + ' 적용') : (meta.isCurrent ? '현재 언어' : '사용할 수 없는 언어'));
     }
     }


     if (selector) {
     if (typeof updateClbiShellVerticalScale === 'function') updateClbiShellVerticalScale();
        selector.setAttribute('data-selected-lang', meta.lang);
    if (typeof scheduleAdaptiveLeftRecentItems === 'function') scheduleAdaptiveLeftRecentItems();
        selector.setAttribute('data-selected-code', meta.code);
    if (typeof scheduleClbiContentBottomGap === 'function') scheduleClbiContentBottomGap();
        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 requestClbiShellMetricsFrame() {
         meta: meta,
     if (CLBI_SHELL_METRICS_RAF !== null) return;
         status: status
    CLBI_SHELL_METRICS_RAF = window.requestAnimationFrame
    };
         ? window.requestAnimationFrame(runClbiShellMetricsBatch)
         : window.setTimeout(runClbiShellMetricsBatch, 16);
}
}


function setSidebarLanguageRotation(value, animate) {
function scheduleClbiShellMetrics() {
     var state = sidebarLanguageState;
    requestClbiShellMetricsFrame();
     state.rotation = value;
    window.clearTimeout(CLBI_SHELL_METRICS_SETTLE_TIMER);
     updateSidebarLanguageDial();
    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();


     if (!state.rotor) 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);


     if (animate) {
     if (window.ResizeObserver) {
         $('#clbi-sidebar-lang-selector').addClass('is-snapping');
         observer = new ResizeObserver(scheduleClbiShellMetrics);
    } else {
        if (top) observer.observe(top);
         $('#clbi-sidebar-lang-selector').removeClass('is-snapping');
         if (bottom) observer.observe(bottom);
        window.CLBI_SHELL_RESIZE_OBSERVER = observer;
     }
     }
    state.rotor.style.transform = 'rotate(' + state.rotation.toFixed(3) + 'deg)';
}
}


function requestSidebarLanguageRotation(value) {
function bindClbiWorldbuildingToggle(buttonSelector, menuSelector) {
     var state = sidebarLanguageState;
     $(buttonSelector).on('click', function() {
    state.pendingRotation = value;
        var $menu = $(menuSelector);
        var $btn = $(this);


    if (state.raf) return;
        $menu.toggleClass('worldbuilding-open');
 
        $btn.toggleClass('clbi-tnav-active', $menu.hasClass('worldbuilding-open'));
    state.raf = requestAnimationFrame(function() {
         scheduleClbiShellMetrics();
        state.raf = null;
         setSidebarLanguageRotation(state.pendingRotation, false);
     });
     });
}
}


function cancelSidebarLanguageSpin() {
bindClbiWorldbuildingToggle('#clbi-tnav-worldbuilding', '#clbi-sub-worldbuilding');
    var state = sidebarLanguageState;
bindClbiWorldbuildingToggle('#clbi-bnav-worldbuilding', '#clbi-bottom-sub-worldbuilding');


     if (state.inertiaRaf) {
$('#clbi-top-search-input, #clbi-bottom-search-input').on('keydown', function(e) {
         cancelAnimationFrame(state.inertiaRaf);
     if (e.key === 'Enter') {
         state.inertiaRaf = null;
         var q = $(this).val().trim();
         if (q) window.location.href = '/index.php?search=' + encodeURIComponent(q);
     }
     }
});


     $('#clbi-sidebar-lang-selector').removeClass('is-spinning');
if (window.mw && mw.hook) {
     mw.hook('wikipage.content').add(function ($content) {
        initClbiBottomShortcutSystem($content && $content[0] ? $content[0] : document);
    });
}
}


function finishSidebarLanguageSnap(nearestIndex, callback) {
watchClbiShellMetrics();
    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');
// 페이지 전환 사운드
var transitionSound = new Audio('/index.php?title=특수:Redirect/file/Sfx-ui-001.mp3');


     renderSidebarLanguageWheel();
(function() {
     updateSidebarLanguageDial();
     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;
})();


     if (typeof callback === 'function') {
function playStaticSound() {
        callback(getSidebarLanguageMeta(state.order[state.selectedIndex]));
     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';


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


     cancelSidebarLanguageSpin();
     transitionSound.volume = master * sfx;
    clearTimeout(state.snapTimer);
     transitionSound.currentTime = 0;
 
     transitionSound.play();
     state.selectedIndex = nearestIndex;
     setSidebarLanguageRotation(targetRotation, !!animate);
 
    state.snapTimer = setTimeout(function() {
        finishSidebarLanguageSnap(nearestIndex, callback);
    }, animate ? 230 : 0);
}
}


function snapSidebarLanguageNearest(callback) {
// 현재 언어 감지
     var state = sidebarLanguageState;
function getCurrentLang() {
    var step = Math.round(-state.rotation / state.sectorAngle);
     var langData = document.getElementById('clbi-lang-data');
     snapSidebarLanguageToStep(step, true, callback);
     return langData ? (langData.getAttribute('data-lang') || 'ko') : 'ko';
}
}


function startSidebarLanguageInertiaSpin(initialVelocity) {
function normalizePageName(value) {
     var state = sidebarLanguageState;
     return String(value || '')
    var velocity;
        .split('?')[0]
    var lastFrame;
        .replace(/^\/index\.php\//, '')
        .replace(/_/g, ' ')
        .trim();
}


     cancelSidebarLanguageSpin();
function buildWikiPath(title) {
     return '/index.php/' + encodeURI(String(title || '').replace(/ /g, '_'));
}


     velocity = Math.max(-state.maxSpinVelocity, Math.min(state.maxSpinVelocity, initialVelocity));
function getLangShortCode(lang) {
     var map = { ko: 'KR', en: 'EN', zh: 'ZH', ja: 'JA', ru: 'RU', es: 'ES' };
    return map[lang] || String(lang || '').toUpperCase();
}


    if (Math.abs(velocity) < state.minSpinVelocity) {
function getLanguageTargetTitle(lang) {
        snapSidebarLanguageNearest();
    var data = document.getElementById('clbi-lang-data');
        return;
    if (!data || !lang) return '';
    }


     $('#clbi-sidebar-lang-selector').addClass('is-spinning');
     var keys = [
     lastFrame = performance.now();
        'data-' + lang,
        'data-page-' + lang,
        'data-title-' + lang,
        'data-target-' + lang,
        'data-lang-' + lang
     ];


     function frame(now) {
     for (var i = 0; i < keys.length; i++) {
        var dt = Math.min(34, Math.max(1, now - lastFrame));
         var value = data.getAttribute(keys[i]);
        var sign = velocity < 0 ? -1 : 1;
         if (value) return value;
        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);
     return '';
}
}


function scheduleSidebarLanguageNavigation(meta) {
function escapeClbiHtml(value) {
     var status = getSidebarLanguageStatus(meta);
     return String(value == null ? '' : value)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}


    if (!meta || !status.canApply) return;


    clearTimeout(sidebarLanguageState.navigateTimer);
var SIDEBAR_LANG_SVG_NS = 'http://www.w3.org/2000/svg';
     sidebarLanguageState.navigateTimer = setTimeout(function() {
var SIDEBAR_LANGUAGE_STATUS_TITLE = 'MediaWiki:LanguageStatus.json';
        var title = getLanguageTargetTitle(meta.lang);
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 (!title || meta.lang === getCurrentLang()) return;
var sidebarLanguageStatusRegistry = {};
var sidebarLanguageStatusLoaded = false;
var sidebarLanguageStatusLoading = false;
var sidebarLanguageStatusCallbacks = [];


        window.location.href = buildWikiPath(title);
var sidebarLanguageState = {
     }, 70);
    order: ['ko', 'en', 'zh', 'ja', 'ru', 'es'],
}
    currentLang: 'ko',
 
     baseIndex: 0,
function setSidebarLanguageSelection(lang) {
    selectedIndex: 0,
     var state = sidebarLanguageState;
    rotation: 0,
     var index = state.order.indexOf(lang);
    dragging: false,
 
    dragMoved: false,
     if (index < 0) index = state.order.indexOf(getCurrentLang());
    dragStartX: 0,
     if (index < 0) index = 0;
    dragStartY: 0,
 
     dragStartRotation: 0,
     if (state.raf) {
     dragAxis: null,
        cancelAnimationFrame(state.raf);
    pointerCaptured: false,
        state.raf = null;
     lastX: 0,
     }
     lastTime: 0,
 
    releaseVelocity: 0,
     cancelSidebarLanguageSpin();
    suppressClickUntil: 0,
     clearTimeout(state.snapTimer);
     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
};


    state.currentLang = lang;
function createSidebarLanguageSvgEl(tag) {
    state.baseIndex = index;
     return document.createElementNS(SIDEBAR_LANG_SVG_NS, tag);
    state.selectedIndex = index;
}
    state.rotation = 0;
     state.dragging = false;
    state.dragMoved = false;
    state.releaseVelocity = 0;


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


function moveSidebarLanguageSelection(delta) {
function getSidebarLanguageName(lang) {
     snapSidebarLanguageToStep(-delta, true);
     return SIDEBAR_LANGUAGE_LABELS[lang] || String(lang || '').toUpperCase();
}
}


function bindSidebarLanguageSelector() {
function getSidebarLanguageDialName(lang) {
     var state = sidebarLanguageState;
     return SIDEBAR_LANGUAGE_DIAL_LABELS[lang] || getSidebarLanguageName(lang);
    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;
function normalizeSidebarLanguageStatusValue(value) {
     value = String(value == null ? '' : value).toLowerCase().trim();
    return SIDEBAR_LANGUAGE_STATUS_VALUES[value] ? value : '';
}


     if (state.bound && state.boundElement === selector) return;
function getSidebarLanguageStatusPageKey() {
     var raw = String(mw.config.get('wgPageName') || '').trim();
    var normalized = normalizePageName(raw);


     state.bound = true;
     return normalized || raw || '대문';
    state.boundElement = selector;
}


     fan.addEventListener('pointerdown', function(e) {
function getSidebarLanguageStatusEntry() {
         cancelSidebarLanguageSpin();
    var registry = sidebarLanguageStatusRegistry || {};
         clearTimeout(state.snapTimer);
    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;


        state.dragging = true;
    for (i = 0; i < keys.length; i += 1) {
        state.dragMoved = false;
         if (keys[i] && pages[keys[i]] && typeof pages[keys[i]] === 'object') {
        state.dragStartX = e.clientX;
            return pages[keys[i]];
         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');
}


        /*
function getSidebarLanguageStatusOverride(lang) {
        Vertical page scrolling must stay available when the pointer starts on
    var entry = getSidebarLanguageStatusEntry();
        the language dial. Capture and preventDefault are delayed until a
     return normalizeSidebarLanguageStatusValue(entry[lang]);
        horizontal drag is confirmed.
}
        */
     });


    fan.addEventListener('pointermove', function(e) {
function flushSidebarLanguageStatusCallbacks() {
        var now;
    var callbacks = sidebarLanguageStatusCallbacks.slice();
        var totalDx;
    sidebarLanguageStatusCallbacks.length = 0;
        var totalDy;
        var frameDx;
        var dt;
        var instantVelocity;


         if (!state.dragging) return;
    callbacks.forEach(function(callback) {
         if (typeof callback === 'function') {
            callback(sidebarLanguageStatusRegistry);
        }
    });
}


        totalDx = e.clientX - state.dragStartX;
function loadSidebarLanguageStatusRegistry(callback, force) {
         totalDy = (e.clientY || 0) - state.dragStartY;
    if (typeof callback === 'function') {
         sidebarLanguageStatusCallbacks.push(callback);
    }


        if (!state.dragAxis && (Math.abs(totalDx) > 4 || Math.abs(totalDy) > 4)) {
    if (sidebarLanguageStatusLoaded && !force) {
            state.dragAxis = Math.abs(totalDx) >= Math.abs(totalDy) ? 'x' : 'y';
        flushSidebarLanguageStatusCallbacks();
        return;
    }


            if (state.dragAxis === 'y') {
    if (sidebarLanguageStatusLoading) return;
                state.dragging = false;
                state.dragMoved = false;
                state.dragAxis = null;
                state.pointerCaptured = false;
                selector.classList.remove('is-dragging');
                return;
            }


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


         if (state.dragAxis !== 'x') return;
    function finishLanguageStatus(parsed) {
         sidebarLanguageStatusRegistry = parsed && typeof parsed === 'object' ? parsed : {};
        sidebarLanguageStatusLoaded = true;
        sidebarLanguageStatusLoading = false;
        flushSidebarLanguageStatusCallbacks();
    }


         now = performance.now();
    if (!force && window.EntryStore && typeof window.EntryStore.fetchJsonRef === 'function') {
        frameDx = e.clientX - state.lastX;
         window.EntryStore.fetchJsonRef(SIDEBAR_LANGUAGE_STATUS_TITLE, { noStore: false })
        dt = Math.max(1, now - state.lastTime);
            .then(function (parsed) { finishLanguageStatus(parsed); })
            .catch(function () { finishLanguageStatus({}); });
        return;
    }


         if (Math.abs(totalDx) > 3) state.dragMoved = true;
    (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 = {};


        instantVelocity = (frameDx * state.dragSensitivity) / dt;
            try {
        state.releaseVelocity = (state.releaseVelocity * 0.62) + (instantVelocity * 0.38);
                parsed = text ? JSON.parse(text) : {};
        state.lastX = e.clientX;
            } catch (err) {
        state.lastTime = now;
                console.error('LanguageStatus.json parse failed:', err);
                parsed = {};
            }


        requestSidebarLanguageRotation(state.dragStartRotation + totalDx * state.dragSensitivity);
            finishLanguageStatus(parsed);
         e.preventDefault();
         }).fail(function() {
         e.stopPropagation();
            finishLanguageStatus({});
     });
         });
     })();
}


     function finishDrag(e) {
window.CLBI_LANGUAGE_STATUS = {
         var velocityAge;
    title: SIDEBAR_LANGUAGE_STATUS_TITLE,
         var throwVelocity;
    languages: sidebarLanguageState.order.slice(),
         var wasHorizontal;
    labels: SIDEBAR_LANGUAGE_LABELS,
 
    dialLabels: SIDEBAR_LANGUAGE_DIAL_LABELS,
         if (!state.dragging) return;
     getPageKey: getSidebarLanguageStatusPageKey,
    getRegistry: function() {
         return sidebarLanguageStatusRegistry || {};
    },
    reload: function(callback) {
         sidebarLanguageStatusLoaded = false;
         loadSidebarLanguageStatusRegistry(function() {
            renderSidebarLanguageBox();
            if (typeof callback === 'function') callback(sidebarLanguageStatusRegistry);
        }, true);
    },
    refreshDial: function() {
         renderSidebarLanguageBox();
    }
};


        wasHorizontal = state.dragAxis === 'x';
function getSidebarLanguageMeta(lang) {
        state.dragging = false;
    var currentLang = getCurrentLang();
        selector.classList.remove('is-dragging');
    var targetTitle = getLanguageTargetTitle(lang);
    var isCurrent = lang === currentLang;


         if (fan.releasePointerCapture && state.pointerCaptured && e && e.pointerId != null) {
    return {
            try { fan.releasePointerCapture(e.pointerId); } catch (err) {}
         lang: lang,
        }
        code: getLangShortCode(lang),
        name: getSidebarLanguageName(lang),
        dialName: getSidebarLanguageDialName(lang),
        targetTitle: targetTitle,
        isCurrent: isCurrent,
        canMove: !!targetTitle && !isCurrent
    };
}


        state.pointerCaptured = false;
function getSidebarLanguageStatus(meta) {
        state.dragAxis = null;
    var override;


        if (!wasHorizontal && !state.dragMoved) {
    if (!meta) {
             return;
        return {
        }
            className: 'is-locked',
            label: 'UNAVAILABLE',
             canApply: false
        };
    }


        velocityAge = performance.now() - state.lastTime;
    if (meta.isCurrent) {
         throwVelocity = velocityAge > 120 ? 0 : state.releaseVelocity;
        return {
            className: 'is-current',
            label: 'CURRENT',
            canApply: false
         };
    }


        if (state.dragMoved) {
    override = getSidebarLanguageStatusOverride(meta.lang);
            state.suppressClickUntil = performance.now() + 180;
        }


        if (state.dragMoved && Math.abs(throwVelocity) >= state.minSpinVelocity) {
    if (override === 'wip') {
             startSidebarLanguageInertiaSpin(throwVelocity);
        return {
         } else {
             className: 'is-locked',
            snapSidebarLanguageNearest();
            label: 'WIP',
        }
            canApply: false
         };
    }


        if (e) {
    if (override === 'unavailable') {
             e.preventDefault();
        return {
             e.stopPropagation();
             className: 'is-locked',
         }
            label: 'UNAVAILABLE',
             canApply: false
         };
     }
     }


     fan.addEventListener('pointerup', finishDrag);
     if (override === 'available' || meta.targetTitle) {
    fan.addEventListener('pointercancel', finishDrag);
        return {
    fan.addEventListener('lostpointercapture', function() {
            className: meta.targetTitle ? 'is-ready' : 'is-locked',
        if (!state.dragging) return;
            label: meta.targetTitle ? 'AVAILABLE' : 'UNAVAILABLE',
            canApply: !!meta.targetTitle
        };
    }


         state.dragging = false;
    return {
         state.pointerCaptured = false;
        className: 'is-locked',
        state.dragAxis = null;
         label: 'UNAVAILABLE',
        selector.classList.remove('is-dragging');
         canApply: false
    };
}


        if (state.dragMoved && Math.abs(state.releaseVelocity) >= state.minSpinVelocity) {
function sidebarLanguageRad(deg) {
            state.suppressClickUntil = performance.now() + 180;
    return (deg * Math.PI) / 180;
            startSidebarLanguageInertiaSpin(state.releaseVelocity);
}
        } else {
            snapSidebarLanguageNearest();
        }
    });


    apply.addEventListener('click', function(e) {
function sidebarLanguagePointAt(radius, deg) {
        e.preventDefault();
    var state = sidebarLanguageState;
        e.stopPropagation();
    var angle = sidebarLanguageRad(deg);


         snapSidebarLanguageNearest(function(meta) {
    return {
            scheduleSidebarLanguageNavigation(meta);
         x: state.cx + Math.sin(angle) * radius,
        });
        y: state.cy - Math.cos(angle) * radius
    });
    };
}


    selector.addEventListener('keydown', function(e) {
function getSidebarLanguageSectorPath(start, end) {
        if (e.key === 'ArrowLeft') {
    var state = sidebarLanguageState;
            moveSidebarLanguageSelection(-1);
    var p1 = sidebarLanguagePointAt(state.outerR, start);
            e.preventDefault();
    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;


         if (e.key === 'ArrowRight') {
    return [
            moveSidebarLanguageSelection(1);
         'M', p1.x.toFixed(3), p1.y.toFixed(3),
            e.preventDefault();
        '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(' ');
}


        if (e.key === 'Enter' || e.key === ' ') {
function getSidebarLanguageShellPath() {
            apply.click();
    return getSidebarLanguageSectorPath(-68, 68);
            e.preventDefault();
        }
    });
}
}


function renderSidebarLanguageBox() {
function getSidebarLanguageByStep(step) {
     bindSidebarLanguageSelector();
     var state = sidebarLanguageState;
     setSidebarLanguageSelection(getCurrentLang());
     var index = normalizeSidebarLanguageIndex(state.baseIndex + step);


     if (!sidebarLanguageStatusLoaded) {
     return {
         loadSidebarLanguageStatusRegistry(function() {
         index: index,
            setSidebarLanguageSelection(getCurrentLang());
        meta: getSidebarLanguageMeta(state.order[index])
        });
    };
    }
}
}


function loadRecentChangesList(targetSelector, limit) {
function getSidebarLanguagePreviewIndex() {
     var $target = $(targetSelector);
     var state = sidebarLanguageState;
    var step = Math.round(-state.rotation / state.sectorAngle);
    return normalizeSidebarLanguageIndex(state.baseIndex + step);
}


     if (!$target.length) return;
function getSidebarLanguagePreviewMeta() {
    var state = sidebarLanguageState;
     return getSidebarLanguageMeta(state.order[getSidebarLanguagePreviewIndex()]);
}


     var lang = getCurrentLang();
function makeSidebarLanguageSector(step) {
     var t = (window.LANG && window.LANG[lang]) ? window.LANG[lang] : (window.LANG ? window.LANG.ko : null);
    var state = sidebarLanguageState;
     var isNewsList = $target.closest('.clbi-left-news-box').length > 0;
     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;


     function escapeHtml(value) {
     group.setAttribute('class', 'sidebar-lang-sector-group');
        return String(value == null ? '' : value)
    group.setAttribute('data-step', String(step));
            .replace(/&/g, '&amp;')
    group.setAttribute('data-index', String(item.index));
            .replace(/</g, '&lt;')
    group.setAttribute('data-lang', item.meta.lang);
            .replace(/>/g, '&gt;')
    group.setAttribute('transform', 'rotate(' + angle + ' ' + state.cx + ' ' + state.cy + ')');
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }


     $target.html((t && t.loading) ? t.loading : '불러오는 중...');
     path.setAttribute('class', 'sidebar-lang-sector');
    path.setAttribute('d', getSidebarLanguageSectorPath(-state.halfSector, state.halfSector));


     $.getJSON(
     label.setAttribute('class', 'sidebar-lang-sector-label');
        '/api.php?action=query&list=recentchanges&rclimit=' + encodeURIComponent(limit || 5) + '&rcprop=title|timestamp|user&format=json&rcnamespace=0&rctype=edit|new',
    label.setAttribute('x', String(state.cx));
        function(data) {
    label.setAttribute('y', String(labelY + 5));
            var items = data && data.query ? data.query.recentchanges : [];
    label.textContent = item.meta.dialName || item.meta.name;
            var html = '';


            if (!items || !items.length) {
    group.appendChild(path);
                $target.html('표시할 변경 사항이 없습니다.');
    group.appendChild(label);
                return;
            }


            $.each(items, function(i, item) {
    group.addEventListener('click', function(e) {
                var label = timeAgo(item.timestamp);
        if (sidebarLanguageState.dragging || performance.now() < sidebarLanguageState.suppressClickUntil) return;
                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) {
        e.preventDefault();
                    html +=
        e.stopPropagation();
                        '<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) {
        cancelSidebarLanguageSpin();
                $target.html(
        snapSidebarLanguageToStep(parseInt(group.getAttribute('data-step') || '0', 10), true);
                    '<div class="news-recent-viewport">' +
    });
                        '<div class="news-recent-stack">' + html + '</div>' +
                    '</div>'
                );


                if (typeof ensureNewsBottomFinish === 'function') {
    return group;
                    ensureNewsBottomFinish();
}
                }
            } else {
                $target.html(html);
            }


            if (isNewsList && typeof scheduleAdaptiveLeftRecentItems === 'function') {
function renderSidebarLanguageWheel() {
                scheduleAdaptiveLeftRecentItems();
    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;


            $target.find(isNewsList ? '.news-recent-item' : '.clbi-recent-item').each(function() {
    if (!fan) 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;
    fan.innerHTML = '';


                var wrapW = wrap.width();
    svg = createSidebarLanguageSvgEl('svg');
                var titleW = title[0].scrollWidth;
    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 (titleW > wrapW + 20) {
    defs = createSidebarLanguageSvgEl('defs');
                    var duration = titleW / 40;


                    title.css({
    clip = createSidebarLanguageSvgEl('clipPath');
                        animation: 'clbi-scroll ' + duration + 's linear infinite',
    clip.setAttribute('id', 'clbi-sidebar-language-fan-clip');
                        '--scroll-dist': '-' + (titleW - wrapW + 8) + 'px'
    clipPath = createSidebarLanguageSvgEl('path');
                    });
    clipPath.setAttribute('d', getSidebarLanguageShellPath());
                }
    clip.appendChild(clipPath);
            });
 
        }
    shadowBlur = createSidebarLanguageSvgEl('filter');
     ).fail(function() {
    shadowBlur.setAttribute('id', 'clbi-sidebar-language-shadow-blur');
        var lang = getCurrentLang();
    shadowBlur.setAttribute('x', '-20%');
        var t = (window.LANG && window.LANG[lang]) ? window.LANG[lang] : (window.LANG ? window.LANG.ko : null);
    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');


         $target.html((t && t.loadFail) ? t.loadFail : '불러오기 실패');
    [
         ['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);


function ensureRecentViewport() {
    shell = createSidebarLanguageSvgEl('path');
     var list = document.getElementById('clbi-left-recent-list');
     shell.setAttribute('class', 'sidebar-lang-shell');
     var viewport;
     shell.setAttribute('d', getSidebarLanguageShellPath());
     var stack;
     svg.appendChild(shell);
    var children;


     if (!list) return null;
     clipped = createSidebarLanguageSvgEl('g');
    clipped.setAttribute('clip-path', 'url(#clbi-sidebar-language-fan-clip)');


     viewport = list.querySelector(':scope > .news-recent-viewport');
     rotor = createSidebarLanguageSvgEl('g');
     stack = viewport ? viewport.querySelector(':scope > .news-recent-stack') : null;
    rotor.setAttribute('id', 'clbi-sidebar-lang-wheel-rotor');
     rotor.setAttribute('class', 'sidebar-lang-wheel-rotor');


     if (viewport && stack) return viewport;
     for (step = -state.repeats; step <= state.repeats; step += 1) {
        rotor.appendChild(makeSidebarLanguageSector(step));
    }


     children = Array.prototype.slice.call(list.children || []);
     clipped.appendChild(rotor);
    svg.appendChild(clipped);


     viewport = document.createElement('div');
     fixedDepthPath = createSidebarLanguageSvgEl('path');
     viewport.className = 'news-recent-viewport';
     fixedDepthPath.setAttribute('class', 'sidebar-lang-fixed-depth');
    fixedDepthPath.setAttribute('d', getSidebarLanguageShellPath());
    svg.appendChild(fixedDepthPath);


     stack = document.createElement('div');
     fixedFocus = createSidebarLanguageSvgEl('path');
     stack.className = 'news-recent-stack';
     fixedFocus.setAttribute('class', 'sidebar-lang-fixed-focus');
    fixedFocus.setAttribute('d', getSidebarLanguageSectorPath(-state.halfSector, state.halfSector));
    svg.appendChild(fixedFocus);


     children.forEach(function (child) {
     shadowSoft = createSidebarLanguageSvgEl('path');
        if (child.classList && child.classList.contains('news-recent-viewport')) return;
    shadowSoft.setAttribute('class', 'sidebar-lang-inner-shadow-soft');
        stack.appendChild(child);
    shadowSoft.setAttribute('d', getSidebarLanguageShellPath());
     });
     svg.appendChild(shadowSoft);


     viewport.appendChild(stack);
     shadowHard = createSidebarLanguageSvgEl('path');
     list.appendChild(viewport);
    shadowHard.setAttribute('class', 'sidebar-lang-inner-shadow-hard');
    shadowHard.setAttribute('d', getSidebarLanguageShellPath());
     svg.appendChild(shadowHard);


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


function ensureNewsBottomFinish() {
    pointer = createSidebarLanguageSvgEl('g');
     var newsBox = document.querySelector('#clbi-left-sidebar .clbi-left-news-box');
     pointer.setAttribute('class', 'sidebar-lang-fixed-pointer');
     var content = newsBox ? newsBox.querySelector('.clbi-news-box') : null;
     pointer.setAttribute('clip-path', 'url(#clbi-sidebar-language-fan-clip)');
    var finish;


     if (!content) return null;
     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);


     finish = content.querySelector(':scope > .news-bottom-finish');
     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);


     if (!finish) {
     svg.appendChild(pointer);
        finish = document.createElement('div');
    fan.appendChild(svg);
        finish.className = 'news-bottom-finish';
        finish.setAttribute('aria-hidden', 'true');
        content.appendChild(finish);
    }


     return finish;
     state.rotor = rotor;
    setSidebarLanguageRotation(state.rotation, false);
}
}


function updateAdaptiveLeftRecentItems() {
function updateSidebarLanguageDial() {
     /*
     var state = sidebarLanguageState;
     134 기준: 좌측 사이드는 뉴스 확장형 flex 레이아웃이 높이를 담당한다.
    var meta = getSidebarLanguagePreviewMeta();
     이전 adaptive 코드는 항목을 숨기거나 mask/fade를 걸기 위한 것이었으므로
     var status = getSidebarLanguageStatus(meta);
     여기서는 잔여 상태만 정리하고 DOM 래퍼만 보장한다.
    var selector = document.getElementById('clbi-sidebar-lang-selector');
     */
    var apply = document.getElementById('clbi-sidebar-lang-apply');
     resetLeftRecentAdaptiveState();
     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 (typeof ensureRecentViewport === 'function') {
     if (availabilityPanel) {
         ensureRecentViewport();
        availabilityPanel.classList.remove('is-ready', 'is-current', 'is-locked');
         availabilityPanel.classList.add(status.className);
     }
     }


     if (typeof ensureNewsBottomFinish === 'function') {
     if (availabilityValue) {
         ensureNewsBottomFinish();
         availabilityValue.textContent = status.label;
     }
     }


     if (typeof scheduleClbiContentBottomGap === 'function') {
     if (apply) {
         scheduleClbiContentBottomGap();
        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 ? '현재 언어' : '사용할 수 없는 언어'));
     }
     }
}


function scheduleAdaptiveLeftRecentItems() {
    if (selector) {
    window.requestAnimationFrame(function () {
        selector.setAttribute('data-selected-lang', meta.lang);
         updateAdaptiveLeftRecentItems();
        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);
     }


     window.setTimeout(updateAdaptiveLeftRecentItems, 80);
     return {
     window.setTimeout(updateAdaptiveLeftRecentItems, 240);
        meta: meta,
        status: status
     };
}
}


function setSidebarLanguageRotation(value, animate) {
    var state = sidebarLanguageState;
    state.rotation = value;
    updateSidebarLanguageDial();


    if (!state.rotor) return;


function updateClbiContentBottomGap(iteration) {
    if (animate) {
    var content = document.querySelector('.container-fluid.liberty-content');
        $('#clbi-sidebar-lang-selector').addClass('is-snapping');
    var main = document.querySelector('.liberty-content-main');
     } else {
     var bottomNav = document.getElementById('clbi-bottom-nav-wrap');
        $('#clbi-sidebar-lang-selector').removeClass('is-snapping');
     var desiredGap = 8;
     }
    var rootStyle;
 
     var scale = 1;
     state.rotor.style.transform = 'rotate(' + state.rotation.toFixed(3) + 'deg)';
    var contentRect;
}
    var bottomTop;
 
    var targetHeight;
function requestSidebarLanguageRotation(value) {
     var currentHeight;
     var state = sidebarLanguageState;
     var visualGap;
     state.pendingRotation = value;


     iteration = iteration || 0;
     if (state.raf) return;


     if (!content || !main || !bottomNav) return;
     state.raf = requestAnimationFrame(function() {
        state.raf = null;
        setSidebarLanguageRotation(state.pendingRotation, false);
    });
}


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


    목표:
     if (state.inertiaRaf) {
    .liberty-content-main.bottom === #clbi-bottom-nav-wrap.top - 8px
         cancelAnimationFrame(state.inertiaRaf);
    */
         state.inertiaRaf = null;
     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();
     $('#clbi-sidebar-lang-selector').removeClass('is-spinning');
     bottomTop = bottomNav.getBoundingClientRect().top;
}
     visualGap = desiredGap * scale;
 
     targetHeight = Math.floor((bottomTop - contentRect.top - visualGap) / scale);
function finishSidebarLanguageSnap(nearestIndex, callback) {
     targetHeight = Math.max(120, targetHeight);
     var state = sidebarLanguageState;
 
    state.baseIndex = normalizeSidebarLanguageIndex(nearestIndex);
     state.selectedIndex = state.baseIndex;
     state.rotation = 0;
     state.dragging = false;


     currentHeight = Math.round(content.getBoundingClientRect().height / scale);
     $('#clbi-sidebar-lang-selector').removeClass('is-snapping is-dragging is-spinning');


     content.style.setProperty('--clbi-content-extra', '0px');
     renderSidebarLanguageWheel();
     content.style.setProperty('height', targetHeight + 'px', 'important');
     updateSidebarLanguageDial();
    content.style.setProperty('max-height', targetHeight + 'px', 'important');


     if (Math.abs(currentHeight - targetHeight) >= 1 && iteration < 4) {
     if (typeof callback === 'function') {
         window.requestAnimationFrame(function () {
         callback(getSidebarLanguageMeta(state.order[state.selectedIndex]));
            updateClbiContentBottomGap(iteration + 1);
        });
     }
     }
}
}


function scheduleClbiContentBottomGap() {
function snapSidebarLanguageToStep(step, animate, callback) {
     window.requestAnimationFrame(function () {
     var state = sidebarLanguageState;
        updateClbiContentBottomGap(0);
     var targetRotation = -step * state.sectorAngle;
     });
     var nearestIndex = normalizeSidebarLanguageIndex(state.baseIndex + step);
     window.setTimeout(function () {
 
        updateClbiContentBottomGap(0);
     cancelSidebarLanguageSpin();
    }, 40);
     clearTimeout(state.snapTimer);
     window.setTimeout(function () {
        updateClbiContentBottomGap(0);
     }, 120);
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
    }, 280);
    window.setTimeout(function () {
        updateClbiContentBottomGap(0);
    }, 520);
}


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


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


function scheduleLeftBillboardAdaptive() {
function snapSidebarLanguageNearest(callback) {
     window.requestAnimationFrame(updateLeftBillboardAdaptive);
     var state = sidebarLanguageState;
     window.setTimeout(updateLeftBillboardAdaptive, 80);
     var step = Math.round(-state.rotation / state.sectorAngle);
     window.setTimeout(updateLeftBillboardAdaptive, 240);
     snapSidebarLanguageToStep(step, true, callback);
}
}


function scheduleLeftSidebarVerticalFit() {
function startSidebarLanguageInertiaSpin(initialVelocity) {
     if (typeof scheduleAdaptiveLeftRecentItems === 'function') {
     var state = sidebarLanguageState;
        scheduleAdaptiveLeftRecentItems();
    var velocity;
     }
    var lastFrame;
 
    cancelSidebarLanguageSpin();
 
     velocity = Math.max(-state.maxSpinVelocity, Math.min(state.maxSpinVelocity, initialVelocity));


     if (typeof scheduleLeftBillboardAdaptive === 'function') {
     if (Math.abs(velocity) < state.minSpinVelocity) {
         scheduleLeftBillboardAdaptive();
         snapSidebarLanguageNearest();
        return;
     }
     }


     window.setTimeout(function () {
     $('#clbi-sidebar-lang-selector').addClass('is-spinning');
        if (typeof scheduleAdaptiveLeftRecentItems === 'function') {
    lastFrame = performance.now();
            scheduleAdaptiveLeftRecentItems();
 
        }
    function frame(now) {
 
        var dt = Math.min(34, Math.max(1, now - lastFrame));
        if (typeof scheduleLeftBillboardAdaptive === 'function') {
         var sign = velocity < 0 ? -1 : 1;
            scheduleLeftBillboardAdaptive();
        var nextSpeed;
         }
    }, 120);
}


        lastFrame = now;
        state.rotation += velocity * dt;
        setSidebarLanguageRotation(state.rotation, false);


// 국가_및_조합 전용 왼쪽 사이드바 이미지
        nextSpeed = Math.max(0, Math.abs(velocity) - (state.spinDecel * dt));
function updateLeftSidebarNationsImage() {
        velocity = sign * nextSpeed;
    $('#clbi-left-nations-image').remove();
}


function setProfileActionLabel(selector, text) {
        if (nextSpeed <= state.minSpinVelocity) {
    var target = $(selector);
            state.inertiaRaf = null;
    var label = target.find('.profile-action-label');
            $('#clbi-sidebar-lang-selector').removeClass('is-spinning');
            snapSidebarLanguageNearest();
            return;
        }


    if (label.length) {
         state.inertiaRaf = requestAnimationFrame(frame);
        label.text(text);
    } else {
         target.text(text);
     }
     }
    state.inertiaRaf = requestAnimationFrame(frame);
}
}


// 사이드바 업데이트
function scheduleSidebarLanguageNavigation(meta) {
function updateSidebar() {
     var status = getSidebarLanguageStatus(meta);
     if (!window.LANG) {
        setTimeout(updateSidebar, 100);
        return;
    }


     var currentLang = getCurrentLang();
     if (!meta || !status.canApply) return;
    var t = (window.LANG && window.LANG[currentLang]) ? window.LANG[currentLang] : window.LANG.ko;


     var newsTitle = t.news || '뉴스';
     clearTimeout(sidebarLanguageState.navigateTimer);
     var changelogTitle = t.changelog || '체인지로그';
     sidebarLanguageState.navigateTimer = setTimeout(function() {
    var recentTitle = t.recentChanges || '최근 변경';
        var title = getLanguageTargetTitle(meta.lang);
    var languageTitle = t.language || '언어';


    $('#clbi-title-left-language').text(languageTitle);
        if (!title || meta.lang === getCurrentLang()) return;
    renderSidebarLanguageBox();


    $('#clbi-title-left-news').text(newsTitle);
        window.location.href = buildWikiPath(title);
     $('#clbi-left-news-changelog-main').text(changelogTitle);
     }, 70);
    $('#clbi-left-news-recent-main').text(recentTitle);
}


    $('#clbi-title-search a').text(t.search);
function setSidebarLanguageSelection(lang) {
     $('#clbi-search-input').attr('placeholder', t.search + '...');
     var state = sidebarLanguageState;
     $('#clbi-title-recent a').text(recentTitle);
     var index = state.order.indexOf(lang);
    $('#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);
     if (index < 0) index = state.order.indexOf(getCurrentLang());
    setProfileActionLabel('#clbi-btn-watchlist', t.watchlist);
     if (index < 0) index = 0;
    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'));
     if (state.raf) {
    var specialPage = String(mw.config.get('wgCanonicalSpecialPageName') || '');
        cancelAnimationFrame(state.raf);
        state.raf = null;
    }


$('#clbi-left-news-changelog-main').text(changelogTitle);
    cancelSidebarLanguageSpin();
$('#clbi-left-news-recent-title').text('RECENT CHANGES');
    clearTimeout(state.snapTimer);


     $('.clbi-user-btn').removeClass('clbi-user-btn-active');
     state.currentLang = lang;
    state.baseIndex = index;
    state.selectedIndex = index;
    state.rotation = 0;
    state.dragging = false;
    state.dragMoved = false;
    state.releaseVelocity = 0;


     if (
     renderSidebarLanguageWheel();
        specialPage === 'Contributions' ||
     updateSidebarLanguageDial();
        specialPage === '기여' ||
}
        pageName.indexOf('특수:기여') === 0 ||
        pageName.indexOf('Special:Contributions') === 0
     ) {
        $('#clbi-btn-contribution').addClass('clbi-user-btn-active');
    }


    if (specialPage === 'Watchlist') {
function moveSidebarLanguageSelection(delta) {
        $('#clbi-btn-watchlist').addClass('clbi-user-btn-active');
    snapSidebarLanguageToStep(-delta, true);
    }
}


    if (
function bindSidebarLanguageSelector() {
        specialPage === '설정' ||
    var state = sidebarLanguageState;
        pageName === '특수:설정' ||
    var selector = document.getElementById('clbi-sidebar-lang-selector');
        pageName === 'Special:설정'
    var fan = document.getElementById('clbi-sidebar-lang-fan');
    ) {
    var apply = document.getElementById('clbi-sidebar-lang-apply');
        $('#clbi-btn-preferences').addClass('clbi-user-btn-active');
    }


     $('.toggleBtn').each(function() {
     if (!selector || !fan || !apply) return;
        var btn = $(this);


        if (!$('#' + btn.data('target')).hasClass('folding-open')) {
    if (state.bound && state.boundElement === selector) return;
            btn.text(t.expand);
        } else {
            btn.text(t.collapse);
        }
    });


     updateLeftSidebarNationsImage();
     state.bound = true;
}
    state.boundElement = selector;


function canShowContentTools() {
     fan.addEventListener('pointerdown', function(e) {
    // 비로그인 사용자는 편집/역사/공유 버튼을 숨김
         cancelSidebarLanguageSpin();
     if (!mw.config.get('wgUserName')) {
        clearTimeout(state.snapTimer);
         return false;
    }


    // MediaWiki가 현재 문서를 편집 가능하지 않다고 판단하면 숨김
        state.dragging = true;
    var isEditable = mw.config.get('wgIsProbablyEditable');
        state.dragMoved = false;
    if (isEditable === false) {
        state.dragStartX = e.clientX;
         return false;
        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;


    var relevantEditable = mw.config.get('wgRelevantPageIsProbablyEditable');
        selector.classList.add('is-dragging');
    if (relevantEditable === false) {
        selector.classList.remove('is-snapping');
        return false;
    }


     return true;
        /*
}
        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.
        */
     });


function getCatlinkNodes(root) {
    fan.addEventListener('pointermove', function(e) {
    var seen = [];
        var now;
    var nodes = [];
        var totalDx;
    var $root = root ? $(root) : $(document);
        var totalDy;
        var frameDx;
        var dt;
        var instantVelocity;


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


    return nodes;
        totalDx = e.clientX - state.dragStartX;
}
        totalDy = (e.clientY || 0) - state.dragStartY;


function getCatlinksTarget(root) {
        if (!state.dragAxis && (Math.abs(totalDx) > 4 || Math.abs(totalDy) > 4)) {
    var $root = root ? $(root) : $(document);
            state.dragAxis = Math.abs(totalDx) >= Math.abs(totalDy) ? 'x' : 'y';
    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')) {
            if (state.dragAxis === 'y') {
        parserOutput = $(root).find('.mw-parser-output').first();
                state.dragging = false;
        main = $(root);
                state.dragMoved = false;
    }
                state.dragAxis = null;
                state.pointerCaptured = false;
                selector.classList.remove('is-dragging');
                return;
            }


    if (!parserOutput.length && root && $(root).is('.mw-parser-output')) {
            if (fan.setPointerCapture && e.pointerId != null) {
        parserOutput = $(root);
                try {
    }
                    fan.setPointerCapture(e.pointerId);
                    state.pointerCaptured = true;
                } catch (err) {
                    state.pointerCaptured = false;
                }
            }
        }


    if (parserOutput.length) return parserOutput;
        if (state.dragAxis !== 'x') return;
    if (main.length) return main;


    if (!root) {
         now = performance.now();
         parserOutput = $('.liberty-content-main .mw-parser-output').first();
         frameDx = e.clientX - state.lastX;
         main = $('.liberty-content-main').first();
         dt = Math.max(1, now - state.lastTime);
         if (parserOutput.length) return parserOutput;
        if (main.length) return main;
    }


    return $();
        if (Math.abs(totalDx) > 3) state.dragMoved = true;
}


var CLBI_CATLINKS_FETCH_TOKEN = 0;
        instantVelocity = (frameDx * state.dragSensitivity) / dt;
        state.releaseVelocity = (state.releaseVelocity * 0.62) + (instantVelocity * 0.38);
        state.lastX = e.clientX;
        state.lastTime = now;


function getCurrentPageTitleForCatlinks() {
        requestSidebarLanguageRotation(state.dragStartRotation + totalDx * state.dragSensitivity);
    return String(
         e.preventDefault();
        mw.config.get('wgPageName') ||
         e.stopPropagation();
         mw.config.get('wgRelevantPageName') ||
    });
         ''
    ).trim();
}


function shouldFetchCatlinks() {
    function finishDrag(e) {
    var pageName = getCurrentPageTitleForCatlinks();
        var velocityAge;
    var specialPage = mw.config.get('wgCanonicalSpecialPageName');
        var throwVelocity;
        var wasHorizontal;


    if (!pageName) return false;
        if (!state.dragging) return;
    if (specialPage) return false;


    return true;
        wasHorizontal = state.dragAxis === 'x';
}
        state.dragging = false;
        selector.classList.remove('is-dragging');


function clearCatlinksInlineHiding(cat) {
        if (fan.releasePointerCapture && state.pointerCaptured && e && e.pointerId != null) {
    if (!cat || !cat.style) return;
            try { fan.releasePointerCapture(e.pointerId); } catch (err) {}
        }


    cat.style.removeProperty('display');
        state.pointerCaptured = false;
    cat.style.removeProperty('visibility');
        state.dragAxis = null;
    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 (!wasHorizontal && !state.dragMoved) {
         if (!this.style) return;
            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) {
        velocityAge = performance.now() - state.lastTime;
    if (!cat) return;
        throwVelocity = velocityAge > 120 ? 0 : state.releaseVelocity;


    $(cat).find('.mw-hidden-catlinks, #mw-hidden-catlinks, .mw-hidden-cats-hidden, .mw-hidden-cats-user-shown').each(function () {
        if (state.dragMoved) {
        this.classList.remove('mw-hidden-cats-hidden');
            state.suppressClickUntil = performance.now() + 180;
         this.classList.add('mw-hidden-cats-user-shown');
         }


         if (this.style) {
         if (state.dragMoved && Math.abs(throwVelocity) >= state.minSpinVelocity) {
            this.style.removeProperty('display');
             startSidebarLanguageInertiaSpin(throwVelocity);
            this.style.removeProperty('visibility');
        } else {
             this.style.removeProperty('height');
             snapSidebarLanguageNearest();
            this.style.removeProperty('max-height');
             this.style.removeProperty('overflow');
         }
         }
    });
}


function getCatlinkTextContent(cat) {
        if (e) {
    var clone;
            e.preventDefault();
     var text;
            e.stopPropagation();
        }
     }


     if (!cat) return '';
     fan.addEventListener('pointerup', finishDrag);
    fan.addEventListener('pointercancel', finishDrag);
    fan.addEventListener('lostpointercapture', function() {
        if (!state.dragging) return;


    clone = cat.cloneNode(true);
        state.dragging = false;
    $(clone).find('script, style').remove();
        state.pointerCaptured = false;
        state.dragAxis = null;
        selector.classList.remove('is-dragging');


    text = String(clone.textContent || '')
        if (state.dragMoved && Math.abs(state.releaseVelocity) >= state.minSpinVelocity) {
        .replace(/\s+/g, ' ')
            state.suppressClickUntil = performance.now() + 180;
        .replace(/^(분류|숨은 분류|Category|Hidden categories)\s*:\s*/i, '')
            startSidebarLanguageInertiaSpin(state.releaseVelocity);
         .replace(/^(분류|숨은 분류|Category|Hidden categories)\s*$/i, '')
         } else {
         .trim();
            snapSidebarLanguageNearest();
         }
    });


     return text;
     apply.addEventListener('click', function(e) {
}
        e.preventDefault();
        e.stopPropagation();


function hasRenderedCatlinkItems(cat) {
        snapSidebarLanguageNearest(function(meta) {
    var hasLink;
            scheduleSidebarLanguageNavigation(meta);
     var hasListText;
        });
     });


     if (!cat) return false;
     selector.addEventListener('keydown', function(e) {
        if (e.key === 'ArrowLeft') {
            moveSidebarLanguageSelection(-1);
            e.preventDefault();
        }


    hasLink = false;
        if (e.key === 'ArrowRight') {
    $(cat).find('a').each(function () {
            moveSidebarLanguageSelection(1);
        var text = String($(this).text() || '').trim();
            e.preventDefault();
        var href = String(this.getAttribute('href') || '').trim();
         }
         if (text || href) hasLink = true;
    });
    if (hasLink) return true;


    hasListText = false;
        if (e.key === 'Enter' || e.key === ' ') {
    $(cat).find('li').each(function () {
            apply.click();
        if (String($(this).text() || '').trim()) hasListText = true;
            e.preventDefault();
        }
     });
     });
    if (hasListText) return true;
    return !!getCatlinkTextContent(cat);
}
}


function normalizeCategoryTitle(rawTitle) {
function renderSidebarLanguageBox() {
     var title = String(rawTitle == null ? '' : rawTitle).trim();
     bindSidebarLanguageSelector();
    setSidebarLanguageSelection(getCurrentLang());


     if (!title) return '';
     if (!sidebarLanguageStatusLoaded) {
 
        loadSidebarLanguageStatusRegistry(function() {
    title = title.replace(/_/g, ' ');
            setSidebarLanguageSelection(getCurrentLang());
 
         });
    if (/^(Category|분류):/i.test(title)) {
         return title;
     }
     }
    return '분류:' + title;
}
}


function makeCategoryLinkTitle(rawTitle) {
function loadRecentChangesList(targetSelector, limit) {
     return String(rawTitle || '')
     var $target = $(targetSelector);
        .replace(/^Category:/i, '')
        .replace(/^분류:/, '')
        .replace(/_/g, ' ')
        .trim();
}


function dedupeCatlinkCategories(categories) {
    if (!$target.length) return;
    var seen = {};
    var result = [];


     (categories || []).forEach(function (item) {
     var lang = getCurrentLang();
        var title = '';
    var t = (window.LANG && window.LANG[lang]) ? window.LANG[lang] : (window.LANG ? window.LANG.ko : null);
        var hidden = false;
    var isNewsList = $target.closest('.clbi-left-news-box').length > 0;


         if (typeof item === 'string') {
    function escapeHtml(value) {
             title = normalizeCategoryTitle(item);
         return String(value == null ? '' : value)
        } else if (item && typeof item === 'object') {
             .replace(/&/g, '&amp;')
             title = normalizeCategoryTitle(item.title || item.name || item.category || '');
            .replace(/</g, '&lt;')
             hidden = item.hidden !== undefined || item.isHidden === true;
            .replace(/>/g, '&gt;')
        }
             .replace(/"/g, '&quot;')
             .replace(/'/g, '&#039;');
    }


        if (!title) return;
    $target.html((t && t.loading) ? t.loading : '불러오는 중...');
        if (seen[title]) return;


         seen[title] = true;
    $.getJSON(
         result.push({ title: title, hidden: hidden });
         '/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 = '';


    return result;
            if (!items || !items.length) {
}
                $target.html('표시할 변경 사항이 없습니다.');
                return;
            }


function getConfigCatlinksCategories() {
            $.each(items, function(i, item) {
    var normal = mw.config.get('wgCategories') || [];
                var label = timeAgo(item.timestamp);
    var hidden = mw.config.get('wgHiddenCategories') || [];
                var title = item.title || '';
    var categories = [];
                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 (!Array.isArray(normal)) normal = [];
            if (isNewsList) {
    if (!Array.isArray(hidden)) hidden = [];
                $target.html(
                    '<div class="news-recent-viewport">' +
                        '<div class="news-recent-stack">' + html + '</div>' +
                    '</div>'
                );


    normal.forEach(function (name) {
                if (typeof ensureNewsBottomFinish === 'function') {
        categories.push({ title: normalizeCategoryTitle(name), hidden: false });
                    ensureNewsBottomFinish();
    });
                }
            } else {
                $target.html(html);
            }


    hidden.forEach(function (name) {
            if (isNewsList && typeof scheduleAdaptiveLeftRecentItems === 'function') {
        categories.push({ title: normalizeCategoryTitle(name), hidden: true });
                scheduleAdaptiveLeftRecentItems();
    });
            }


    return dedupeCatlinkCategories(categories);
            $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');


function markCatlinksReady(cat, pageTitle) {
                if (!wrap.length || !title.length) return;
    if (!cat) return;


    cat.classList.add('catlinks');
                var wrapW = wrap.width();
    cat.classList.add('clbi-catlinks-ready');
                var titleW = title[0].scrollWidth;
    cat.classList.remove('clbi-catlinks-empty');
 
    cat.classList.remove('clbi-catlinks-pending');
                if (titleW > wrapW + 20) {
    cat.classList.remove('clbi-catlinks-loading');
                    var duration = titleW / 40;
    cat.removeAttribute('data-clbi-catlinks-fetching');
    cat.setAttribute('data-clbi-catlinks-page', pageTitle || getCurrentPageTitleForCatlinks());
    clearCatlinksInlineHiding(cat);
    exposeHiddenCatlinks(cat);
}


function markCatlinksEmpty(cat) {
                    title.css({
    if (!cat) 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);


    cat.classList.add('catlinks');
        $target.html((t && t.loadFail) ? t.loadFail : '불러오기 실패');
    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');
function ensureRecentViewport() {
     cat.classList.remove('clbi-catlinks-ready');
     var list = document.getElementById('clbi-left-recent-list');
    cat.classList.remove('clbi-catlinks-empty');
     var viewport;
     cat.classList.add('clbi-catlinks-pending');
     var stack;
    cat.classList.add('clbi-catlinks-loading');
     var children;
     cat.setAttribute('data-clbi-catlinks-fetching', '1');
     cat.setAttribute('data-clbi-catlinks-page', pageTitle || getCurrentPageTitleForCatlinks());
}


function renderFetchedCatlinks(cat, categories, pageTitle) {
    if (!list) return null;
    var container;
    var ul;
    var normalized;


     if (!cat) return false;
     viewport = list.querySelector(':scope > .news-recent-viewport');
    stack = viewport ? viewport.querySelector(':scope > .news-recent-stack') : null;


     normalized = dedupeCatlinkCategories(categories);
     if (viewport && stack) return viewport;


     if (!normalized.length) {
     children = Array.prototype.slice.call(list.children || []);
        markCatlinksEmpty(cat);
        return false;
    }


     cat.innerHTML = '';
     viewport = document.createElement('div');
    cat.classList.add('catlinks');
     viewport.className = 'news-recent-viewport';
     cat.classList.add('clbi-catlinks-api-populated');


     container = document.createElement('div');
     stack = document.createElement('div');
     container.className = 'mw-normal-catlinks';
     stack.className = 'news-recent-stack';
    container.appendChild(document.createTextNode('분류: '));


     ul = document.createElement('ul');
     children.forEach(function (child) {
        if (child.classList && child.classList.contains('news-recent-viewport')) return;
        stack.appendChild(child);
    });


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


        if (!title) return;
    return viewport;
}


        li = document.createElement('li');
function ensureNewsBottomFinish() {
        a = document.createElement('a');
    var newsBox = document.querySelector('#clbi-left-sidebar .clbi-left-news-box');
        a.href = mw.util.getUrl(title);
    var content = newsBox ? newsBox.querySelector('.clbi-news-box') : null;
        a.title = title;
    var finish;
        a.textContent = makeCategoryLinkTitle(title);


        if (item.hidden) {
    if (!content) return null;
            li.className = 'clbi-hidden-category-item';
        }


        li.appendChild(a);
    finish = content.querySelector(':scope > .news-bottom-finish');
        ul.appendChild(li);
    });


     if (!ul.children.length) {
     if (!finish) {
         markCatlinksEmpty(cat);
        finish = document.createElement('div');
         return false;
        finish.className = 'news-bottom-finish';
         finish.setAttribute('aria-hidden', 'true');
         content.appendChild(finish);
     }
     }


    container.appendChild(ul);
     return finish;
    cat.appendChild(container);
    markCatlinksReady(cat, pageTitle);
     return true;
}
}


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


     if (typeof pageTitle === 'function') {
     if (typeof ensureRecentViewport === 'function') {
         callback = pageTitle;
         ensureRecentViewport();
        pageTitle = getCurrentPageTitleForCatlinks();
     }
     }


     pageTitle = String(pageTitle || '').trim();
     if (typeof ensureNewsBottomFinish === 'function') {
 
        ensureNewsBottomFinish();
    if (!pageTitle || !shouldFetchCatlinks()) {
        if (typeof callback === 'function') callback([], pageTitle);
        return;
     }
     }


     if (!mw.Api) {
     if (typeof scheduleClbiContentBottomGap === 'function') {
        if (typeof callback === 'function') callback([], pageTitle);
        scheduleClbiContentBottomGap();
        return;
     }
     }
}


    api = new mw.Api();
function scheduleAdaptiveLeftRecentItems() {
    api.get({
     window.requestAnimationFrame(function () {
        action: 'query',
         updateAdaptiveLeftRecentItems();
        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);
    window.setTimeout(updateAdaptiveLeftRecentItems, 80);
     }).fail(function () {
     window.setTimeout(updateAdaptiveLeftRecentItems, 240);
        if (typeof callback === 'function') callback([], pageTitle);
    });
}
}


function finalizeEmptyCatlinks(cat) {
    if (!cat) return;
    if (!cat.isConnected) return;


    clearCatlinksInlineHiding(cat);
    exposeHiddenCatlinks(cat);


    if (hasRenderedCatlinkItems(cat)) {
function updateClbiContentBottomGap(iteration) {
        markCatlinksReady(cat, getCurrentPageTitleForCatlinks());
    var content = document.querySelector('.container-fluid.liberty-content');
        return;
    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;


     markCatlinksEmpty(cat);
     iteration = iteration || 0;
}


function fetchCatlinksIfNeeded(cat) {
    if (!content || !main || !bottomNav) return;
    var configCategories;
    var pageTitle;
    var requestToken;


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


     pageTitle = getCurrentPageTitleForCatlinks();
     목표:
    .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);
    }


     clearCatlinksInlineHiding(cat);
     contentRect = content.getBoundingClientRect();
     exposeHiddenCatlinks(cat);
     bottomTop = bottomNav.getBoundingClientRect().top;
    visualGap = desiredGap * scale;
    targetHeight = Math.floor((bottomTop - contentRect.top - visualGap) / scale);
    targetHeight = Math.max(120, targetHeight);


     if (hasRenderedCatlinkItems(cat)) {
     currentHeight = Math.round(content.getBoundingClientRect().height / scale);
        markCatlinksReady(cat, pageTitle);
        return;
    }


     configCategories = getConfigCatlinksCategories();
     content.style.setProperty('--clbi-content-extra', '0px');
     if (configCategories.length) {
     content.style.setProperty('height', targetHeight + 'px', 'important');
        renderFetchedCatlinks(cat, configCategories, pageTitle);
    content.style.setProperty('max-height', targetHeight + 'px', 'important');
        return;
    }


     if (!shouldFetchCatlinks()) {
     if (Math.abs(currentHeight - targetHeight) >= 1 && iteration < 4) {
         finalizeEmptyCatlinks(cat);
         window.requestAnimationFrame(function () {
         return;
            updateClbiContentBottomGap(iteration + 1);
         });
     }
     }
}


     if (cat.getAttribute('data-clbi-catlinks-fetching') === '1' && cat.getAttribute('data-clbi-catlinks-page') === pageTitle) return;
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);
}


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


    fetchCatlinksForPage(pageTitle, function (categories, requestedPage) {
function updateLeftBillboardAdaptive() {
        if (requestToken !== CLBI_CATLINKS_FETCH_TOKEN) return;
    /*
        if (requestedPage !== getCurrentPageTitleForCatlinks()) return;
    134 기준: Ad는 이미지/CRT 비율을 유지하는 고정 슬롯이다.
        if (!cat || !cat.isConnected) return;
    남는 세로 공간은 뉴스 박스가 흡수하므로, Ad에 하단 finish를 늘리거나
        if (cat.getAttribute('data-clbi-catlinks-page') !== requestedPage) return;
    title-only 상태로 접는 adaptive 보정은 사용하지 않는다.
    */
    resetLeftBillboardAdaptiveState();
}


        if (!renderFetchedCatlinks(cat, categories, requestedPage)) {
function scheduleLeftBillboardAdaptive() {
            finalizeEmptyCatlinks(cat);
    window.requestAnimationFrame(updateLeftBillboardAdaptive);
        }
    window.setTimeout(updateLeftBillboardAdaptive, 80);
     });
     window.setTimeout(updateLeftBillboardAdaptive, 240);
}
}


function normalizeCatlinksPanel(cat) {
function scheduleLeftSidebarVerticalFit() {
     if (!cat) return;
     if (typeof scheduleAdaptiveLeftRecentItems === 'function') {
        scheduleAdaptiveLeftRecentItems();
    }


     cat.classList.add('catlinks');
     if (typeof scheduleLeftBillboardAdaptive === 'function') {
    clearCatlinksInlineHiding(cat);
        scheduleLeftBillboardAdaptive();
     exposeHiddenCatlinks(cat);
     }


     if (hasRenderedCatlinkItems(cat)) {
     window.setTimeout(function () {
         markCatlinksReady(cat, getCurrentPageTitleForCatlinks());
         if (typeof scheduleAdaptiveLeftRecentItems === 'function') {
         return;
            scheduleAdaptiveLeftRecentItems();
    }
         }


     fetchCatlinksIfNeeded(cat);
        if (typeof scheduleLeftBillboardAdaptive === 'function') {
            scheduleLeftBillboardAdaptive();
        }
     }, 120);
}
}


function createCatlinksPanel(target, className) {
    var cat;


    if (!target || !target.length) return null;
// 시대 문서 전용 왼쪽 사이드바 이미지
 
function updateLeftSidebarNationsImage() {
     cat = document.createElement('div');
     $('#clbi-left-nations-image').remove();
    cat.id = 'catlinks';
    cat.className = className || 'catlinks clbi-catlinks-created clbi-catlinks-pending';
    target.append(cat);
    return cat;
}
}


function prepareSpaCatlinksBeforeInsert(root) {
function setProfileActionLabel(selector, text) {
     var nodes;
     var target = $(selector);
     var target;
     var label = target.find('.profile-action-label');
    var configCategories;
    var pageTitle;


     if (!root) return;
     if (label.length) {
        label.text(text);
    } else {
        target.text(text);
    }
}


    pageTitle = getCurrentPageTitleForCatlinks();
// 사이드바 업데이트
     configCategories = getConfigCatlinksCategories();
function updateSidebar() {
    nodes = getCatlinkNodes(root);
     if (!window.LANG) {
        setTimeout(updateSidebar, 100);
        return;
    }


     nodes.forEach(function (node) {
     var currentLang = getCurrentLang();
        node.classList.add('catlinks');
    var t = (window.LANG && window.LANG[currentLang]) ? window.LANG[currentLang] : window.LANG.ko;
        clearCatlinksInlineHiding(node);
        exposeHiddenCatlinks(node);


        if (hasRenderedCatlinkItems(node)) {
    var newsTitle = t.news || '뉴스';
            markCatlinksReady(node, pageTitle);
    var changelogTitle = t.changelog || '체인지로그';
        } else if (configCategories.length) {
    var recentTitle = t.recentChanges || '최근 변경';
            renderFetchedCatlinks(node, configCategories, pageTitle);
     var languageTitle = t.language || '언어';
        } else {
            markCatlinksEmpty(node);
        }
     });


     if (nodes.length || !configCategories.length) return;
     $('#clbi-title-left-language').text(languageTitle);
    renderSidebarLanguageBox();


     target = getCatlinksTarget(root);
     $('#clbi-title-left-news').text(newsTitle);
     if (!target.length) target = $(root);
     $('#clbi-left-news-changelog-main').text(changelogTitle);
    $('#clbi-left-news-recent-main').text(recentTitle);


     renderFetchedCatlinks(createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending'), configCategories, pageTitle);
     $('#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);


function moveCatlinksToBottom() {
    setProfileActionLabel('#clbi-btn-contribution', t.contribution);
     var main = $('.liberty-content-main').first();
     setProfileActionLabel('#clbi-btn-watchlist', t.watchlist);
     var target = getCatlinksTarget();
     setProfileActionLabel('#clbi-btn-preferences', t.preferences);
     var catlinks = getCatlinkNodes();
     setProfileActionLabel('#clbi-btn-logout', t.logout);
     var configCategories;
     setProfileActionLabel('#clbi-btn-login', t.login);
    var pageTitle;
    var requestToken;


     if (!main.length || !target.length) return;
     var pageName = normalizePageName(mw.config.get('wgPageName'));
    var specialPage = String(mw.config.get('wgCanonicalSpecialPageName') || '');


    pageTitle = getCurrentPageTitleForCatlinks();
$('#clbi-left-news-changelog-main').text(changelogTitle);
$('#clbi-left-news-recent-title').text('RECENT CHANGES');


     catlinks.forEach(function (node) {
     $('.clbi-user-btn').removeClass('clbi-user-btn-active');
        var catNode = $(node);


         if (node.parentNode !== target[0]) {
    if (
             catNode.appendTo(target);
        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);
         }
         }
        normalizeCatlinksPanel(node);
     });
     });


     if (catlinks.length) return;
     updateLeftSidebarNationsImage();
}


    configCategories = getConfigCatlinksCategories();
function canShowContentTools() {
     if (configCategories.length) {
    // 비로그인 사용자는 편집/역사/공유 버튼을 숨김
        renderFetchedCatlinks(createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending'), configCategories, pageTitle);
     if (!mw.config.get('wgUserName')) {
         return;
         return false;
     }
     }


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


     requestToken = ++CLBI_CATLINKS_FETCH_TOKEN;
     var relevantEditable = mw.config.get('wgRelevantPageIsProbablyEditable');
    if (relevantEditable === false) {
        return false;
    }


     fetchCatlinksForPage(pageTitle, function (categories, requestedPage) {
     return true;
        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 getCatlinkNodes(root) {
function initCategoryNavIfAvailable(root) {
    var seen = [];
     /*
    var nodes = [];
     CategoryNav.js는 대문 카테고리 네비를 SVG로 생성한다.
    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();


     Common.js가 SPA로 본문을 갈아끼운 뒤에는 MediaWiki 원래 페이지 로드와 달리
     if (!parserOutput.length && root && $(root).is('.liberty-content-main')) {
    CategoryNav.js의 초기 DOMContentLoaded만으로는 새 mount를 다시 잡지 못할 수 있다.
        parserOutput = $(root).find('.mw-parser-output').first();
    CategoryNav.js 자체도 mw.hook('wikipage.content')를 듣지만, 로드 순서와 SPA 타이밍이
        main = $(root);
     엇갈릴 수 있으므로 Common.js 쪽에서도 존재 여부를 확인한 뒤 한 번 더 호출한다.
     }


    이 함수는 CategoryNav.js가 아직 로드되지 않았으면 아무 것도 하지 않는다.
     if (!parserOutput.length && root && $(root).is('.mw-parser-output')) {
    */
         parserOutput = $(root);
     if (
        window.CLBI &&
        window.CLBI.categoryNav &&
        typeof window.CLBI.categoryNav.init === 'function'
    ) {
         window.CLBI.categoryNav.init(root || document);
     }
     }
}


function removeLegacyMainPageHero() {
    if (parserOutput.length) return parserOutput;
     /*
     if (main.length) return main;
    기존 대문 전용 레거시 요소 정리
    -----------------------------------------
    이전 대문 구조에서는 Common.js가 본문 바깥에 #clbi-main-logo를 직접 삽입하고,
    본문 안의 #clbi-main-crt-hero를 #clbi-main-crt-hero-wrap으로 감싸서
    .liberty-content-main 위쪽으로 재배치했다.


     새 대문은 본문 내부의 .main-portal이 로고, 알림, 카테고리 네비, 이미지 피드,
     if (!root) {
    방명록, 상태 패널을 모두 담당한다. 따라서 Common.js가 별도 로고나 CRT 래퍼를
        parserOutput = $('.liberty-content-main .mw-parser-output').first();
     삽입하면 새 로고/콘텐츠와 중복된다.
        main = $('.liberty-content-main').first();
        if (parserOutput.length) return parserOutput;
        if (main.length) return main;
     }


     여기서는 JS가 만들던 바깥 로고와 CRT 래퍼를 제거하고, 예전 대문 원본이나
     return $();
    캐시된 렌더 결과에 남아 있을 수 있는 #clbi-main-crt-hero도 제거한다.
    */
    $('#clbi-main-logo').remove();
    $('#clbi-main-crt-hero-wrap').remove();
    $('#clbi-main-crt-hero').remove();
}
}


var CLBI_CATLINKS_FETCH_TOKEN = 0;


function setNativePageTitleHiddenHard(hidden) {
function getCurrentPageTitleForCatlinks() {
     var selectors = [
     return String(
         '.liberty-content-header',
         mw.config.get('wgPageName') ||
        '.liberty-content-header .title',
         mw.config.get('wgRelevantPageName') ||
         '.liberty-content-header .title h1',
         ''
        '.liberty-content-header h1',
    ).trim();
         '#firstHeading',
}
        '.firstHeading',
 
        '.mw-first-heading',
function shouldFetchCatlinks() {
        '.page-heading',
    var pageName = getCurrentPageTitleForCatlinks();
        '.page-header',
    var specialPage = mw.config.get('wgCanonicalSpecialPageName');
        '.mw-page-title-main',
        '.mw-page-title-namespace',
        '.mw-page-title-separator'
    ];


     document.querySelectorAll(selectors.join(',')).forEach(function(node) {
     if (!pageName) return false;
        if (!node || !node.style) return;
    if (specialPage) return false;


        if (hidden) {
    return true;
            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() {
function clearCatlinksInlineHiding(cat) {
     var hideTitle = true;
     if (!cat || !cat.style) return;
    var isSystemAssetPage = false;


     if (window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.isSystemAssetPage === 'function') {
     cat.style.removeProperty('display');
        isSystemAssetPage = window.CLBI_PAGE_SHELL.isSystemAssetPage();
    cat.style.removeProperty('visibility');
     }
    cat.style.removeProperty('height');
    cat.style.removeProperty('max-height');
     cat.style.removeProperty('overflow');


     if (isSystemAssetPage) {
     $(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 () {
         hideTitle = true;
        if (!this.style) return;
    } else if (window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.isBackendOrSystemPage === 'function') {
         this.style.removeProperty('display');
         hideTitle = !window.CLBI_PAGE_SHELL.isBackendOrSystemPage();
        this.style.removeProperty('visibility');
     }
        this.style.removeProperty('height');
        this.style.removeProperty('max-height');
         this.style.removeProperty('overflow');
     });
}


    $('body')
function exposeHiddenCatlinks(cat) {
        .toggleClass('page-title-hidden', hideTitle)
    if (!cat) return;
        .toggleClass('page-title-visible', !hideTitle)
        .toggleClass('clbi-system-doc-page', isSystemAssetPage);


     $('.content-tools').css('display', 'none');
     $(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 (isSystemAssetPage && window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.renderSystemDocIndicator === 'function') {
         if (this.style) {
         window.CLBI_PAGE_SHELL.renderSystemDocIndicator();
            this.style.removeProperty('display');
    } else if (!isSystemAssetPage && window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.removeSystemDocIndicator === 'function') {
            this.style.removeProperty('visibility');
        window.CLBI_PAGE_SHELL.removeSystemDocIndicator();
            this.style.removeProperty('height');
    }
            this.style.removeProperty('max-height');
 
            this.style.removeProperty('overflow');
    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() {
function getCatlinkTextContent(cat) {
     var specialPage = mw.config.get('wgCanonicalSpecialPageName');
     var clone;
     if (specialPage === 'Preferences') return;
     var text;


     var pageName = normalizePageName(mw.config.get('wgPageName'));
     if (!cat) return '';
    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);
     clone = cat.cloneNode(true);
     $('body').toggleClass('clbi-main-page', isMainPage);
     $(clone).find('script, style').remove();


     // 모든 문서에서 분류 바를 본문 컨테이너 아래로 이동
     text = String(clone.textContent || '')
    moveCatlinksToBottom();
        .replace(/\s+/g, ' ')
        .replace(/^(분류|숨은 분류|Category|Hidden categories)\s*:\s*/i, '')
        .replace(/^(분류|숨은 분류|Category|Hidden categories)\s*$/i, '')
        .trim();


     if (isMainPage) {
     return text;
        $('.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 본문 구조가 로고/히어로를 담당한다.
function hasRenderedCatlinkItems(cat) {
        // Common.js의 구식 바깥 로고/CRT 재배치 루틴은 사용하지 않는다.
    var hasLink;
        removeLegacyMainPageHero();
    var hasListText;
        $('#clbi-tools-box').remove();


        $('.content-tools').css('display', 'none');
    if (!cat) return false;


         initCategoryNavIfAvailable(document);
    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;


     } else if (isUserProfilePage) {
     hasListText = false;
        $('.liberty-content-header').css('display', 'none');
    $(cat).find('li').each(function () {
         $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').addClass('clbi-hide');
         if (String($(this).text() || '').trim()) hasListText = true;
        $('.catlinks').css('display', 'none');
    });
        $('.liberty-content-main').css('border-radius', '0');
    if (hasListText) return true;


        $('#clbi-main-logo').remove();
    return !!getCatlinkTextContent(cat);
        $('#clbi-main-crt-hero-wrap').remove();
}
        $('#clbi-main-crt-hero').remove();
        $('#clbi-tools-box').remove();


        $('.content-tools').css('display', 'none');
function normalizeCategoryTitle(rawTitle) {
    var title = String(rawTitle == null ? '' : rawTitle).trim();


     } else if (isScreenDoc) {
     if (!title) return '';
        $('.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();
    title = title.replace(/_/g, ' ');
        $('#clbi-main-crt-hero-wrap').remove();


        if ($('#clbi-tools-box').length === 0 && canShowContentTools()) {
    if (/^(Category|분류):/i.test(title)) {
            var $toolsBox = $('<div id="clbi-tools-box" class="clbi-left-box"></div>');
        return title;
            var $toolsTitle = $('<div class="clbi-left-title">관리</div>');
    }
            var $toolsContent = $('<div class="clbi-left-content"></div>');


            $toolsContent.append($('.content-tools .btn-group').clone(true));
    return '분류:' + title;
            $toolsBox.append($toolsTitle).append($toolsContent);
}
            $('#clbi-left-sidebar').append($toolsBox);
        }


         $('.content-tools').css('display', 'none');
function makeCategoryLinkTitle(rawTitle) {
    return String(rawTitle || '')
         .replace(/^Category:/i, '')
        .replace(/^분류:/, '')
        .replace(/_/g, ' ')
        .trim();
}


    } else {
function dedupeCatlinkCategories(categories) {
        $('.liberty-content-header').css('display', '');
    var seen = {};
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').removeClass('clbi-hide');
    var result = [];
        $('.catlinks').css('display', '');
        $('.liberty-content-main').css('border-radius', '0');


        $('#clbi-main-logo').remove();
    (categories || []).forEach(function (item) {
         $('#clbi-main-crt-hero-wrap').remove();
         var title = '';
         $('#clbi-tools-box').remove();
         var hidden = false;
    }


    if (!isUserProfilePage) {
        if (typeof item === 'string') {
        $('.profile-card').remove();
            title = normalizeCategoryTitle(item);
         $('.user-profile-portal').removeClass('user-profile-portal');
         } else if (item && typeof item === 'object') {
    }
            title = normalizeCategoryTitle(item.title || item.name || item.category || '');
            hidden = item.hidden !== undefined || item.isHidden === true;
        }


    $('.content-tools').css('display', 'none');
        if (!title) return;
        if (seen[title]) return;


    applyDefaultPageTitleVisibility();
        seen[title] = true;
     updateSidebar();
        result.push({ title: title, hidden: hidden });
}
     });


// 본문 기본 목차 제거
     return result;
function removeNativeTocFromContent() {
     $('.liberty-content-main #toc, .liberty-content-main .toc').remove();
}
}


// 왼쪽 목차: MediaWiki 문단 ID 가져오기
function getConfigCatlinksCategories() {
function getHeadingId(heading) {
     var normal = mw.config.get('wgCategories') || [];
     if (heading.id) {
    var hidden = mw.config.get('wgHiddenCategories') || [];
        return heading.id;
     var categories = [];
     }


     var headline = heading.querySelector('.mw-headline[id]');
     if (!Array.isArray(normal)) normal = [];
     if (headline && headline.id) {
     if (!Array.isArray(hidden)) hidden = [];
        return headline.id;
    }


     return '';
    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);
}
}


// 왼쪽 목차: MediaWiki 문단 제목 텍스트 가져오기
function markCatlinksReady(cat, pageTitle) {
function getHeadingText(heading) {
     if (!cat) return;
     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();
     cat.classList.add('catlinks');
 
    cat.classList.add('clbi-catlinks-ready');
     return (clone.textContent || '')
    cat.classList.remove('clbi-catlinks-empty');
        .replace(/\s+/g, ' ')
    cat.classList.remove('clbi-catlinks-pending');
        .trim();
    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) {
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);
    cat.classList.add('clbi-catlinks-empty');
        var $wrap = $text.closest('.toc-scroll-wrap');
    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');
}


        if (!$wrap.length) return;
function markCatlinksPending(cat, pageTitle) {
    if (!cat) return;


        var wrapW = Math.floor($wrap.width());
    cat.classList.add('catlinks');
        var textW = Math.ceil(this.scrollWidth);
    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) {
        if (!wrapW || !textW) return;
    var container;
    var ul;
    var normalized;


        if (textW <= wrapW + 12) {
    if (!cat) return false;
            // 왼쪽 목차: 칸을 넘지 않는 제목은 전체 텍스트를 그대로 보여준다.
            $wrap.removeClass('is-scrolling');


            if ($text.data('toc-scroll-enabled')) {
    normalized = dedupeCatlinkCategories(categories);
                $text.css({
                    animation: '',
                    'animation-delay': '',
                    '--scroll-dist': ''
                });
                $text.removeData('toc-scroll-enabled');
                $text.removeData('toc-scroll-key');
            }


            return;
    if (!normalized.length) {
        }
        markCatlinksEmpty(cat);
        return false;
    }


        var scrollDist = '-' + (textW - wrapW + 10) + 'px';
    cat.innerHTML = '';
        var duration = Math.max(7, textW / 38) * 1.25;
    cat.classList.add('catlinks');
        var scrollKey = scrollDist + '|' + duration;
    cat.classList.add('clbi-catlinks-api-populated');


        // 왼쪽 목차: 긴 제목에는 오른쪽 페이드와 스크롤을 적용한다.
    container = document.createElement('div');
        $wrap.addClass('is-scrolling');
    container.className = 'mw-normal-catlinks';
    container.appendChild(document.createTextNode('분류: '));


        // 왼쪽 목차: 같은 값으로 이미 적용된 애니메이션은 다시 초기화하지 않는다.
    ul = document.createElement('ul');
        if ($text.data('toc-scroll-key') === scrollKey) {
            return;
        }


        $text.data('toc-scroll-enabled', true);
    normalized.forEach(function (item) {
         $text.data('toc-scroll-key', scrollKey);
         var title = String(item && item.title ? item.title : '').trim();
        var li;
        var a;


         $text.css({
         if (!title) return;
            // 왼쪽 목차: 페이지 진입 직후에는 잠시 읽을 시간을 준 뒤 흐르게 한다.
            animation: 'toc-scroll-blink-reset ' + duration + 's linear infinite',
            'animation-delay': '1s',
            '--scroll-dist': scrollDist
        });
    });
}


// 목차를 왼쪽 사이드바에 새로 생성
        li = document.createElement('li');
function moveTocToLeftSidebar() {
        a = document.createElement('a');
    removeNativeTocFromContent();
        a.href = mw.util.getUrl(title);
    $('#side-toc-box').remove();
        a.title = title;
    return;
        a.textContent = makeCategoryLinkTitle(title);


    // 왼쪽 목차: MediaWiki가 만든 원래 목차는 본문에서 제거한다.
        if (item.hidden) {
    removeNativeTocFromContent();
            li.className = 'clbi-hidden-category-item';
        }


    var leftSidebar = document.getElementById('clbi-left-sidebar');
        li.appendChild(a);
     if (!leftSidebar) return;
        ul.appendChild(li);
     });


     var content =
     if (!ul.children.length) {
        document.querySelector('.liberty-content-main .mw-parser-output') ||
         markCatlinksEmpty(cat);
         document.querySelector('.liberty-content-main');
        return false;
    }


     if (!content) return;
     container.appendChild(ul);
    cat.appendChild(container);
    markCatlinksReady(cat, pageTitle);
    return true;
}


    var headings = Array.prototype.slice.call(
function fetchCatlinksForPage(pageTitle, callback) {
        content.querySelectorAll('h2, h3')
     var api;
     ).filter(function (heading) {
        if (heading.closest('#toc, .toc, #side-toc-box')) return false;


         var id = getHeadingId(heading);
    if (typeof pageTitle === 'function') {
         var text = getHeadingText(heading);
         callback = pageTitle;
         pageTitle = getCurrentPageTitleForCatlinks();
    }


        if (!id || !text) return false;
    pageTitle = String(pageTitle || '').trim();


        return true;
     if (!pageTitle || !shouldFetchCatlinks()) {
     });
         if (typeof callback === 'function') callback([], pageTitle);
 
    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;
         return;
     }
     }


     if (existingBox) {
     if (!mw.Api) {
         existingBox.remove();
         if (typeof callback === 'function') callback([], pageTitle);
        return;
     }
     }


     if (!headings.length) 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 : [];


    var tocBox = document.createElement('div');
        if (typeof callback === 'function') callback(categories || [], pageTitle);
     tocBox.className = 'clbi-left-box';
     }).fail(function () {
    tocBox.id = 'side-toc-box';
        if (typeof callback === 'function') callback([], pageTitle);
     tocBox.setAttribute('data-toc-key', tocKey);
     });
}


     var title = document.createElement('div');
function finalizeEmptyCatlinks(cat) {
     title.className = 'clbi-left-title';
     if (!cat) return;
     if (!cat.isConnected) return;


     // 왼쪽 목차: 박스 제목은 Lang.js의 현재 UI 언어를 따른다.
     clearCatlinksInlineHiding(cat);
    var currentLang = getCurrentLang();
     exposeHiddenCatlinks(cat);
    var t = (window.LANG && window.LANG[currentLang]) ? window.LANG[currentLang] : window.LANG.ko;
     var tocTitleText = (t && t.toc) ? t.toc : '목차';


     title.textContent = tocTitleText;
     if (hasRenderedCatlinkItems(cat)) {
        markCatlinksReady(cat, getCurrentPageTitleForCatlinks());
        return;
    }


     var body = document.createElement('div');
     markCatlinksEmpty(cat);
    body.className = 'clbi-left-content toc-sidebar-content';
}


     var list = document.createElement('ul');
function fetchCatlinksIfNeeded(cat) {
     list.className = 'generated-toc';
    var configCategories;
     var pageTitle;
     var requestToken;


     headings.forEach(function (heading) {
     if (!cat) return;
        var id = getHeadingId(heading);
    if (!cat.isConnected) return;
        var text = getHeadingText(heading);
        var level = heading.tagName.toLowerCase() === 'h3' ? 3 : 2;


        var item = document.createElement('li');
    pageTitle = getCurrentPageTitleForCatlinks();
        item.className = 'toc-level-' + level;


        var link = document.createElement('a');
    clearCatlinksInlineHiding(cat);
        link.setAttribute('href', '#' + id);
    exposeHiddenCatlinks(cat);


        // 왼쪽 목차: 긴 제목 스크롤을 위해 텍스트를 별도 span으로 감싼다.
    if (hasRenderedCatlinkItems(cat)) {
         var textWrap = document.createElement('span');
         markCatlinksReady(cat, pageTitle);
         textWrap.className = 'toc-scroll-wrap';
         return;
    }


        var textSpan = document.createElement('span');
    configCategories = getConfigCatlinksCategories();
         textSpan.className = 'toc-scroll-text';
    if (configCategories.length) {
         textSpan.textContent = text;
         renderFetchedCatlinks(cat, configCategories, pageTitle);
         return;
    }


         textWrap.appendChild(textSpan);
    if (!shouldFetchCatlinks()) {
         link.appendChild(textWrap);
         finalizeEmptyCatlinks(cat);
         return;
    }


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


     body.appendChild(list);
     requestToken = ++CLBI_CATLINKS_FETCH_TOKEN;
    tocBox.appendChild(title);
     markCatlinksPending(cat, pageTitle);
    tocBox.appendChild(body);
     leftSidebar.appendChild(tocBox);


     // 왼쪽 목차: DOM 배치가 끝난 뒤 긴 제목 스크롤 여부를 계산한다.
     fetchCatlinksForPage(pageTitle, function (categories, requestedPage) {
    requestAnimationFrame(function () {
         if (requestToken !== CLBI_CATLINKS_FETCH_TOKEN) return;
         initTocTitleScroll(tocBox);
        if (requestedPage !== getCurrentPageTitleForCatlinks()) return;
        if (!cat || !cat.isConnected) return;
        if (cat.getAttribute('data-clbi-catlinks-page') !== requestedPage) return;


         setTimeout(function () {
         if (!renderFetchedCatlinks(cat, categories, requestedPage)) {
             initTocTitleScroll(tocBox);
             finalizeEmptyCatlinks(cat);
         }, 120);
         }
     });
     });
}
}


function normalizeCatlinksPanel(cat) {
    if (!cat) return;


// 우측 광고판: 이미지/번역 캡션 목록
     cat.classList.add('catlinks');
var RIGHT_BILLBOARD_ITEMS = [
     clearCatlinksInlineHiding(cat);
     {
     exposeHiddenCatlinks(cat);
        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) {
     if (hasRenderedCatlinkItems(cat)) {
    var items = RIGHT_BILLBOARD_ITEMS;
         markCatlinksReady(cat, getCurrentPageTitleForCatlinks());
 
         return;
     if (!items || !items.length) {
         return {
            file: 'Side-visual-001.png',
            alt: '',
            caption: []
         };
     }
     }


     var normalized = index % items.length;
     fetchCatlinksIfNeeded(cat);
    if (normalized < 0) normalized += items.length;
 
    return items[normalized];
}
}


function getRightBillboardImageUrl(fileName) {
function createCatlinksPanel(target, className) {
     return '/index.php?title=특수:Redirect/file/' + encodeURIComponent(fileName || 'Side-visual-001.png');
     var cat;
}


function getRightBillboardCaptionHtml(item) {
    if (!target || !target.length) return null;
    var lines = item && item.caption ? item.caption : [];
    var html = '';


     function escapeCaptionText(value) {
     cat = document.createElement('div');
        return String(value == null ? '' : value)
    cat.id = 'catlinks';
            .replace(/&/g, '&amp;')
    cat.className = className || 'catlinks clbi-catlinks-created clbi-catlinks-pending';
            .replace(/</g, '&lt;')
    target.append(cat);
            .replace(/>/g, '&gt;')
     return cat;
            .replace(/\"/g, '&quot;')
}
            .replace(/'/g, '&#039;');
     }


    lines.forEach(function(line) {
function prepareSpaCatlinksBeforeInsert(root) {
        var text = String(line == null ? '' : line);
    var nodes;
        var isGap = !text.trim();
    var target;
        var className = 'right-billboard-caption-line' + (isGap ? ' is-gap' : '');
    var configCategories;
        html += '<span class="' + className + '">' + (isGap ? '&nbsp;' : escapeCaptionText(text)) + '</span>';
     var pageTitle;
     });


     return html;
     if (!root) return;
}


function setRightBillboardItem(index) {
    pageTitle = getCurrentPageTitleForCatlinks();
     var box = document.querySelector('.right-billboard-box');
     configCategories = getConfigCatlinksCategories();
     if (!box) return;
     nodes = getCatlinkNodes(root);


     var item = getRightBillboardItem(index);
     nodes.forEach(function (node) {
    var src = getRightBillboardImageUrl(item.file);
        node.classList.add('catlinks');
    var images = box.querySelectorAll('.right-billboard-image');
        clearCatlinksInlineHiding(node);
    var caption = box.querySelector('#right-billboard-caption');
        exposeHiddenCatlinks(node);
    var emptySub = box.querySelector('.right-billboard-empty-sub');


    box.setAttribute('data-billboard-index', String(index));
        if (hasRenderedCatlinkItems(node)) {
     box.classList.remove('is-empty');
            markCatlinksReady(node, pageTitle);
        } else if (configCategories.length) {
            renderFetchedCatlinks(node, configCategories, pageTitle);
        } else {
            markCatlinksEmpty(node);
        }
     });


     Array.prototype.forEach.call(images, function(img) {
     if (nodes.length || !configCategories.length) return;
        img.style.display = '';
        img.setAttribute('src', src);
        img.setAttribute('alt', img.classList.contains('right-billboard-image-base') ? (item.alt || '') : '');
    });


     if (caption) {
     target = getCatlinksTarget(root);
        caption.innerHTML = getRightBillboardCaptionHtml(item);
    if (!target.length) target = $(root);
    }


     if (emptySub) {
     renderFetchedCatlinks(createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending'), configCategories, pageTitle);
        emptySub.textContent = item.file || 'Side-visual-001.png';
    }
}
}


function getRightBillboardItemDuration(item) {
function moveCatlinksToBottom() {
     var duration = item && item.duration ? parseInt(item.duration, 10) : 3000;
     var main = $('.liberty-content-main').first();
    var target = getCatlinksTarget();
    var catlinks = getCatlinkNodes();
    var configCategories;
    var pageTitle;
    var requestToken;


     if (Number.isNaN(duration) || duration < 500) {
     if (!main.length || !target.length) return;
        duration = 3000;
    }


     return duration;
     pageTitle = getCurrentPageTitleForCatlinks();
}


function initRightBillboardCarousel() {
    catlinks.forEach(function (node) {
    var box = document.querySelector('.right-billboard-box');
        var catNode = $(node);
    if (!box || box.getAttribute('data-billboard-ready') === '1') return;


    box.setAttribute('data-billboard-ready', '1');
        if (node.parentNode !== target[0]) {
    box.setAttribute('data-billboard-index', '0');
            catNode.appendTo(target);
        }


     setRightBillboardItem(0);
        normalizeCatlinksPanel(node);
     });


     if (!RIGHT_BILLBOARD_ITEMS || RIGHT_BILLBOARD_ITEMS.length <= 1) return;
     if (catlinks.length) return;


     function scheduleNext() {
     configCategories = getConfigCatlinksCategories();
         var current = parseInt(box.getAttribute('data-billboard-index') || '0', 10);
    if (configCategories.length) {
         if (Number.isNaN(current)) current = 0;
         renderFetchedCatlinks(createCatlinksPanel(target, 'catlinks catlinks-allhidden clbi-catlinks-created clbi-catlinks-pending'), configCategories, pageTitle);
 
         return;
        var currentItem = getRightBillboardItem(current);
    }
        var delay = getRightBillboardItemDuration(currentItem);
 
    if (!shouldFetchCatlinks()) return;


        window.setTimeout(function() {
    requestToken = ++CLBI_CATLINKS_FETCH_TOKEN;
            if (!document.body.contains(box)) return;


            if (!document.hidden) {
    fetchCatlinksForPage(pageTitle, function (categories, requestedPage) {
                setRightBillboardItem(current + 1);
        var cat;
            }


            scheduleNext();
        if (requestToken !== CLBI_CATLINKS_FETCH_TOKEN) return;
         }, delay);
         if (requestedPage !== getCurrentPageTitleForCatlinks()) return;
    }
        if (getCatlinkNodes().length) return;
        if (!categories || !categories.length) return;


     scheduleNext();
        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;
    }


function escapeRightBillboardAttr(value) {
     if (
     return String(value == null ? '' : value)
         window.CLBI &&
         .replace(/&/g, '&amp;')
         window.CLBI.categoryNav &&
         .replace(/</g, '&lt;')
         typeof window.CLBI.categoryNav.init === 'function'
         .replace(/>/g, '&gt;')
    ) {
         .replace(/"/g, '&quot;')
         window.CLBI.categoryNav.init(root || document);
        .replace(/'/g, '&#039;');
    }
}
}


function buildRightBillboardBox() {
function removeLegacyMainPageHero() {
     var billboardInitial = getRightBillboardItem(0);
     /*
     var billboardSrc = getRightBillboardImageUrl(billboardInitial.file);
    기존 대문 전용 레거시 요소 정리
    -----------------------------------------
    이전 대문 구조에서는 Common.js가 본문 바깥에 #clbi-main-logo를 직접 삽입하고,
    본문 안의 #clbi-main-crt-hero를 #clbi-main-crt-hero-wrap으로 감싸서
     .liberty-content-main 위쪽으로 재배치했다.


     return '' +
     새 대문은 본문 내부의 .main-portal이 로고, 알림, 카테고리 네비, 이미지 피드,
        '<div class="clbi-left-box right-billboard-box left-billboard-box left-ad-box" data-billboard-index="0">' +
    방명록, 상태 패널을 모두 담당한다. 따라서 Common.js가 별도 로고나 CRT 래퍼를
            '<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>' +
    여기서는 JS가 만들던 바깥 로고와 CRT 래퍼를 제거하고, 예전 대문 원본이나
            '<div class="clbi-left-content left-ad-content-shell">' +
    캐시된 렌더 결과에 남아 있을 수 있는 #clbi-main-crt-hero도 제거한다.
                '<div class="right-billboard-body">' +
    */
                    '<div class="right-billboard-recess">' +
    $('#clbi-main-logo').remove();
                        '<div class="right-billboard-screen">' +
    $('#clbi-main-crt-hero-wrap').remove();
                            '<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\');}">' +
    $('#clbi-main-crt-hero').remove();
                            '<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';
function setNativePageTitleHiddenHard(hidden) {
var GREAT_WALL_LIST_LIMIT = 0;
    var selectors = [
var greatWallState = {
        '.liberty-content-header',
    data: { entries: {} },
        '.liberty-content-header .title',
    loaded: false,
        '.liberty-content-header .title h1',
    loading: false,
        '.liberty-content-header h1',
    saving: false,
        '#firstHeading',
    selectedOwnEntry: false,
        '.firstHeading',
    statusText: ''
        '.mw-first-heading',
};
        '.page-heading',
        '.page-header',
        '.mw-page-title-main',
        '.mw-page-title-namespace',
        '.mw-page-title-separator'
    ];


function normalizeGreatWallData(data) {
     document.querySelectorAll(selectors.join(',')).forEach(function(node) {
     var normalized = { entries: {} };
        if (!node || !node.style) return;
    var entries = data && data.entries && typeof data.entries === 'object' ? data.entries : {};


    Object.keys(entries).forEach(function(key) {
        if (hidden) {
        var item = entries[key];
            node.setAttribute('data-clbi-title-hidden', 'true');
        var user = item && item.user ? String(item.user) : String(key || '');
            node.style.setProperty('display', 'none', 'important');
        var text = item && item.text ? String(item.text) : '';
            node.style.setProperty('visibility', 'hidden', 'important');
         var timestamp = item && item.timestamp ? String(item.timestamp) : '';
            node.style.setProperty('height', '0', 'important');
 
            node.style.setProperty('min-height', '0', 'important');
        if (!user || !text) return;
            node.style.setProperty('margin', '0', 'important');
 
            node.style.setProperty('padding', '0', 'important');
        normalized.entries[user] = {
            node.style.setProperty('overflow', 'hidden', 'important');
             user: user,
         } else if (node.getAttribute('data-clbi-title-hidden') === 'true') {
             text: text.slice(0, 140),
            node.removeAttribute('data-clbi-title-hidden');
             timestamp: timestamp || new Date(0).toISOString()
            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');
         }
     });
     });
    return normalized;
}
}


function parseGreatWallData(text) {
function applyDefaultPageTitleVisibility() {
     var parsed;
     var hideTitle = true;
    var isSystemAssetPage = false;


     try {
     if (window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.isSystemAssetPage === 'function') {
         parsed = text ? JSON.parse(text) : {};
         isSystemAssetPage = window.CLBI_PAGE_SHELL.isSystemAssetPage();
    } catch (err) {
        console.error('The Great Wall data parse failed:', err);
        parsed = {};
     }
     }


     return normalizeGreatWallData(parsed);
     if (isSystemAssetPage) {
}
        hideTitle = true;
    } else if (window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.isBackendOrSystemPage === 'function') {
        hideTitle = !window.CLBI_PAGE_SHELL.isBackendOrSystemPage();
    }


function stringifyGreatWallData(data) {
    $('body')
    return JSON.stringify(normalizeGreatWallData(data), null, 2) + '\n';
        .toggleClass('page-title-hidden', hideTitle)
}
        .toggleClass('page-title-visible', !hideTitle)
        .toggleClass('clbi-system-doc-page', isSystemAssetPage);


function getGreatWallRevisionText(page) {
    $('.content-tools').css('display', 'none');
    var rev;
    var slot;


     if (!page || !page.revisions || !page.revisions.length) return '';
     if (isSystemAssetPage && window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.renderSystemDocIndicator === 'function') {
 
        window.CLBI_PAGE_SHELL.renderSystemDocIndicator();
     rev = page.revisions[0];
     } else if (!isSystemAssetPage && window.CLBI_PAGE_SHELL && typeof window.CLBI_PAGE_SHELL.removeSystemDocIndicator === 'function') {
        window.CLBI_PAGE_SHELL.removeSystemDocIndicator();
    }


     if (rev.slots && rev.slots.main) {
     if (hideTitle) {
         slot = rev.slots.main;
        $('.liberty-content-header').css('display', 'none');
         return slot.content || slot['*'] || '';
        $('.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);
     }
     }
    return rev.content || rev['*'] || '';
}
}


function fetchGreatWallData() {
function applyMainPageStyle() {
     var api = new mw.Api();
     var specialPage = mw.config.get('wgCanonicalSpecialPageName');
    if (specialPage === 'Preferences') return;


     return api.get({
     var pageName = normalizePageName(mw.config.get('wgPageName'));
        action: 'query',
    var namespaceNumber = mw.config.get('wgNamespaceNumber');
        prop: 'revisions',
    var isMainPage = (pageName === '대문');
        titles: GREAT_WALL_DATA_TITLE,
     var isUserProfilePage = (namespaceNumber === 2);
        rvprop: 'content|timestamp',
    var isScreenDoc = ($('.screen-header').length > 0);
        rvslots: 'main',
    var hideTools = (isMainPage || isUserProfilePage || !canShowContentTools());
        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) {
    $('body').toggleClass('user-profile-page', isUserProfilePage);
            return { entries: {} };
    $('body').toggleClass('clbi-main-page', isMainPage);
        }


        return parseGreatWallData(getGreatWallRevisionText(page));
    // 모든 문서에서 분류 바를 본문 컨테이너 아래로 이동
     }, function(err) {
     moveCatlinksToBottom();
        console.error('The Great Wall load failed:', err);
        return { entries: {} };
    });
}


function getGreatWallEntries(data) {
    if (isMainPage) {
    var entries = data && data.entries && typeof data.entries === 'object' ? data.entries : {};
        $('.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');


    return Object.keys(entries).map(function(key) {
        // 새 대문은 .main-portal 본문 구조가 로고/히어로를 담당한다.
         return entries[key];
         // Common.js의 구식 바깥 로고/CRT 재배치 루틴은 사용하지 않는다.
    }).filter(function(item) {
         removeLegacyMainPageHero();
         return item && item.user && item.text;
         $('#clbi-tools-box').remove();
    }).sort(function(a, b) {
         return String(a.timestamp || '').localeCompare(String(b.timestamp || ''));
    });
}


function getGreatWallMessageTime(timestamp) {
        $('.content-tools').css('display', 'none');
    var date = timestamp ? new Date(timestamp) : null;
    var month;
    var day;
    var hour;
    var minute;


    if (!date || isNaN(date.getTime())) return '—';
        initCategoryNavIfAvailable(document);


     month = String(date.getMonth() + 1).padStart(2, '0');
     } else if (isUserProfilePage) {
    day = String(date.getDate()).padStart(2, '0');
        $('.liberty-content-header').css('display', 'none');
    hour = String(date.getHours()).padStart(2, '0');
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').addClass('clbi-hide');
    minute = String(date.getMinutes()).padStart(2, '0');
        $('.catlinks').css('display', 'none');
        $('.liberty-content-main').css('border-radius', '0');


    return month + '.' + day + ' ' + hour + ':' + minute;
        $('#clbi-main-logo').remove();
}
        $('#clbi-main-crt-hero-wrap').remove();
        $('#clbi-main-crt-hero').remove();
        $('#clbi-tools-box').remove();


function getGreatWallAvatarSrc(user) {
        $('.content-tools').css('display', 'none');
    return '/index.php?title=특수:Redirect/file/Pfp-' + encodeURIComponent(String(user || '')) + '.png';
}


function buildGreatWallEntryHtml(item, currentUser, selectedOwnEntry) {
    } else if (isScreenDoc) {
    var isOwn = currentUser && item.user === currentUser;
        $('.liberty-content-header').css('display', 'none');
    var tag = isOwn ? 'button' : 'div';
        $('.mw-page-title-main').addClass('clbi-hide');
    var attrs = isOwn ? ' type="button" data-great-wall-own-entry="1" aria-label="Edit your wall message"' : '';
        $('.catlinks').css('display', '');
    var className = 'great-wall-entry' + (isOwn ? ' is-own' : '') + (isOwn && selectedOwnEntry ? ' is-selected' : '');
        $('.liberty-content-main').css('border-radius', '0');
    var avatarSrc = getGreatWallAvatarSrc(item.user);
    var messageTime = getGreatWallMessageTime(item.timestamp);
    var isoTime = item.timestamp || '';


    return '' +
         $('#clbi-main-logo').remove();
         '<' + tag + attrs + ' class="' + className + '">' +
        $('#clbi-main-crt-hero-wrap').remove();
            '<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() {
        if ($('#clbi-tools-box').length === 0 && canShowContentTools()) {
    var box = document.getElementById('great-wall-sidebar');
            var $toolsBox = $('<div id="clbi-tools-box" class="clbi-left-box"></div>');
    var list = document.getElementById('great-wall-list');
            var $toolsTitle = $('<div class="clbi-left-title">관리</div>');
    var input = document.getElementById('great-wall-input');
            var $toolsContent = $('<div class="clbi-left-content"></div>');
    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;
            $toolsContent.append($('.content-tools .btn-group').clone(true));
            $toolsBox.append($toolsTitle).append($toolsContent);
            $('#clbi-left-sidebar').append($toolsBox);
        }


    box.classList.toggle('is-guest', !currentUser);
        $('.content-tools').css('display', 'none');
    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 {
     } else {
         list.innerHTML = visibleEntries.map(function(item) {
         $('.liberty-content-header').css('display', '');
            return buildGreatWallEntryHtml(item, currentUser, greatWallState.selectedOwnEntry);
        $('.mw-page-title-main, .mw-page-title-namespace, .mw-page-title-separator').removeClass('clbi-hide');
         }).join('');
         $('.catlinks').css('display', '');
    }
        $('.liberty-content-main').css('border-radius', '0');


    if (list && list.scrollHeight > list.clientHeight) {
        $('#clbi-main-logo').remove();
         list.scrollTop = list.scrollHeight;
        $('#clbi-main-crt-hero-wrap').remove();
         $('#clbi-tools-box').remove();
     }
     }


     if (status) {
     if (!isUserProfilePage) {
         status.textContent = greatWallState.statusText || (currentUser ? (ownEntry ? 'SELECT YOUR MARK TO UPDATE' : 'LEAVE ONE MARK') : 'ACCOUNT REQUIRED');
         $('.profile-card').remove();
        $('.user-profile-portal').removeClass('user-profile-portal');
     }
     }


     if (!input || !submit) return;
     $('.content-tools').css('display', 'none');


     input.disabled = false;
     applyDefaultPageTitleVisibility();
    input.readOnly = false;
     updateSidebar();
     input.removeAttribute('aria-readonly');
}


    if (!currentUser) {
// 본문 기본 목차 제거
        input.disabled = true;
function removeNativeTocFromContent() {
        input.readOnly = false;
    $('.liberty-content-main #toc, .liberty-content-main .toc').remove();
        input.value = '';
}
        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) {
// 왼쪽 목차: MediaWiki 문단 ID 가져오기
        input.disabled = true;
function getHeadingId(heading) {
        input.readOnly = false;
    if (heading.id) {
        submit.disabled = true;
         return heading.id;
        submit.textContent = greatWallState.saving ? 'SAVE' : 'SYNC';
        if (deleteButton) {
            deleteButton.disabled = true;
            deleteButton.title = greatWallState.saving ? 'Saving' : 'Syncing';
        }
         return;
     }
     }


     if (deleteButton) {
    var headline = heading.querySelector('.mw-headline[id]');
         deleteButton.disabled = !ownEntry;
     if (headline && headline.id) {
        deleteButton.title = ownEntry ? 'Delete your mark' : 'No mark to delete';
         return headline.id;
     }
     }


     if (ownEntry && !greatWallState.selectedOwnEntry) {
     return '';
        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() {
// 왼쪽 목차: MediaWiki 문단 제목 텍스트 가져오기
     var input = document.getElementById('great-wall-input');
function getHeadingText(heading) {
     var currentUser = mw.config.get('wgUserName') || '';
     var headline = heading.querySelector('.mw-headline');
    var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
     var source = headline || heading;
     var text = input ? String(input.value || '').trim() : '';
     var clone = source.cloneNode(true);
    var api;


     if (!currentUser) {
     $(clone).find('.mw-editsection, .mw-editsection-bracket, .mw-editsection-divider').remove();
        window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
        return;
    }


     if (ownEntry && !greatWallState.selectedOwnEntry) {
     return (clone.textContent || '')
         greatWallState.statusText = 'SELECT YOUR MARK FIRST';
         .replace(/\s+/g, ' ')
         renderGreatWallBox();
         .trim();
        return;
}
    }


    if (!text) {
// 왼쪽 목차: 긴 제목에 자동 스크롤 적용
         greatWallState.statusText = 'EMPTY MARK';
function initTocTitleScroll(root) {
         renderGreatWallBox();
    var $items = root
        return;
         ? $(root).find('.toc-scroll-text')
    }
         : $('#side-toc-box .toc-scroll-text');


     if (text.length > 140) {
     $items.each(function () {
         text = text.slice(0, 140);
         var $text = $(this);
    }
        var $wrap = $text.closest('.toc-scroll-wrap');


    greatWallState.saving = true;
        if (!$wrap.length) return;
    greatWallState.statusText = 'SAVING';
    renderGreatWallBox();


    fetchGreatWallData().then(function(data) {
        var wrapW = Math.floor($wrap.width());
        data = normalizeGreatWallData(data);
         var textW = Math.ceil(this.scrollWidth);
         data.entries[currentUser] = {
            user: currentUser,
            text: text,
            timestamp: new Date().toISOString()
        };


         api = new mw.Api();
         // 왼쪽 목차: 레이아웃 계산이 끝나지 않았으면 이번 실행에서는 건드리지 않는다.
        return api.postWithToken('csrf', {
         if (!wrapW || !textW) return;
            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();
    });
}


        if (textW <= wrapW + 12) {
            // 왼쪽 목차: 칸을 넘지 않는 제목은 전체 텍스트를 그대로 보여준다.
            $wrap.removeClass('is-scrolling');


function deleteGreatWallEntry() {
            if ($text.data('toc-scroll-enabled')) {
    var input = document.getElementById('great-wall-input');
                $text.css({
    var currentUser = mw.config.get('wgUserName') || '';
                    animation: '',
    var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
                    'animation-delay': '',
    var api;
                    '--scroll-dist': ''
                });
                $text.removeData('toc-scroll-enabled');
                $text.removeData('toc-scroll-key');
            }


    if (!currentUser) {
            return;
        window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
         }
         return;
    }


    if (!ownEntry) {
        var scrollDist = '-' + (textW - wrapW + 10) + 'px';
        greatWallState.statusText = 'NO MARK TO DELETE';
         var duration = Math.max(7, textW / 38) * 1.25;
         renderGreatWallBox();
         var scrollKey = scrollDist + '|' + duration;
         return;
    }


    greatWallState.saving = true;
        // 왼쪽 목차: 긴 제목에는 오른쪽 페이드와 스크롤을 적용한다.
    greatWallState.statusText = 'DELETING';
        $wrap.addClass('is-scrolling');
    renderGreatWallBox();


    fetchGreatWallData().then(function(data) {
        // 왼쪽 목차: 같은 값으로 이미 적용된 애니메이션은 다시 초기화하지 않는다.
        data = normalizeGreatWallData(data);
         if ($text.data('toc-scroll-key') === scrollKey) {
         if (data.entries && data.entries[currentUser]) {
             return;
             delete data.entries[currentUser];
         }
         }


         api = new mw.Api();
         $text.data('toc-scroll-enabled', true);
         return api.postWithToken('csrf', {
         $text.data('toc-scroll-key', scrollKey);
            action: 'edit',
 
            title: GREAT_WALL_DATA_TITLE,
        $text.css({
             text: stringifyGreatWallData(data),
             // 왼쪽 목차: 페이지 진입 직후에는 잠시 읽을 시간을 준 뒤 흐르게 한다.
             summary: 'Delete The Great Wall entry',
             animation: 'toc-scroll-blink-reset ' + duration + 's linear infinite',
             format: 'json'
             'animation-delay': '1s',
        }).then(function() {
             '--scroll-dist': scrollDist
            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;
function moveTocToLeftSidebar() {
     removeNativeTocFromContent();
    $('#side-toc-box').remove();
    return;


     if (mw.Api) {
     // 왼쪽 목차: MediaWiki가 만든 원래 목차는 본문에서 제거한다.
        initGreatWallBox();
    removeNativeTocFromContent();
        return;
    }


     if (mw.loader && mw.loader.using) {
     var leftSidebar = document.getElementById('clbi-left-sidebar');
        mw.loader.using(['mediawiki.api']).then(function() {
    if (!leftSidebar) return;
            initGreatWallBox();
        });
    }
}


function initGreatWallBox() {
     var content =
     var box = document.getElementById('great-wall-sidebar');
        document.querySelector('.liberty-content-main .mw-parser-output') ||
    var input = document.getElementById('great-wall-input');
        document.querySelector('.liberty-content-main');
    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 (!content) return;


     if (!mw.Api) {
     var headings = Array.prototype.slice.call(
         initGreatWallBoxWhenReady();
        content.querySelectorAll('h2, h3')
        return;
    ).filter(function (heading) {
    }
         if (heading.closest('#toc, .toc, #side-toc-box')) return false;


    box.setAttribute('data-great-wall-ready', '1');
        var id = getHeadingId(heading);
        var text = getHeadingText(heading);


    box.addEventListener('click', function(e) {
         if (!id || !text) return false;
         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;
         return true;
 
        greatWallState.selectedOwnEntry = true;
        greatWallState.statusText = 'YOUR MARK SELECTED';
        renderGreatWallBox();
 
        if (input) {
            input.focus();
            input.setSelectionRange(input.value.length, input.value.length);
        }
     });
     });


     document.addEventListener('click', function(e) {
     var tocKey = headings.map(function (heading) {
         var target = e.target;
         return getHeadingId(heading) + '|' + getHeadingText(heading);
        var keepSelection;
    }).join('||');


        if (!greatWallState.selectedOwnEntry || !target || !target.closest) return;
    var existingBox = document.getElementById('side-toc-box');


        keepSelection = target.closest('[data-great-wall-own-entry="1"], .great-wall-editor, .great-wall-compose-sector');
    // 왼쪽 목차: 같은 문서에서 같은 목차를 이미 만들었다면 다시 지우고 만들지 않는다.
    if (existingBox && existingBox.getAttribute('data-toc-key') === tocKey) {
        initTocTitleScroll(existingBox);
        return;
    }


         if (keepSelection) return;
    if (existingBox) {
         existingBox.remove();
    }


        greatWallState.selectedOwnEntry = false;
    if (!headings.length) return;
        greatWallState.statusText = '';
        if (input) input.value = '';
        renderGreatWallBox();
    });


     if (submit) {
     var tocBox = document.createElement('div');
        submit.addEventListener('click', function(e) {
    tocBox.className = 'clbi-left-box';
            e.preventDefault();
    tocBox.id = 'side-toc-box';
            if (!mw.config.get('wgUserName')) {
    tocBox.setAttribute('data-toc-key', tocKey);
                window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
                return;
            }
            saveGreatWallEntry();
        });
    }


     if (deleteButton) {
     var title = document.createElement('div');
        deleteButton.addEventListener('click', function(e) {
    title.className = 'clbi-left-title';
            e.preventDefault();
            deleteGreatWallEntry();
        });
    }


     if (input) {
     // 왼쪽 목차: 박스 제목은 Lang.js의 현재 UI 언어를 따른다.
        input.addEventListener('keydown', function(e) {
    var currentLang = getCurrentLang();
            if (e.key === 'Enter') {
    var t = (window.LANG && window.LANG[currentLang]) ? window.LANG[currentLang] : window.LANG.ko;
                e.preventDefault();
    var tocTitleText = (t && t.toc) ? t.toc : '목차';
                saveGreatWallEntry();
            }
        });


        input.addEventListener('input', function() {
    title.textContent = tocTitleText;
            if (input.value.length > 140) {
                input.value = input.value.slice(0, 140);
            }
        });
    }


     greatWallState.loading = true;
     var body = document.createElement('div');
     greatWallState.statusText = 'SYNCING WALL';
     body.className = 'clbi-left-content toc-sidebar-content';
    renderGreatWallBox();


     fetchGreatWallData().then(function(data) {
     var list = document.createElement('ul');
        greatWallState.data = normalizeGreatWallData(data);
    list.className = 'generated-toc';
        greatWallState.loaded = true;
        greatWallState.loading = false;
        greatWallState.selectedOwnEntry = false;
        greatWallState.statusText = '';
        renderGreatWallBox();
    });
}


function buildGreatWallBox() {
    headings.forEach(function (heading) {
    return '' +
         var id = getHeadingId(heading);
         '<div id="great-wall-sidebar" class="clbi-right-box great-wall-sidebar">' +
        var text = getHeadingText(heading);
            '<div class="clbi-right-title great-wall-title">' +
        var level = heading.tagName.toLowerCase() === 'h3' ? 3 : 2;
                '<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="Leave your mark">' +
                    '<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 item = document.createElement('li');
    var portal = document.querySelector('.main-portal');
        item.className = 'toc-level-' + level;
    var guestbook = portal ? portal.querySelector('.guestbook-device') : null;
    var sideScreen;
    var grid;


    if (!portal || !guestbook) return;
        var link = document.createElement('a');
        link.setAttribute('href', '#' + id);


    sideScreen = guestbook.closest ? guestbook.closest('.side-screen') : null;
        // 왼쪽 목차: 긴 제목 스크롤을 위해 텍스트를 별도 span으로 감싼다.
    grid = sideScreen && sideScreen.closest ? sideScreen.closest('.console-grid') : null;
        var textWrap = document.createElement('span');
        textWrap.className = 'toc-scroll-wrap';


    if (guestbook.parentNode) {
        var textSpan = document.createElement('span');
         guestbook.parentNode.removeChild(guestbook);
         textSpan.className = 'toc-scroll-text';
    }
        textSpan.textContent = text;


    if (sideScreen && !(sideScreen.textContent || '').trim() && !sideScreen.querySelector('img,svg,video,canvas,form,input,button,a')) {
        textWrap.appendChild(textSpan);
         if (sideScreen.parentNode) {
         link.appendChild(textWrap);
            sideScreen.parentNode.removeChild(sideScreen);
        }


         if (grid) {
         item.appendChild(link);
            grid.style.gridTemplateColumns = 'minmax(0,1fr)';
        list.appendChild(item);
        }
     });
     }


     portal.classList.add('is-great-wall-relocated');
     body.appendChild(list);
}
    tocBox.appendChild(title);
    tocBox.appendChild(body);
    leftSidebar.appendChild(tocBox);


function buildSiteInformationBox() {
     // 왼쪽 목차: DOM 배치가 끝난 뒤 긴 제목 스크롤 여부를 계산한다.
     return '' +
    requestAnimationFrame(function () {
        '<div class="clbi-right-box site-info-sidebar">' +
        initTocTitleScroll(tocBox);
            '<div class="clbi-right-title site-info-title">' +
 
                '<span>정보</span>' +
        setTimeout(function () {
            '</div>' +
             initTocTitleScroll(tocBox);
            '<div class="clbi-right-content site-info-content">' +
         }, 120);
                '<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 RIGHT_BILLBOARD_ITEMS = [
    var header = $('.liberty-content-header');
     {
     var content = $('.liberty-content');
         file: 'Side-visual-001.png',
 
        alt: 'PROOF TO THE WORLD / YOU ONCE PART OF IT',
    if (header.length && content.length) {
         duration: 3000,
         header.prependTo(content);
         caption: [
    }
             '"당신이 한때 이 세계의',
 
            '',
    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'
        file: 'Side-visual-002.png',
            : '/index.php?title=특수:Redirect/file/Pfp-default.png';
        alt: 'APPLY NOW',
 
        duration: 1000,
         var userBox;
        caption: [
 
            '"지금 지원하세요!"'
         if (isLoggedIn) {
        ]
             userBox =
    },
                '<div class="clbi-right-box profile-card-box">' +
    {
                    '<div id="clbi-user-avatar-wrap" class="profile-identity-panel">' +
        file: 'Side-visual-003.png',
                        '<div class="profile-avatar-stage">' +
        alt: 'APPLY NOW',
                            '<img id="clbi-user-avatar" src="' + avatarSrc + '" onerror="this.onerror=null;this.src=\'/index.php?title=특수:Redirect/file/Pfp-default.png\';">' +
        duration: 1000,
                        '</div>' +
         caption: [
                        '<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">' +
        file: 'Side-visual-002.png',
                        '<div class="profile-quick-actions" aria-label="프로필 빠른 메뉴">' +
        alt: 'APPLY NOW',
                            '<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>' +
        duration: 1000,
                            '<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>' +
        caption: [
                            '<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>' +
function getRightBillboardItem(index) {
                    '</div>' +
    var items = RIGHT_BILLBOARD_ITEMS;
                '</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 {
    if (!items || !items.length) {
            greatWallBox = buildGreatWallBox();
         return {
         } catch (err) {
             file: 'Side-visual-001.png',
             console.error('The Great Wall build failed:', err);
            alt: '',
            greatWallBox = '';
            caption: []
        }
        };
    }
 
    var normalized = index % items.length;
    if (normalized < 0) normalized += items.length;


        try {
    return items[normalized];
            siteInformationBox = buildSiteInformationBox();
}
        } catch (err) {
            console.error('Site information build failed:', err);
            siteInformationBox = '';
        }


function getRightBillboardImageUrl(fileName) {
    return '/index.php?title=특수:Redirect/file/' + encodeURIComponent(fileName || 'Side-visual-001.png');
}


        var sidebar = userBox + greatWallBox + siteInformationBox;
function getRightBillboardCaptionHtml(item) {
    var lines = item && item.caption ? item.caption : [];
    var html = '';


         $('.content-wrapper').append('<div id="clbi-right-sidebar">' + sidebar + '</div>');
    function escapeCaptionText(value) {
        initGreatWallBoxWhenReady();
         return String(value == null ? '' : value)
        removeMainPortalGuestbookPreview();
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\"/g, '&quot;')
            .replace(/'/g, '&#039;');
     }
     }


     initGreatWallBoxWhenReady();
     lines.forEach(function(line) {
     removeMainPortalGuestbookPreview();
        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;
}


     if ($('#clbi-left-sidebar').length === 0) {
function setRightBillboardItem(index) {
var leftBillboardBox = '';
     var box = document.querySelector('.right-billboard-box');
    if (!box) return;


        try {
    var item = getRightBillboardItem(index);
            leftBillboardBox = buildRightBillboardBox();
    var src = getRightBillboardImageUrl(item.file);
        } catch (err) {
    var images = box.querySelectorAll('.right-billboard-image');
            console.error('Left billboard build failed:', err);
    var caption = box.querySelector('#right-billboard-caption');
            leftBillboardBox = '';
    var emptySub = box.querySelector('.right-billboard-empty-sub');
        }


var leftSidebar =
     box.setAttribute('data-billboard-index', String(index));
     '<div id="clbi-left-sidebar">' +
    box.classList.remove('is-empty');
        '<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>' +
    Array.prototype.forEach.call(images, function(img) {
                '<div class="news-left-changelog-feed">' +
        img.style.display = '';
                    '<a href="/index.php/체인지로그" class="news-post-item">' +
        img.setAttribute('src', src);
                        '<div class="news-post-title-wrap">' +
        img.setAttribute('alt', img.classList.contains('right-billboard-image-base') ? (item.alt || '') : '');
                            '<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>' +
    if (caption) {
        caption.innerHTML = getRightBillboardCaptionHtml(item);
    }


                '<div class="news-feed-title" id="clbi-left-news-recent-title">RECENT CHANGES</div>' +
    if (emptySub) {
                '<div class="news-left-recent-feed" id="clbi-left-recent-list">불러오는 중...</div>' +
        emptySub.textContent = item.file || 'Side-visual-001.png';
    }
}


                '<a class="news-fill-image-slot" id="clbi-left-news-fill-image" href="/index.php/특수:최근바뀜" aria-label="최근 바뀜으로 이동">' +
function getRightBillboardItemDuration(item) {
                    '<div class="news-fill-image-frame">' +
    var duration = item && item.duration ? parseInt(item.duration, 10) : 3000;
                        '<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>' +
    if (Number.isNaN(duration) || duration < 500) {
         '</div>' +
         duration = 3000;
        leftBillboardBox +
     }
     '</div>';


        $('.content-wrapper').prepend(leftSidebar);
    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);


        renderSidebarLanguageBox();
    if (!RIGHT_BILLBOARD_ITEMS || RIGHT_BILLBOARD_ITEMS.length <= 1) return;
        loadRecentChangesList('#clbi-left-recent-list', 10);
        scheduleAdaptiveLeftRecentItems();
        scheduleLeftBillboardAdaptive();
        scheduleClbiContentBottomGap();
        updateLeftSidebarNationsImage();
    }


     try {
     function scheduleNext() {
        initRightBillboardCarousel();
         var current = parseInt(box.getAttribute('data-billboard-index') || '0', 10);
    } catch (err) {
        if (Number.isNaN(current)) current = 0;
         console.error('Right billboard carousel failed:', err);
    }


    if (typeof window.normalizeClbiShellDomOrder === 'function') window.normalizeClbiShellDomOrder();
        var currentItem = getRightBillboardItem(current);
    applyMainPageStyle();
        var delay = getRightBillboardItemDuration(currentItem);
    initClbiCustomDocumentScrollbars();
    initCategoryNavIfAvailable(document);


    if (window.ProgressSystemWebUi && typeof window.ProgressSystemWebUi.boot === 'function') {
        window.setTimeout(function() {
        window.ProgressSystemWebUi.boot('initSidebars');
            if (!document.body.contains(box)) return;
    }


    $('#side-toc-box').remove();
            if (!document.hidden) {
                setRightBillboardItem(current + 1);
            }


    mw.loader.using(['mediawiki.api']).then(function() {
             scheduleNext();
        setTimeout(function() {
         }, delay);
             initNotifications();
    }
            initProfile();
            moveTocToLeftSidebar();
         }, 300);


        setTimeout(moveTocToLeftSidebar, 800);
    scheduleNext();
        setTimeout(moveTocToLeftSidebar, 1500);
    });
}
}


$(function() {
    loadLangScript(function() {
        setTimeout(function() {
            initSidebars();
        }, 100);
    });
});


$(document).on('click.profileQuickPlaceholder', '#profile-quick-inventory, #profile-quick-achievements', function(e) {
function escapeRightBillboardAttr(value) {
    e.preventDefault();
    return String(value == null ? '' : value)
    e.stopPropagation();
        .replace(/&/g, '&amp;')
});
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}


function extractJsonArrayAfterMwConfigKey(text, key) {
function buildRightBillboardBox() {
     var needle = '"' + key + '"';
     var billboardInitial = getRightBillboardItem(0);
     var keyIndex = String(text || '').indexOf(needle);
     var billboardSrc = getRightBillboardImageUrl(billboardInitial.file);
    var start;
    var i;
    var depth = 0;
    var inString = false;
    var escaped = false;


     if (keyIndex === -1) return null;
     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>';
}


    start = String(text || '').indexOf('[', keyIndex + needle.length);
    if (start === -1) return null;


    for (i = start; i < text.length; i += 1) {
var GREAT_WALL_DATA_TITLE = '프로젝트:The_Great_Wall/Data.json';
        var ch = text.charAt(i);
var GREAT_WALL_LIST_LIMIT = 0;
var greatWallState = {
    data: { entries: {} },
    loaded: false,
    loading: false,
    saving: false,
    selectedOwnEntry: false,
    statusText: ''
};


        if (inString) {
function normalizeGreatWallData(data) {
            if (escaped) {
    var normalized = { entries: {} };
                escaped = false;
    var entries = data && data.entries && typeof data.entries === 'object' ? data.entries : {};
            } else if (ch === '\\') {
 
                escaped = true;
    Object.keys(entries).forEach(function(key) {
            } else if (ch === '"') {
        var item = entries[key];
                inString = false;
        var user = item && item.user ? String(item.user) : String(key || '');
            }
        var text = item && item.text ? String(item.text) : '';
            continue;
        var timestamp = item && item.timestamp ? String(item.timestamp) : '';
        }


         if (ch === '"') {
         if (!user || !text) return;
            inString = true;
            continue;
        }


         if (ch === '[') depth += 1;
         normalized.entries[user] = {
        if (ch === ']') {
             user: user,
             depth -= 1;
             text: text.slice(0, 140),
             if (depth === 0) {
            timestamp: timestamp || new Date(0).toISOString()
                try {
         };
                    return JSON.parse(text.slice(start, i + 1));
     });
                } catch (err) {
                    return null;
                }
            }
         }
     }


     return null;
     return normalized;
}
}


function extractJsonStringAfterMwConfigKey(text, key) {
function parseGreatWallData(text) {
     var needle = '"' + key + '"';
     var parsed;
    var keyIndex = String(text || '').indexOf(needle);
    var colon;
    var start;
    var i;
    var escaped = false;


     if (keyIndex === -1) return null;
     try {
        parsed = text ? JSON.parse(text) : {};
    } catch (err) {
        console.error('The Great Wall data parse failed:', err);
        parsed = {};
    }


     colon = text.indexOf(':', keyIndex + needle.length);
     return normalizeGreatWallData(parsed);
    if (colon === -1) return null;
}


    start = text.indexOf('"', colon + 1);
function stringifyGreatWallData(data) {
     if (start === -1) return null;
     return JSON.stringify(normalizeGreatWallData(data), null, 2) + '\n';
}


    for (i = start + 1; i < text.length; i += 1) {
function getGreatWallRevisionText(page) {
        var ch = text.charAt(i);
    var rev;
    var slot;


        if (escaped) {
    if (!page || !page.revisions || !page.revisions.length) return '';
            escaped = false;
            continue;
        }


        if (ch === '\\') {
    rev = page.revisions[0];
            escaped = true;
            continue;
        }


        if (ch === '"') {
    if (rev.slots && rev.slots.main) {
            try {
        slot = rev.slots.main;
                return JSON.parse(text.slice(start, i + 1));
        return slot.content || slot['*'] || '';
            } catch (err) {
                return text.slice(start + 1, i);
            }
        }
     }
     }


     return null;
     return rev.content || rev['*'] || '';
}
}


function syncCatlinksConfigFromSpaDocument(doc) {
function fetchGreatWallData() {
     var scripts = doc ? doc.querySelectorAll('script') : [];
     var api = new mw.Api();
    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) {
     return api.get({
         text = scripts[i].textContent || '';
        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 (categories === null) {
         if (!page || page.missing) {
             value = extractJsonArrayAfterMwConfigKey(text, 'wgCategories');
             return { entries: {} };
            if (Array.isArray(value)) categories = value;
         }
         }


         if (hiddenCategories === null) {
         return parseGreatWallData(getGreatWallRevisionText(page));
            value = extractJsonArrayAfterMwConfigKey(text, 'wgHiddenCategories');
    }, function(err) {
            if (Array.isArray(value)) hiddenCategories = value;
        console.error('The Great Wall load failed:', err);
        }
        return { entries: {} };
    });
}


        if (relevantPageName === null) {
function getGreatWallEntries(data) {
            value = extractJsonStringAfterMwConfigKey(text, 'wgRelevantPageName');
    var entries = data && data.entries && typeof data.entries === 'object' ? data.entries : {};
            if (value !== null) relevantPageName = value;
 
        }
    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 || ''));
    });
}


        if (pageName === null) {
function getGreatWallMessageTime(timestamp) {
            value = extractJsonStringAfterMwConfigKey(text, 'wgPageName');
    var date = timestamp ? new Date(timestamp) : null;
            if (value !== null) pageName = value;
    var month;
        }
    var day;
     }
    var hour;
     var minute;


     mw.config.set('wgCategories', Array.isArray(categories) ? categories : []);
     if (!date || isNaN(date.getTime())) return '';
    mw.config.set('wgHiddenCategories', Array.isArray(hiddenCategories) ? hiddenCategories : []);


     if (relevantPageName !== null) {
     month = String(date.getMonth() + 1).padStart(2, '0');
        mw.config.set('wgRelevantPageName', relevantPageName);
    day = String(date.getDate()).padStart(2, '0');
     } else if (pageName !== null) {
     hour = String(date.getHours()).padStart(2, '0');
        mw.config.set('wgRelevantPageName', pageName);
    minute = String(date.getMinutes()).padStart(2, '0');
    }


     CLBI_CATLINKS_FETCH_TOKEN += 1;
     return month + '.' + day + ' ' + hour + ':' + minute;
}
}


// SPA 네비게이션
function getGreatWallAvatarSrc(user) {
function shouldSkip(url) {
     return '/index.php?title=특수:Redirect/file/Pfp-' + encodeURIComponent(String(user || '')) + '.png';
     return url.match(/action=edit|action=submit|action=history|action=delete|action=protect|action=purge|특수:로그인|특수:로그아웃|Special:UserLogin|Special:UserLogout|특수:사용자정보|특수:비밀번호바꾸기|uselang=/);
}
}


$(function() {
function buildGreatWallEntryHtml(item, currentUser, selectedOwnEntry) {
     if (window._spaInitialized) return;
     var isOwn = currentUser && item.user === currentUser;
     window._spaInitialized = true;
    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 || '';


     function isInternal(url) {
     return '' +
        var a = document.createElement('a');
        '<' + tag + attrs + ' class="' + className + '">' +
        a.href = url;
            '<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;;">' +
        return a.hostname === window.location.hostname;
            '<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;
     });


     function getCachedSpaPageHtml(url) {
     if (greatWallState.loading && !greatWallState.loaded) {
         if (!window.EntryStore || typeof window.EntryStore.getTextSync !== 'function') return '';
         list.innerHTML = '<div class="great-wall-empty">SYNCING WALL</div>';
         return window.EntryStore.getTextSync(url) || window.EntryStore.getTextSync(String(url || '').replace(/^https?:\/\/[^/]+/i, '')) || '';
    } 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('');
     }
     }


     function fetchSpaPageHtml(url) {
     if (list && list.scrollHeight > list.clientHeight) {
        var cached = getCachedSpaPageHtml(url);
         list.scrollTop = list.scrollHeight;
        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 (status) {
         /*
         // Status text is intentionally suppressed in the composer strip; the area is spacing-only UI.
        Initial boot prepares entry artifacts; SPA is only allowed to consume them.
         status.textContent = '';
        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) {
     if (!input || !submit) return;
        invalidateProfileRender();


        return fetchSpaPageHtml(url)
    input.disabled = false;
            .then(function(html) {
    input.readOnly = false;
                var parser = new DOMParser();
    input.removeAttribute('aria-readonly');
                var doc = parser.parseFromString(html, 'text/html');


                var scripts = doc.querySelectorAll('script');
    if (!currentUser) {
                for (var i = 0; i < scripts.length; i++) {
        input.disabled = true;
                    var src = scripts[i].textContent;
        input.readOnly = false;
        input.value = '';
        input.placeholder = '담벼락';
        submit.textContent = 'LOGIN';
        submit.disabled = false;
        if (deleteButton) {
            deleteButton.disabled = true;
            deleteButton.title = 'Login required';
        }
        return;
    }


                    if (src.indexOf('wgNamespaceNumber') !== -1) {
    if (greatWallState.saving || greatWallState.loading) {
                        var match = src.match(/"wgNamespaceNumber":(-?\d+)/);
        input.disabled = true;
                        if (match) mw.config.set('wgNamespaceNumber', parseInt(match[1], 10));
        input.readOnly = false;
        submit.disabled = true;
        submit.textContent = greatWallState.saving ? 'SAVE' : 'SYNC';
        if (deleteButton) {
            deleteButton.disabled = true;
            deleteButton.title = greatWallState.saving ? 'Saving' : 'Syncing';
        }
        return;
    }


                        var matchTitle = src.match(/"wgTitle":"([^"]+)"/);
    if (deleteButton) {
                        if (matchTitle) mw.config.set('wgTitle', matchTitle[1]);
        deleteButton.disabled = !ownEntry;
        deleteButton.title = ownEntry ? 'Delete your mark' : 'No mark to delete';
    }


                        var matchPage = src.match(/"wgPageName":"([^"]+)"/);
    if (ownEntry && !greatWallState.selectedOwnEntry) {
                        if (matchPage) mw.config.set('wgPageName', matchPage[1]);
        input.disabled = false;
        input.readOnly = true;
        input.setAttribute('aria-readonly', 'true');
        input.value = '';
        input.placeholder = '담벼락';
        submit.disabled = true;
        submit.textContent = 'UPDATE';
        return;
    }


                        var matchArticle = src.match(/"wgArticleId":(\d+)/);
    input.disabled = false;
                        if (matchArticle) {
    input.readOnly = false;
                            mw.config.set('wgArticleId', parseInt(matchArticle[1], 10));
    input.removeAttribute('aria-readonly');
                        } else {
    input.placeholder = '담벼락';
                            mw.config.set('wgArticleId', 0);
    if (ownEntry && greatWallState.selectedOwnEntry && !input.value) {
                        }
        input.value = ownEntry.text || '';
    }
    submit.disabled = false;
    submit.textContent = ownEntry ? 'UPDATE' : 'POST';
}


                        var matchIsMainPage = src.match(/"wgIsMainPage":(true|false)/);
function saveGreatWallEntry() {
                        if (matchIsMainPage) {
    var input = document.getElementById('great-wall-input');
                            mw.config.set('wgIsMainPage', matchIsMainPage[1] === 'true');
    var currentUser = mw.config.get('wgUserName') || '';
                        } else {
    var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
                            mw.config.set('wgIsMainPage', false);
    var text = input ? String(input.value || '').trim() : '';
                        }
    var api;


                        var matchSpecial = src.match(/"wgCanonicalSpecialPageName":"([^"]+)"/);
    if (!currentUser) {
                        if (matchSpecial) {
        window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
                            mw.config.set('wgCanonicalSpecialPageName', matchSpecial[1]);
        return;
                        } else {
    }
                            mw.config.set('wgCanonicalSpecialPageName', false);
                        }
                        break;
                    }
                }


                syncCatlinksConfigFromSpaDocument(doc);
    if (ownEntry && !greatWallState.selectedOwnEntry) {
        greatWallState.statusText = '';
        renderGreatWallBox();
        return;
    }


                var newContent = doc.querySelector('.liberty-content-main');
    if (!text) {
                var newTitle = doc.querySelector('.mw-page-title-main');
        greatWallState.statusText = 'EMPTY MARK';
                var newHead = doc.querySelector('title');
        renderGreatWallBox();
                var newHeader = doc.querySelector('.liberty-content-header');
        return;
    }


                if (newContent) {
    if (text.length > 140) {
                    prepareDetachedEntryContent(newContent);
        text = text.slice(0, 140);
                    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) {
    greatWallState.saving = true;
                    $('.mw-page-title-main').html(newTitle.innerHTML);
    greatWallState.statusText = 'SAVING';
                }
    renderGreatWallBox();


                if (newHead) {
    fetchGreatWallData().then(function(data) {
                    document.title = newHead.textContent;
        data = normalizeGreatWallData(data);
                }
        data.entries[currentUser] = {
            user: currentUser,
            text: text,
            timestamp: new Date().toISOString()
        };


                if (newHeader) {
        api = new mw.Api();
                    $('.liberty-content-header').html(newHeader.innerHTML);
        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();
    });
}


                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') {
function deleteGreatWallEntry() {
                    window.ProgressSystemWebUi.handleSpaPageView();
    var input = document.getElementById('great-wall-input');
                } else if (window.ProgressSystemWebUi && typeof window.ProgressSystemWebUi.boot === 'function') {
    var currentUser = mw.config.get('wgUserName') || '';
                    window.ProgressSystemWebUi.boot('spa');
    var ownEntry = currentUser && greatWallState.data.entries ? greatWallState.data.entries[currentUser] : null;
                }
    var api;


                $('#side-toc-box').remove();
    if (!currentUser) {
                setTimeout(moveTocToLeftSidebar, 100);
        window.location.href = '/index.php?title=특수:로그인&returnto=' + encodeURIComponent(mw.config.get('wgPageName') || '대문');
                setTimeout(moveTocToLeftSidebar, 500);
        return;
                setTimeout(moveTocToLeftSidebar, 1200);
    }


                mw.loader.using(['mediawiki.api']).then(function() {
    if (!ownEntry) {
                    initProfile();
        greatWallState.statusText = 'NO MARK TO DELETE';
                    moveTocToLeftSidebar();
        renderGreatWallBox();
                });
        return;
            })
            .catch(function (err) {
                console.error('SPA page load failed:', err);
                $('body').removeClass('page-loading');
            });
     }
     }


// 목차 링크는 전용 처리
    greatWallState.saving = true;
$(document).on('click', '#side-toc-box a, #toc a, .toc a', function(e) {
    greatWallState.statusText = 'DELETING';
    var href = $(this).attr('href');
    renderGreatWallBox();
    if (!href || href.charAt(0) !== '#') return;
 
    fetchGreatWallData().then(function(data) {
        data = normalizeGreatWallData(data);
        if (data.entries && data.entries[currentUser]) {
            delete data.entries[currentUser];
        }


     var rawId = href.slice(1);
        api = new mw.Api();
     if (!rawId) return;
        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();
     });
}


     var decodedId = rawId;
function initGreatWallBoxWhenReady() {
     if (!document.getElementById('great-wall-sidebar')) return;


     try {
     if (mw.Api) {
         decodedId = decodeURIComponent(rawId);
         initGreatWallBox();
    } catch (err) {
         return;
         decodedId = rawId;
     }
     }


    var target = document.getElementById(decodedId);
     if (mw.loader && mw.loader.using) {
 
         mw.loader.using(['mediawiki.api']).then(function() {
     if (!target && window.CSS && CSS.escape) {
            initGreatWallBox();
         target = document.querySelector('#' + CSS.escape(decodedId));
        });
     }
     }
}


     if (!target) return;
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');


     e.preventDefault();
     if (!box || box.getAttribute('data-great-wall-ready') === '1') return;
    e.stopPropagation();


     var scrollTarget = target.closest('h2, h3') || target;
     if (!mw.Api) {
        initGreatWallBoxWhenReady();
        return;
    }


     scrollTarget.scrollIntoView({
     box.setAttribute('data-great-wall-ready', '1');
        behavior: 'auto',
        block: 'start'
    });


     history.replaceState(null, '', '#' + rawId);
     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;


    $(document).on('click', 'a', function(e) {
         if (!ownButton || !ownEntry) return;
        // 휠 클릭, 새 탭 열기, 보조키 이동은 브라우저 기본 동작을 유지한다.
        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');
         greatWallState.selectedOwnEntry = true;
         if (!href) return;
        greatWallState.statusText = '';
         renderGreatWallBox();


        // 목차 링크는 별도 핸들러에서 처리
         if (input) {
         if ($(this).closest('#side-toc-box, #toc, .toc').length) return;
            input.focus();
            input.setSelectionRange(input.value.length, input.value.length);
        }
    });


        // 단순 해시 링크는 SPA 가로채기 제외
    document.addEventListener('click', function(e) {
        if (href.startsWith('#')) return;
        var target = e.target;
        var keepSelection;


         var link = document.createElement('a');
         if (!greatWallState.selectedOwnEntry || !target || !target.closest) return;
        link.href = href;


         var samePath = decodeURIComponent(link.pathname) === decodeURIComponent(window.location.pathname);
         keepSelection = target.closest('[data-great-wall-own-entry="1"], .great-wall-editor, .great-wall-compose-sector');
        var sameSearch = (link.search || '') === (window.location.search || '');


         if (link.hash && samePath && sameSearch) return;
         if (keepSelection) return;


         var currentBase = window.location.href.split('#')[0];
         greatWallState.selectedOwnEntry = false;
         var targetBase = link.href.split('#')[0];
        greatWallState.statusText = '';
         if (input) input.value = '';
        renderGreatWallBox();
    });


         if (link.hash && currentBase === targetBase) return;
    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 (!isInternal(href)) return;
    if (deleteButton) {
        if (shouldSkip(href)) return;
         deleteButton.addEventListener('click', function(e) {
            e.preventDefault();
            deleteGreatWallEntry();
        });
    }


        e.preventDefault();
    if (input) {
         playStaticSound();
         input.addEventListener('keydown', function(e) {
        /*
             if (e.key === 'Enter') {
        SPA must remain a consumer phase.  If the target page HTML was prepared by
                e.preventDefault();
        the first-load boot pack, do not show the legacy page-loading veil.  The
                saveGreatWallEntry();
        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() {
        input.addEventListener('input', function() {
        loadPage(window.location.href);
            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();
    });
}


/* ========== CLBI Custom Document Scrollbar ========== */
function buildGreatWallBox() {
function isGeneralDocumentView() {
    return '' +
    var body = document.body;
        '<div id="great-wall-sidebar" class="clbi-right-box great-wall-sidebar">' +
    if (!body) return false;
            '<div class="clbi-right-title great-wall-title">' +
 
                '<span id="clbi-title-great-wall">The Great Wall</span>' +
    return body.classList.contains('action-view') &&
            '</div>' +
        !body.classList.contains('clbi-main-page') &&
            '<div class="clbi-right-content great-wall-content">' +
        !body.classList.contains('clbi-system-doc-page') &&
                '<div id="great-wall-list" class="great-wall-list"><div class="great-wall-empty">SYNCING WALL</div></div>' +
        !body.classList.contains('backend-system-page') &&
            '</div>' +
        !body.classList.contains('user-profile-page') &&
            '<div class="great-wall-compose-sector" aria-label="The Great Wall editor">' +
         !body.classList.contains('user-profile-settings-page');
                '<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 getClbiDocumentScrollTargets() {
function removeMainPortalGuestbookPreview() {
     if (!isGeneralDocumentView()) return [];
     var portal = document.querySelector('.main-portal');
    var guestbook = portal ? portal.querySelector('.guestbook-device') : null;
    var sideScreen;
    var grid;


     return Array.prototype.slice.call(document.querySelectorAll(
     if (!portal || !guestbook) return;
        '.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) {
    sideScreen = guestbook.closest ? guestbook.closest('.side-screen') : null;
     var main = scrollEl ? scrollEl.closest('.liberty-content-main') : null;
     grid = sideScreen && sideScreen.closest ? sideScreen.closest('.console-grid') : null;
    var children;
    var i;
    var child;


     if (!main) return null;
     if (guestbook.parentNode) {
 
         guestbook.parentNode.removeChild(guestbook);
    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;
     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 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');
function initSidebars() {
        bar.className = 'clbi-custom-scrollbar';
    var header = $('.liberty-content-header');
        bar.setAttribute('aria-hidden', 'true');
    var content = $('.liberty-content');
        bar.innerHTML =
 
            '<div class="clbi-custom-scroll-arrow clbi-custom-scroll-arrow-up" data-scroll-arrow="up"></div>' +
    if (header.length && content.length) {
            '<div class="clbi-custom-scroll-track"><div class="clbi-custom-scroll-thumb"></div></div>' +
         header.prependTo(content);
            '<div class="clbi-custom-scroll-arrow clbi-custom-scroll-arrow-down" data-scroll-arrow="down"></div>';
         well.appendChild(bar);
     }
     }


     bar.__clbiScrollTarget = scrollEl;
     if ($('#clbi-right-sidebar').length === 0) {
    up = bar.querySelector('.clbi-custom-scroll-arrow-up');
        var username = mw.config.get('wgUserName');
    track = bar.querySelector('.clbi-custom-scroll-track');
        var isLoggedIn = username !== null;
    thumb = bar.querySelector('.clbi-custom-scroll-thumb');
        var avatarSrc = isLoggedIn
    down = bar.querySelector('.clbi-custom-scroll-arrow-down');
            ? '/index.php?title=특수:Redirect/file/Pfp-' + username + '.png'
            : '/index.php?title=특수:Redirect/file/Pfp-default.png';


    if (up && !up.__clbiBound) {
         var userBox;
         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) {
        if (isLoggedIn) {
        down.__clbiBound = true;
            userBox =
        down.addEventListener('mousedown', function (e) {
                '<div class="clbi-right-box profile-card-box">' +
            e.preventDefault();
                    '<div id="clbi-user-avatar-wrap" class="profile-identity-panel">' +
            e.stopPropagation();
                        '<div class="profile-avatar-stage">' +
             if (bar.__clbiScrollTarget) bar.__clbiScrollTarget.scrollTop += 48;
                            '<img id="clbi-user-avatar" src="' + avatarSrc + '" onerror="this.onerror=null;this.src=\'/index.php?title=특수:Redirect/file/Pfp-default.png\';">' +
            updateClbiCustomScrollbar(bar);
                        '</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 = '';


    if (track && !track.__clbiBound) {
        try {
        track.__clbiBound = true;
            greatWallBox = buildGreatWallBox();
         track.addEventListener('mousedown', function (e) {
         } catch (err) {
             var rect;
            console.error('The Great Wall build failed:', err);
             var thumbRect;
             greatWallBox = '';
             var target;
        }
             var direction;
 
        try {
             siteInformationBox = buildSiteInformationBox();
        } catch (err) {
             console.error('Site information build failed:', err);
             siteInformationBox = '';
        }


            if (e.target === thumb) return;
            e.preventDefault();
            e.stopPropagation();


            target = bar.__clbiScrollTarget;
        var sidebar = userBox + greatWallBox + siteInformationBox;
            if (!target) return;


            rect = track.getBoundingClientRect();
        $('.content-wrapper').append('<div id="clbi-right-sidebar">' + sidebar + '</div>');
            thumbRect = thumb.getBoundingClientRect();
        initGreatWallBoxWhenReady();
            direction = e.clientY < thumbRect.top ? -1 : 1;
         removeMainPortalGuestbookPreview();
            target.scrollTop += direction * Math.max(60, Math.floor(target.clientHeight * 0.82));
            updateClbiCustomScrollbar(bar);
         });
     }
     }


     if (thumb && !thumb.__clbiBound) {
     initGreatWallBoxWhenReady();
        thumb.__clbiBound = true;
    removeMainPortalGuestbookPreview();
        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();
    if ($('#clbi-left-sidebar').length === 0) {
            e.stopPropagation();
var leftBillboardBox = '';


            startY = e.clientY;
        try {
             startScroll = target.scrollTop;
             leftBillboardBox = buildRightBillboardBox();
            maxScroll = Math.max(1, target.scrollHeight - target.clientHeight);
        } catch (err) {
             trackHeight = track ? track.clientHeight : 0;
             console.error('Left billboard build failed:', err);
             thumbHeight = thumb.offsetHeight || 0;
             leftBillboardBox = '';
            maxThumbTop = Math.max(1, trackHeight - thumbHeight);
        }


             bar.classList.add('is-dragging');
var leftSidebar =
 
    '<div id="clbi-left-sidebar">' +
             function onMove(moveEvent) {
        '<div class="clbi-left-box clbi-left-lang-box">' +
                 var dy = moveEvent.clientY - startY;
             '<div class="clbi-left-title">' +
                target.scrollTop = startScroll + (dy / maxThumbTop) * maxScroll;
                '<span id="clbi-title-left-language">언어</span>' +
                 updateClbiCustomScrollbar(bar);
            '</div>' +
                 moveEvent.preventDefault();
             '<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">' +


            function onUp() {
                '<div class="news-feed-title" id="clbi-left-news-changelog-title">CHANGELOG</div>' +
                 bar.classList.remove('is-dragging');
                 '<div class="news-left-changelog-feed">' +
                document.removeEventListener('mousemove', onMove);
                    '<a href="/index.php/체인지로그" class="news-post-item">' +
                 document.removeEventListener('mouseup', onUp);
                        '<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>' +


            document.addEventListener('mousemove', onMove);
                '<div class="news-divider"></div>' +
            document.addEventListener('mouseup', onUp);
        });
    }


    if (!scrollEl.__clbiCustomScrollbarBound) {
                '<div class="news-feed-title" id="clbi-left-news-recent-title">RECENT CHANGES</div>' +
        scrollEl.__clbiCustomScrollbarBound = true;
                '<div class="news-left-recent-feed" id="clbi-left-recent-list">불러오는 중...</div>' +
        scrollEl.addEventListener('scroll', function () {
            if (scrollEl.__clbiCustomScrollbar) {
                updateClbiCustomScrollbar(scrollEl.__clbiCustomScrollbar);
            }
        }, { passive: true });
    }


    scrollEl.__clbiCustomScrollbar = bar;
                '<a class="news-fill-image-slot" id="clbi-left-news-fill-image" href="/index.php/특수:최근바뀜" aria-label="최근 바뀜으로 이동">' +
    updateClbiCustomScrollbar(bar);
                    '<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>' +


     return bar;
            '</div>' +
}
        '</div>' +
        leftBillboardBox +
     '</div>';


function updateClbiCustomScrollbar(bar) {
        $('.content-wrapper').prepend(leftSidebar);
    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;
        renderSidebarLanguageBox();
        loadRecentChangesList('#clbi-left-recent-list', 10);
        scheduleAdaptiveLeftRecentItems();
        scheduleLeftBillboardAdaptive();
        scheduleClbiContentBottomGap();
        updateLeftSidebarNationsImage();
    }


     maxScroll = scrollEl.scrollHeight - scrollEl.clientHeight;
     try {
     if (maxScroll <= 1) {
        initRightBillboardCarousel();
         bar.classList.add('is-hidden');
     } catch (err) {
        return;
         console.error('Right billboard carousel failed:', err);
     }
     }


     bar.classList.remove('is-hidden');
     if (typeof window.normalizeClbiShellDomOrder === 'function') window.normalizeClbiShellDomOrder();
    applyMainPageStyle();
    initClbiCustomDocumentScrollbars();
    initCategoryNavIfAvailable(document);


     trackHeight = Math.max(1, track.clientHeight || 1);
     if (window.ProgressSystemWebUi && typeof window.ProgressSystemWebUi.boot === 'function') {
    thumbHeight = Math.max(12, Math.floor((scrollEl.clientHeight / Math.max(scrollEl.scrollHeight, 1)) * trackHeight));
        window.ProgressSystemWebUi.boot('initSidebars');
    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';
     $('#side-toc-box').remove();
    thumb.style.transform = 'translateY(' + top + 'px)';
}


function initClbiCustomDocumentScrollbars() {
    mw.loader.using(['mediawiki.api']).then(function() {
    var existing = Array.prototype.slice.call(document.querySelectorAll('.clbi-custom-scrollbar'));
        setTimeout(function() {
    var targets = getClbiDocumentScrollTargets();
            initNotifications();
    var liveBars = [];
            initProfile();
            moveTocToLeftSidebar();
        }, 300);


    if (!targets.length) {
        setTimeout(moveTocToLeftSidebar, 800);
         existing.forEach(function (bar) { bar.remove(); });
         setTimeout(moveTocToLeftSidebar, 1500);
        return;
    });
    }
}


    targets.forEach(function (scrollEl) {
$(function() {
        var well = getClbiOuterWellForScroll(scrollEl);
    loadLangScript(function() {
         var bar;
         setTimeout(function() {
 
            initSidebars();
        if (!well) return;
         }, 100);
        bar = buildClbiCustomScrollbar(well, scrollEl);
         liveBars.push(bar);
     });
     });
});


    existing.forEach(function (bar) {
$(document).on('click.profileQuickPlaceholder', '#profile-quick-inventory, #profile-quick-achievements', function(e) {
        if (liveBars.indexOf(bar) === -1) bar.remove();
    e.preventDefault();
    });
    e.stopPropagation();
});


    window.requestAnimationFrame(function () {
function extractJsonArrayAfterMwConfigKey(text, key) {
        liveBars.forEach(updateClbiCustomScrollbar);
    var needle = '"' + key + '"';
     });
    var keyIndex = String(text || '').indexOf(needle);
     var start;
    var i;
    var depth = 0;
    var inString = false;
    var escaped = false;


     setTimeout(function () {
     if (keyIndex === -1) return null;
        liveBars.forEach(updateClbiCustomScrollbar);
    }, 120);
}


if (!window.__clbiCustomScrollbarResizeBound) {
     start = String(text || '').indexOf('[', keyIndex + needle.length);
     window.__clbiCustomScrollbarResizeBound = true;
     if (start === -1) return null;
    window.addEventListener('resize', function () {
        setTimeout(initClbiCustomDocumentScrollbars, 60);
     });
}


    for (i = start; i < text.length; i += 1) {
        var ch = text.charAt(i);


// 시간 계산 함수
        if (inString) {
function timeAgo(timestamp) {
            if (escaped) {
    var now = new Date();
                escaped = false;
    var date = new Date(timestamp);
            } else if (ch === '\\') {
    var diff = Math.floor((now - date) / 1000);
                escaped = true;
            } else if (ch === '"') {
                inString = false;
            }
            continue;
        }


    if (diff < 60) return diff + '초 전';
        if (ch === '"') {
    if (diff < 3600) return Math.floor(diff / 60) + '분 전';
            inString = true;
    if (diff < 86400) return Math.floor(diff / 3600) + '시간 전';
             continue;
    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');
         if (ch === '[') depth += 1;
    });
        if (ch === ']') {
}
            depth -= 1;
 
             if (depth === 0) {
function bindInnerResizeUpdates($target) {
                 try {
    // 이미지 늦게 로드될 때 높이 갱신
                    return JSON.parse(text.slice(start, i + 1));
    $target.find('img').off('.foldimg').on('load.foldimg', function () {
                } catch (err) {
        if ($target.hasClass('folding-open')) {
                    return null;
             if ($target.data('fold-state') !== 'open') {
                }
                 $target.css('max-height', $target[0].scrollHeight + 'px');
             }
             }
            refreshOpenAncestors($target);
         }
         }
     });
     }
 
    return null;
}
}


function openFold($target, $btn) {
function extractJsonStringAfterMwConfigKey(text, key) {
     var t = getFoldTexts();
     var needle = '"' + key + '"';
    var keyIndex = String(text || '').indexOf(needle);
    var colon;
    var start;
    var i;
    var escaped = false;


     $target.data('fold-state', 'opening');
     if (keyIndex === -1) return null;
    $target.addClass('folding-open');


     // 열린 뒤 자연 확장 가능하게 만들기 위해 먼저 px로 열기
     colon = text.indexOf(':', keyIndex + needle.length);
    $target.css('max-height', '0px');
     if (colon === -1) return null;
     $target[0].offsetHeight;
    $target.css('max-height', $target[0].scrollHeight + 'px');


     $btn.text(t.collapse);
     start = text.indexOf('"', colon + 1);
    if (start === -1) return null;


     bindInnerResizeUpdates($target);
     for (i = start + 1; i < text.length; i += 1) {
        var ch = text.charAt(i);
 
        if (escaped) {
            escaped = false;
            continue;
        }


    // 바깥 펼접 즉시 갱신
        if (ch === '\\') {
    refreshOpenAncestors($target);
            escaped = true;
            continue;
        }


    // 전환 끝나면 none으로 풀어서 중첩 펼접/동적 내용 증가를 자연스럽게 허용
        if (ch === '"') {
    $target.off('transitionend.foldopen').on('transitionend.foldopen', function (e) {
            try {
        if (e.target !== this) return;
                return JSON.parse(text.slice(start, i + 1));
         if (!$target.hasClass('folding-open')) return;
            } catch (err) {
                return text.slice(start + 1, i);
            }
         }
    }


        $target.css('max-height', 'none');
    return null;
        $target.data('fold-state', 'open');
}


        refreshOpenAncestors($target);
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) {
    requestAnimationFrame(function () {
         text = scripts[i].textContent || '';
         if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
            $target.css('max-height', $target[0].scrollHeight + 'px');
            refreshOpenAncestors($target);
        }
    });


    setTimeout(function () {
         if (categories === null) {
         if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
             value = extractJsonArrayAfterMwConfigKey(text, 'wgCategories');
             $target.css('max-height', $target[0].scrollHeight + 'px');
             if (Array.isArray(value)) categories = value;
             refreshOpenAncestors($target);
         }
         }
    }, 80);


    setTimeout(function () {
         if (hiddenCategories === null) {
         if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
             value = extractJsonArrayAfterMwConfigKey(text, 'wgHiddenCategories');
             $target.css('max-height', $target[0].scrollHeight + 'px');
             if (Array.isArray(value)) hiddenCategories = value;
             refreshOpenAncestors($target);
         }
         }
    }, 220);
}


function closeFold($target, $btn) {
        if (relevantPageName === null) {
    var t = getFoldTexts();
            value = extractJsonStringAfterMwConfigKey(text, 'wgRelevantPageName');
            if (value !== null) relevantPageName = value;
        }


    // none 상태에서 닫으면 transition이 안 되므로 실제 높이로 고정
        if (pageName === null) {
    if ($target.css('max-height') === 'none' || $target.data('fold-state') === 'open') {
            value = extractJsonStringAfterMwConfigKey(text, 'wgPageName');
        $target.css('max-height', $target[0].scrollHeight + 'px');
            if (value !== null) pageName = value;
    } else {
        }
        $target.css('max-height', $target[0].scrollHeight + 'px');
     }
     }


     $target.data('fold-state', 'closing');
     mw.config.set('wgCategories', Array.isArray(categories) ? categories : []);
    $target[0].offsetHeight;
     mw.config.set('wgHiddenCategories', Array.isArray(hiddenCategories) ? hiddenCategories : []);
     $target.css('max-height', '0px');
    $target.removeClass('folding-open');


     $btn.text(t.expand);
     if (relevantPageName !== null) {
        mw.config.set('wgRelevantPageName', relevantPageName);
    } else if (pageName !== null) {
        mw.config.set('wgRelevantPageName', pageName);
    }


     refreshOpenAncestors($target);
     CLBI_CATLINKS_FETCH_TOKEN += 1;
}


    setTimeout(function () {
// SPA 네비게이션
        refreshOpenAncestors($target);
function shouldSkip(url) {
        $target.data('fold-state', 'closed');
    return url.match(/action=edit|action=submit|action=history|action=delete|action=protect|action=purge|특수:로그인|특수:로그아웃|Special:UserLogin|Special:UserLogout|특수:사용자정보|특수:비밀번호바꾸기|uselang=/);
    }, 250);
}
}


$(function () {
$(function() {
     $(document)
     if (window._spaInitialized) return;
        .off('click.clbiToggle')
    window._spaInitialized = true;
        .on('click.clbiToggle', '.toggleBtn', function () {
            var $btn = $(this);
            var targetId = $btn.data('target');
            var $target = $('#' + targetId);
            if (!$target.length) return;


            var scrollY = window.scrollY;
    function isInternal(url) {
        var a = document.createElement('a');
        a.href = url;
        return a.hostname === window.location.hostname;
    }


            if ($target.hasClass('folding-open')) {
    function getCachedSpaPageHtml(url) {
                closeFold($target, $btn);
        if (!window.EntryStore || typeof window.EntryStore.getTextSync !== 'function') return '';
            } else {
        return window.EntryStore.getTextSync(url) || window.EntryStore.getTextSync(String(url || '').replace(/^https?:\/\/[^/]+/i, '')) || '';
                openFold($target, $btn);
    }
            }


             window.scrollTo(0, scrollY);
    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) {
function initProfile() {
        /*
    $('.profile-card').remove();
        Initial boot prepares entry artifacts; SPA is only allowed to consume them.
    $('.user-profile-portal').removeClass('user-profile-portal');
        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);
        }
    }


     var token = ++PROFILE_RENDER_TOKEN;
     function loadPage(url) {
    var ns = mw.config.get('wgNamespaceNumber');
        invalidateProfileRender();
    var title = mw.config.get('wgTitle');
    var specialPage = mw.config.get('wgCanonicalSpecialPageName');
    var isProfileSettings = specialPage === '사용자정보';


    $('body').toggleClass('user-profile-page', ns === 2);
        return fetchSpaPageHtml(url)
    $('body').toggleClass('user-profile-settings-page', isProfileSettings);
            .then(function(html) {
                var parser = new DOMParser();
                var doc = parser.parseFromString(html, 'text/html');


    if (ns === 2) {
                var scripts = doc.querySelectorAll('script');
        var profileUser = title.split('/')[0];
                for (var i = 0; i < scripts.length; i++) {
        renderProfile(profileUser, token);
                    var src = scripts[i].textContent;
    }


    if (isProfileSettings) {
                    if (src.indexOf('wgNamespaceNumber') !== -1) {
        initUserProfilePage();
                        var match = src.match(/"wgNamespaceNumber":(-?\d+)/);
    }
                        if (match) mw.config.set('wgNamespaceNumber', parseInt(match[1], 10));
}


function renderProfile(username, token) {
                        var matchTitle = src.match(/"wgTitle":"([^"]+)"/);
    var api = new mw.Api();
                        if (matchTitle) mw.config.set('wgTitle', matchTitle[1]);
    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];
                        var matchPage = src.match(/"wgPageName":"([^"]+)"/);
        if (currentTitle !== username) return;
                        if (matchPage) mw.config.set('wgPageName', matchPage[1]);


        var user = data.query.users[0];
                        var matchArticle = src.match(/"wgArticleId":(\d+)/);
        var contentEl = document.getElementById('mw-content-text');
                        if (matchArticle) {
        if (!contentEl) return;
                            mw.config.set('wgArticleId', parseInt(matchArticle[1], 10));
                        } else {
                            mw.config.set('wgArticleId', 0);
                        }


        var pageContent = contentEl.querySelector('.mw-parser-output') || contentEl;
                        var matchIsMainPage = src.match(/"wgIsMainPage":(true|false)/);
        injectProfileCard(username, user, pageContent);
                        if (matchIsMainPage) {
    });
                            mw.config.set('wgIsMainPage', matchIsMainPage[1] === 'true');
}
                        } else {
                            mw.config.set('wgIsMainPage', false);
                        }


function injectProfileCard(username, userData, container) {
                        var matchSpecial = src.match(/"wgCanonicalSpecialPageName":"([^"]+)"/);
    var isOwnPage = mw.config.get('wgUserName') === username;
                        if (matchSpecial) {
    var editCount = (userData && userData.editcount) ? userData.editcount : 0;
                            mw.config.set('wgCanonicalSpecialPageName', matchSpecial[1]);
                        } else {
                            mw.config.set('wgCanonicalSpecialPageName', false);
                        }
                        break;
                    }
                }


    function escapeHtml(value) {
                syncCatlinksConfigFromSpaDocument(doc);
        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 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');


    var safeUsername = escapeHtml(username);
                if (newContent) {
    var avatarSrc = '/index.php?title=특수:Redirect/file/Pfp-' + encodeURIComponent(username) + '.png&width=220';
                    prepareDetachedEntryContent(newContent);
    var fallbackSrc = '/index.php?title=특수:Redirect/file/Pfp-default.png&width=220';
                    prepareSpaCatlinksBeforeInsert(newContent);
    var editBtn = isOwnPage
                    $('#side-toc-box').remove();
        ? '<a href="/index.php/특수:사용자정보" class="profile-edit-btn"><span class="profile-edit-label">프로필 수정</span><span class="profile-edit-arrow">›</span></a>'
                    $('.profile-card').remove();
        : '';
                    $('.user-profile-portal').removeClass('user-profile-portal');
 
                    $('.liberty-content-main').html(newContent.innerHTML);
    var progressHtml = isOwnPage
                    $('.profile-card').remove();
        ? '<div class="profile-page-progress is-syncing" data-profile-progress>' +
                    try {
            '<div class="profile-section-title">LEVEL RECORD</div>' +
                        if (window.Decorations && typeof window.Decorations.renderPrepared === 'function') window.Decorations.renderPrepared();
            '<div class="profile-page-progress-body">' +
                        else if (window.CLBI_DECORATIONS && typeof window.CLBI_DECORATIONS.renderPrepared === 'function') window.CLBI_DECORATIONS.renderPrepared();
                 '<div class="profile-page-progress-row">' +
                    } catch (err) {}
                     '<span class="profile-page-level">SYNC</span>' +
                    $('body').removeClass('page-loading');
                     '<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>' +
                if (newTitle) {
                 '<div class="profile-page-progress-sub">SYNCING</div>' +
                    $('.mw-page-title-main').html(newTitle.innerHTML);
                 '<div class="profile-page-progress-meta">TODAY — · DISCOVERED —</div>' +
                }
            '</div>' +
 
        '</div>'
                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');
                }


    var card = document.createElement('div');
                $('#side-toc-box').remove();
    card.className = 'profile-card profile-page-console';
                 setTimeout(moveTocToLeftSidebar, 100);
    card.innerHTML =
                 setTimeout(moveTocToLeftSidebar, 500);
        '<div class="profile-card-titlebar">' +
                 setTimeout(moveTocToLeftSidebar, 1200);
            '<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();
                mw.loader.using(['mediawiki.api']).then(function() {
    container.insertBefore(card, container.firstChild);
                    initProfile();
    loadProfileFields(username, card);
                    moveTocToLeftSidebar();
    loadProfileContributionPages(username, card);
                });
    updateProfilePageEnvironment(card, null);
            })
 
            .catch(function (err) {
    if (isOwnPage) {
                console.error('SPA page load failed:', err);
        loadProfileProgressForUserPage(card);
                $('body').removeClass('page-loading');
            });
     }
     }
}


function getProfileLanguageLabel() {
// 목차 링크는 전용 처리
     var lang = getCurrentLang();
$(document).on('click', '#side-toc-box a, #toc a, .toc a', function(e) {
     return SIDEBAR_LANGUAGE_LABELS[lang] || (lang ? lang.toUpperCase() : '');
     var href = $(this).attr('href');
}
     if (!href || href.charAt(0) !== '#') return;


function updateProfilePageEnvironment(card, summary) {
    var rawId = href.slice(1);
     if (!card) return;
     if (!rawId) return;


     var timezone = summary && summary.timezone ? summary.timezone : 'UTC';
     var decodedId = rawId;
    var timeEl = card.querySelector('[data-profile-time]');
    var langEl = card.querySelector('[data-profile-language]');


     if (timeEl) {
     try {
         try {
         decodedId = decodeURIComponent(rawId);
            timeEl.textContent = timezone + ' ' + new Intl.DateTimeFormat('ko-KR', {
    } catch (err) {
                hour: '2-digit',
        decodedId = rawId;
                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) {
    var target = document.getElementById(decodedId);
         langEl.textContent = getProfileLanguageLabel();
 
     if (!target && window.CSS && CSS.escape) {
         target = document.querySelector('#' + CSS.escape(decodedId));
     }
     }
}


function loadProfileContributionPages(username, card) {
     if (!target) return;
     if (!username || !card) return;
    if (!mw.loader || typeof mw.loader.using !== 'function') return;


     var valueEl = card.querySelector('[data-contrib-pages-value]');
     e.preventDefault();
     if (valueEl) valueEl.textContent = 'SYNC';
     e.stopPropagation();


     mw.loader.using(['mediawiki.api']).then(function () {
     var scrollTarget = target.closest('h2, h3') || target;
        var api = new mw.Api();
        var pages = Object.create(null);
        var cont = {};
        var guard = 0;


        function requestNext() {
    scrollTarget.scrollIntoView({
            guard++;
        behavior: 'auto',
        block: 'start'
    });


            var params = Object.assign({
    history.replaceState(null, '', '#' + rawId);
                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 : [];
    $(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;


                rows.forEach(function (row) {
        if (window.BottomGuideNav && typeof window.BottomGuideNav.toggle === 'function') {
                    if (row && row.title) pages[row.title] = true;
            e.preventDefault();
                });
            e.stopImmediatePropagation();
            window.BottomGuideNav.toggle();
        }
    });


                if (data && data.continue && data.continue.uccontinue && guard < 40) {
    $(document).on('click', 'a', function(e) {
                    cont = data.continue;
        // 휠 클릭, 새 탭 열기, 보조키 이동은 브라우저 기본 동작을 유지한다.
                    return requestNext();
        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 (valueEl) valueEl.textContent = Object.keys(pages).length;
        /* 길라잡이 화면 탭은 위 전용 처리 외에는 SPA 문서 이동 대상으로 삼지 않는다. */
            });
        if ($(this).is('.portal-guide-anchor[data-category-key="guide"]')) return;
        }


         requestNext().fail(function () {
         var href = $(this).attr('href');
            if (valueEl) valueEl.textContent = '';
         if (!href) return;
         });
    });
}


function loadProfileProgressForUserPage(card) {
        // 목차 링크는 별도 핸들러에서 처리
    if (!mw.config.get('wgUserName')) return;
        if ($(this).closest('#side-toc-box, #toc, .toc').length) return;
    if (!mw.loader || typeof mw.loader.using !== 'function') return;


    mw.loader.using(['mediawiki.api']).then(function () {
        // 단순 해시 링크는 SPA 가로채기 제외
         var api = new mw.Api();
         if (href.startsWith('#')) return;
        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 link = document.createElement('a');
    var panel = card.querySelector('[data-profile-progress]');
        link.href = href;
    if (!panel || !summary) return;


    var level = summary.level || 1;
        var samePath = decodeURIComponent(link.pathname) === decodeURIComponent(window.location.pathname);
    var totalXp = summary.totalXp || 0;
        var sameSearch = (link.search || '') === (window.location.search || '');
    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');
        if (link.hash && samePath && sameSearch) return;
    panel.classList.toggle('is-max-level', isMaxLevel);


    var levelEl = panel.querySelector('.profile-page-level');
        var currentBase = window.location.href.split('#')[0];
    var totalEl = panel.querySelector('.profile-page-total-xp');
        var targetBase = link.href.split('#')[0];
    var fillEl = panel.querySelector('.profile-page-xp-fill');
 
    var subEl = panel.querySelector('.profile-page-progress-sub');
        if (link.hash && currentBase === targetBase) return;
    var metaEl = panel.querySelector('.profile-page-progress-meta');
 
        if (!isInternal(href)) return;
        if (shouldSkip(href)) return;


    if (levelEl) levelEl.textContent = (isMaxLevel ? 'MAX ' : 'LVL ') + level;
        e.preventDefault();
    if (totalEl) totalEl.textContent = totalXp + ' XP';
        playStaticSound();
    if (fillEl) fillEl.style.width = percent + '%';
        /*
    if (subEl) subEl.textContent = isMaxLevel ? 'MAX LEVEL' : (xpIntoLevel + ' / ' + xpForNext + ' TO NEXT');
        SPA must remain a consumer phase.  If the target page HTML was prepared by
    if (metaEl) metaEl.textContent = 'TODAY ' + dailyXp + ' XP · DISCOVERED ' + discoveries;
        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);
    });


function loadProfileFields(username, card) {
     window.addEventListener('popstate', function() {
    var api = new mw.Api();
         loadPage(window.location.href);
     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');
/* ========== CLBI Custom Document Scrollbar ========== */
     popup.id = 'clbi-notification-popup';
function isGeneralDocumentView() {
     popup.style.cssText =
     var body = document.body;
        'display:none;position:fixed;z-index:99999;width:320px;max-height:420px;' +
     if (!body) return false;
        '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 =
     return body.classList.contains('action-view') &&
        '<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;">' +
        !body.classList.contains('clbi-main-page') &&
            '<span>알림</span>' +
         !body.classList.contains('clbi-system-doc-page') &&
            '<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>' +
         !body.classList.contains('backend-system-page') &&
         '</div>' +
        !body.classList.contains('user-profile-page') &&
        '<div id="clbi-notification-list" style="max-height:320px;overflow-y:auto;padding:8px 0;color:#E2E2E2;font-size:12px;">불러오는 중...</div>' +
         !body.classList.contains('user-profile-settings-page');
         '<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() {
function getClbiDocumentScrollTargets() {
     var btn = document.getElementById('profile-quick-notifications');
     if (!isGeneralDocumentView()) return [];
    var popup = document.getElementById('clbi-notification-popup');
    if (!btn || !popup) return;


     var rect = btn.getBoundingClientRect();
     return Array.prototype.slice.call(document.querySelectorAll(
    var top = rect.bottom + 6;
        '.liberty-content-main > #mw-content-text .mw-parser-output, ' +
     var left = rect.left + (rect.width / 2) - (popup.offsetWidth / 2);
        '.liberty-content-main > .mw-body-content .mw-parser-output'
     )).filter(function (el, index, list) {
        return el && list.indexOf(el) === index;
    });
}


    if (left < 8) left = 8;
function getClbiOuterWellForScroll(scrollEl) {
     if (left + popup.offsetWidth > window.innerWidth - 8) {
     var main = scrollEl ? scrollEl.closest('.liberty-content-main') : null;
        left = window.innerWidth - popup.offsetWidth - 8;
     var children;
     }
     var i;
     if (top + popup.offsetHeight > window.innerHeight - 8) {
     var child;
        top = Math.max(8, rect.top - popup.offsetHeight - 6);
     }


     popup.style.top = top + 'px';
     if (!main) return null;
    popup.style.left = left + 'px';
}


function parseNotificationItemsFromHtml(html) {
    children = Array.prototype.slice.call(main.children || []);
     var parser = new DOMParser();
     for (i = 0; i < children.length; i += 1) {
    var doc = parser.parseFromString(html, 'text/html');
        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;
}


     var selectors = [
function buildClbiCustomScrollbar(well, scrollEl) {
        '.mw-echo-ui-notificationItemWidget',
     var bar = well.querySelector(':scope > .clbi-custom-scrollbar');
        '.mw-echo-ui-notificationsInboxWidgetRow',
    var up;
        '.echo-ui-notificationItemWidget',
    var track;
        'li[data-notification-id]',
    var thumb;
        '.mw-echo-notifications-list li'
     var down;
     ];


     var items = [];
     if (!bar) {
    for (var i = 0; i < selectors.length; i++) {
        bar = document.createElement('div');
        items = Array.prototype.slice.call(doc.querySelectorAll(selectors[i]));
        bar.className = 'clbi-custom-scrollbar';
         if (items.length) break;
        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);
     }
     }


     return items.slice(0, 5).map(function(item) {
     bar.__clbiScrollTarget = scrollEl;
        var link = item.querySelector('a[href]');
    up = bar.querySelector('.clbi-custom-scroll-arrow-up');
        var href = link ? link.getAttribute('href') : '/index.php?title=Special:Notifications';
    track = bar.querySelector('.clbi-custom-scroll-track');
        var text = (item.textContent || '').replace(/\s+/g, ' ').trim();
    thumb = bar.querySelector('.clbi-custom-scroll-thumb');
    down = bar.querySelector('.clbi-custom-scroll-arrow-down');


         var notificationId =
    if (up && !up.__clbiBound) {
            item.getAttribute('data-notification-id') ||
         up.__clbiBound = true;
             item.getAttribute('data-id') ||
        up.addEventListener('mousedown', function (e) {
             item.getAttribute('data-notification') ||
             e.preventDefault();
            '';
             e.stopPropagation();
            if (bar.__clbiScrollTarget) bar.__clbiScrollTarget.scrollTop -= 48;
            updateClbiCustomScrollbar(bar);
        });
    }


        if (!notificationId) {
    if (down && !down.__clbiBound) {
            var anyWithId = item.querySelector('[data-notification-id], [data-id], [data-notification]');
        down.__clbiBound = true;
             if (anyWithId) {
        down.addEventListener('mousedown', function (e) {
                notificationId =
             e.preventDefault();
                    anyWithId.getAttribute('data-notification-id') ||
            e.stopPropagation();
                    anyWithId.getAttribute('data-id') ||
            if (bar.__clbiScrollTarget) bar.__clbiScrollTarget.scrollTop += 48;
                    anyWithId.getAttribute('data-notification') ||
            updateClbiCustomScrollbar(bar);
                    '';
        });
            }
    }
        }


        if (href && href.indexOf('http') !== 0) {
    if (track && !track.__clbiBound) {
            href = href.charAt(0) === '/'
        track.__clbiBound = true;
                ? href
        track.addEventListener('mousedown', function (e) {
                : '/index.php' + (href.charAt(0) === '?' ? href : '/' + href);
            var rect;
        }
            var thumbRect;
            var target;
            var direction;


        return {
            if (e.target === thumb) return;
             id: notificationId,
             e.preventDefault();
             href: href,
             e.stopPropagation();
            text: text || '알림'
        };
    });
}


function setNotificationIcon(hasItems) {
            target = bar.__clbiScrollTarget;
    var quickIcon = document.getElementById('profile-quick-notification-icon');
            if (!target) return;
    var svg = hasItems ? CLBI_SVG_BELL_DOT : CLBI_SVG_BELL;


    if (quickIcon) {
            rect = track.getBoundingClientRect();
        quickIcon.innerHTML = svg;
            thumbRect = thumb.getBoundingClientRect();
        quickIcon.classList.toggle('has-notifications', !!hasItems);
            direction = e.clientY < thumbRect.top ? -1 : 1;
            target.scrollTop += direction * Math.max(60, Math.floor(target.clientHeight * 0.82));
            updateClbiCustomScrollbar(bar);
        });
     }
     }
}


function renderNotificationPopup(items) {
    if (thumb && !thumb.__clbiBound) {
    var list = document.getElementById('clbi-notification-list');
        thumb.__clbiBound = true;
    var badge = document.getElementById('clbi-notification-badge');
        thumb.addEventListener('mousedown', function (e) {
    if (!list) return;
            var target = bar.__clbiScrollTarget;
            var startY;
            var startScroll;
            var maxScroll;
            var maxThumbTop;
            var trackHeight;
            var thumbHeight;


    if (!items || !items.length) {
            if (!target) return;
        list.innerHTML = '<div style="padding:14px 12px;color:#999;">표시할 알림이 없습니다.</div>';
 
        if (badge) badge.style.display = 'none';
            e.preventDefault();
        setNotificationIcon(false);
            e.stopPropagation();
        return;
    }


    var html = '';
            startY = e.clientY;
    for (var i = 0; i < items.length; i++) {
            startScroll = target.scrollTop;
        html +=
             maxScroll = Math.max(1, target.scrollHeight - target.clientHeight);
             '<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;">' +
            trackHeight = track ? track.clientHeight : 0;
                items[i].text +
             thumbHeight = thumb.offsetHeight || 0;
             '</a>';
            maxThumbTop = Math.max(1, trackHeight - thumbHeight);
    }
    list.innerHTML = html;


    if (badge) {
            bar.classList.add('is-dragging');
        badge.textContent = items.length;
        badge.style.display = 'block';
    }
    setNotificationIcon(true);
}


function loadNotificationsIntoPopup() {
            function onMove(moveEvent) {
    var list = document.getElementById('clbi-notification-list');
                var dy = moveEvent.clientY - startY;
    if (list) {
                target.scrollTop = startScroll + (dy / maxThumbTop) * maxScroll;
        list.innerHTML = '<div style="padding:14px 12px;color:#999;">불러오는 중...</div>';
                updateClbiCustomScrollbar(bar);
    }
                moveEvent.preventDefault();
            }


    fetch('/index.php?title=Special:Notifications', { credentials: 'same-origin' })
            function onUp() {
        .then(function(res) {
                bar.classList.remove('is-dragging');
            return res.text();
                document.removeEventListener('mousemove', onMove);
        })
                 document.removeEventListener('mouseup', onUp);
        .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>';
             }
             }
            document.addEventListener('mousemove', onMove);
            document.addEventListener('mouseup', onUp);
         });
         });
}
    }


function markAllNotificationsRead() {
    if (!scrollEl.__clbiCustomScrollbarBound) {
    return new mw.Api().postWithToken('csrf', {
        scrollEl.__clbiCustomScrollbarBound = true;
         action: 'echomarkread',
        scrollEl.addEventListener('scroll', function () {
        list: 'all'
            if (scrollEl.__clbiCustomScrollbar) {
    });
                updateClbiCustomScrollbar(scrollEl.__clbiCustomScrollbar);
}
            }
         }, { passive: true });
    }


function markNotificationReadById(notificationId) {
    scrollEl.__clbiCustomScrollbar = bar;
     if (!notificationId) {
     updateClbiCustomScrollbar(bar);
        return $.Deferred().resolve().promise();
    }


     return new mw.Api().postWithToken('csrf', {
     return bar;
        action: 'echomarkread',
        list: notificationId
    });
}
}


function initNotifications() {
function updateClbiCustomScrollbar(bar) {
     var quickBtn = document.getElementById('profile-quick-notifications');
     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 (!quickBtn) return;
     if (!bar || !scrollEl || !track || !thumb) return;


     ensureNotificationPopup();
     maxScroll = scrollEl.scrollHeight - scrollEl.clientHeight;
    loadNotificationsIntoPopup();
    if (maxScroll <= 1) {
        bar.classList.add('is-hidden');
        return;
    }


     $(document)
     bar.classList.remove('is-hidden');
        .off('click.clbiNotificationToggle')
        .on('click.clbiNotificationToggle', '#profile-quick-notifications', function(e) {
            e.preventDefault();
            e.stopPropagation();


            var popup = document.getElementById('clbi-notification-popup');
    trackHeight = Math.max(1, track.clientHeight || 1);
            if (!popup) return;
    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;


            if (popup.style.display === 'none' || popup.style.display === '') {
    thumb.style.height = thumbHeight + 'px';
                popup.style.display = 'block';
    thumb.style.transform = 'translateY(' + top + 'px)';
                positionNotificationPopup();
}
                loadNotificationsIntoPopup();
            } else {
                popup.style.display = 'none';
            }
        });


    $(document)
function initClbiCustomDocumentScrollbars() {
        .off('click.clbiNotificationOutside')
    var existing = Array.prototype.slice.call(document.querySelectorAll('.clbi-custom-scrollbar'));
        .on('click.clbiNotificationOutside', function(e) {
    var targets = getClbiDocumentScrollTargets();
            var popup = document.getElementById('clbi-notification-popup');
    var liveBars = [];
            var quickToggle = document.getElementById('profile-quick-notifications');
            if (!popup) return;


            if (!popup.contains(e.target) && (!quickToggle || !quickToggle.contains(e.target))) {
    if (!targets.length) {
                popup.style.display = 'none';
        existing.forEach(function (bar) { bar.remove(); });
            }
         return;
         });
    }


     $(document)
     targets.forEach(function (scrollEl) {
        .off('click.clbiNotificationReadAll')
        var well = getClbiOuterWellForScroll(scrollEl);
        .on('click.clbiNotificationReadAll', '#clbi-notification-readall', function(e) {
        var bar;
            e.preventDefault();
            e.stopPropagation();


            var button = this;
        if (!well) return;
            button.disabled = true;
        bar = buildClbiCustomScrollbar(well, scrollEl);
            button.textContent = '처리 중...';
        liveBars.push(bar);
    });


            markAllNotificationsRead()
    existing.forEach(function (bar) {
                .then(function() {
        if (liveBars.indexOf(bar) === -1) bar.remove();
                    loadNotificationsIntoPopup();
    });
                })
                .always(function() {
                    button.disabled = false;
                    button.textContent = '전체 읽음';
                });
        });


     $(document)
     window.requestAnimationFrame(function () {
        .off('click.clbiNotificationItem')
        liveBars.forEach(updateClbiCustomScrollbar);
        .on('click.clbiNotificationItem', '.clbi-notification-item', function(e) {
    });
            e.preventDefault();
            e.stopPropagation();


            var href = this.getAttribute('href');
    setTimeout(function () {
            var notificationId = this.getAttribute('data-notification-id') || '';
        liveBars.forEach(updateClbiCustomScrollbar);
    }, 120);
}


            markNotificationReadById(notificationId).always(function() {
if (!window.__clbiCustomScrollbarResizeBound) {
                loadNotificationsIntoPopup();
    window.__clbiCustomScrollbarResizeBound = true;
                if (href) {
    window.addEventListener('resize', function () {
                    window.location.href = href;
        setTimeout(initClbiCustomDocumentScrollbars, 60);
                }
    });
            });
}
        });
 
 
// 시간 계산 함수
function timeAgo(timestamp) {
    var now = new Date();
    var date = new Date(timestamp);
    var diff = Math.floor((now - date) / 1000);


     $(window)
     if (diff < 60) return diff + '초 전';
        .off('resize.clbiNotification')
    if (diff < 3600) return Math.floor(diff / 60) + '분 전';
        .on('resize.clbiNotification', function() {
    if (diff < 86400) return Math.floor(diff / 3600) + '시간 전';
            var popup = document.getElementById('clbi-notification-popup');
    return Math.floor(diff / 86400) + '일 전';
            if (popup && popup.style.display === 'block') {
                positionNotificationPopup();
            }
        });
}
}
// ========== 알림 시스템 끝 ==========


function initUserProfilePage() {
// 펼접 토글
     $('body').addClass('user-profile-settings-page');
// 펼접 토글
function getFoldTexts() {
     var lang = getCurrentLang();
    return (window.LANG && window.LANG[lang])
        ? window.LANG[lang]
        : (window.LANG ? window.LANG.ko : { expand: '펼치기', collapse: '접기' });
}


     var saveBtn = document.getElementById('pref-save');
function refreshOpenAncestors($start) {
    if (!saveBtn) return;
     $start.parents('[id^="collapsible"]').each(function () {
        var $parent = $(this);
        if (!$parent.hasClass('folding-open')) return;


    function getPrefRow(id) {
         // 이미 fully open 상태면 굳이 다시 잠그지 않음
         var el = document.getElementById(id);
         if ($parent.data('fold-state') === 'open') {
         if (!el) return null;
             return;
        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) {
         $parent.css('max-height', this.scrollHeight + 'px');
         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');
function bindInnerResizeUpdates($target) {
         body.className = 'clbi-pref-section-body';
    // 이미지 늦게 로드될 때 높이 갱신
    $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();


        section.appendChild(title);
    $target.data('fold-state', 'opening');
        section.appendChild(body);
    $target.addClass('folding-open');


        return {
    // 열린 뒤 자연 확장 가능하게 만들기 위해 먼저 px로 열기
            section: section,
    $target.css('max-height', '0px');
            body: body
    $target[0].offsetHeight;
        };
     $target.css('max-height', $target[0].scrollHeight + 'px');
     }


     function moveRowToSection(id, targetBody, className) {
     $btn.text(t.collapse);
        var row = getPrefRow(id);
        if (!row || !targetBody) return false;


        row.classList.add('clbi-pref-row-key-' + className);
    bindInnerResizeUpdates($target);
        targetBody.appendChild(row);
        return true;
    }


     function rebuildProfileSettingsLayout() {
     // 바깥 펼접 즉시 갱신
        var root = document.querySelector('.clbi-prefs-profile');
    refreshOpenAncestors($target);
        if (!root || root.dataset.profileSettingsReworked === '1') return;


        root.dataset.profileSettingsReworked = '1';
    // 전환 끝나면 none으로 풀어서 중첩 펼접/동적 내용 증가를 자연스럽게 허용
         root.classList.add('profile-settings-console');
    $target.off('transitionend.foldopen').on('transitionend.foldopen', function (e) {
        if (e.target !== this) return;
         if (!$target.hasClass('folding-open')) return;


         removePrefRow('pref-badges');
         $target.css('max-height', 'none');
        $target.data('fold-state', 'open');


         var originalRows = Array.prototype.slice.call(root.querySelectorAll('.clbi-pref-row'));
         refreshOpenAncestors($target);
        var actionNodes = [];
    });


         if (saveBtn.parentNode === root || saveBtn.closest('.clbi-prefs-profile') === root) {
    // 늦게 렌더되는 콘텐츠 대응
             actionNodes.push(saveBtn);
    requestAnimationFrame(function () {
         if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
             $target.css('max-height', $target[0].scrollHeight + 'px');
            refreshOpenAncestors($target);
         }
         }
    });


         var statusNode = document.getElementById('pref-status');
    setTimeout(function () {
        if (statusNode && statusNode.closest('.clbi-prefs-profile') === root) {
         if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
             actionNodes.push(statusNode);
             $target.css('max-height', $target[0].scrollHeight + 'px');
            refreshOpenAncestors($target);
         }
         }
    }, 80);


         var main = document.createElement('div');
    setTimeout(function () {
        main.className = 'clbi-pref-main-grid';
         if ($target.hasClass('folding-open') && $target.data('fold-state') !== 'open') {
            $target.css('max-height', $target[0].scrollHeight + 'px');
            refreshOpenAncestors($target);
        }
    }, 220);
}


        var media = createPrefSection('clbi-pref-section-media', 'PROFILE IMAGE');
function closeFold($target, $btn) {
        var identity = createPrefSection('clbi-pref-section-identity', 'IDENTITY RECORD');
    var t = getFoldTexts();
        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);
    // none 상태에서 닫으면 transition이 안 되므로 실제 높이로 고정
        main.appendChild(identity.section);
    if ($target.css('max-height') === 'none' || $target.data('fold-state') === 'open') {
         main.appendChild(bio.section);
         $target.css('max-height', $target[0].scrollHeight + 'px');
         main.appendChild(account.section);
    } else {
        main.appendChild(misc.section);
         $target.css('max-height', $target[0].scrollHeight + 'px');
    }


        root.innerHTML = '';
    $target.data('fold-state', 'closing');
        root.appendChild(main);
    $target[0].offsetHeight;
    $target.css('max-height', '0px');
    $target.removeClass('folding-open');


        moveRowToSection('pref-pfp-preview', media.body, 'pfp');
    $btn.text(t.expand);
        moveRowToSection('pref-pfp-btn', media.body, 'pfp');
        moveRowToSection('pref-pfp-input', media.body, 'pfp');


        moveRowToSection('pref-name', identity.body, 'name');
    refreshOpenAncestors($target);
        moveRowToSection('pref-role', identity.body, 'role');
        moveRowToSection('pref-discord', identity.body, 'discord');


         moveRowToSection('pref-bio', bio.body, 'bio');
    setTimeout(function () {
         refreshOpenAncestors($target);
        $target.data('fold-state', 'closed');
    }, 250);
}


         moveRowToSection('pref-new-email', account.body, 'email');
$(function () {
         moveRowToSection('pref-email-password', account.body, 'email');
    $(document)
        moveRowToSection('pref-email-save', account.body, 'email');
         .off('click.clbiToggle')
         .on('click.clbiToggle', '.toggleBtn', function () {
            var $btn = $(this);
            var targetId = $btn.data('target');
            var $target = $('#' + targetId);
            if (!$target.length) return;


        originalRows.forEach(function (row) {
            var scrollY = window.scrollY;
             if (!row.parentNode && !row.className.match(/clbi-pref-row-key-/)) {
 
                 misc.body.appendChild(row);
             if ($target.hasClass('folding-open')) {
                closeFold($target, $btn);
            } else {
                 openFold($target, $btn);
             }
             }
            window.scrollTo(0, scrollY);
         });
         });
});


        if (!misc.body.children.length) {
// ========== 프로필 시스템 ==========
            misc.section.parentNode.removeChild(misc.section);
function initProfile() {
        }
    $('.profile-card').remove();
    $('.user-profile-portal').removeClass('user-profile-portal');


        var actions = document.createElement('div');
    var token = ++PROFILE_RENDER_TOKEN;
        actions.className = 'clbi-pref-actions';
    var ns = mw.config.get('wgNamespaceNumber');
    var title = mw.config.get('wgTitle');
    var specialPage = mw.config.get('wgCanonicalSpecialPageName');
    var isProfileSettings = specialPage === '사용자정보';


        if (saveBtn) actions.appendChild(saveBtn);
    $('body').toggleClass('user-profile-page', ns === 2);
        if (statusNode) actions.appendChild(statusNode);
    $('body').toggleClass('user-profile-settings-page', isProfileSettings);


         root.appendChild(actions);
    if (ns === 2) {
         var profileUser = title.split('/')[0];
        renderProfile(profileUser, token);
     }
     }


     rebuildProfileSettingsLayout();
     if (isProfileSettings) {
        initUserProfilePage();
    }
}


function renderProfile(username, token) {
     var api = new mw.Api();
     var api = new mw.Api();
     var selectedFile = null;
     api.get({
    var cropper = null;
        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;


    if (!document.getElementById('clbi-gallery-modal')) {
        var user = data.query.users[0];
         var gModal = document.createElement('div');
         var contentEl = document.getElementById('mw-content-text');
        gModal.id = 'clbi-gallery-modal';
         if (!contentEl) return;
         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 =
         var pageContent = contentEl.querySelector('.mw-parser-output') || contentEl;
            '<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;">' +
        injectProfileCard(username, user, pageContent);
                '<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);
function injectProfileCard(username, userData, container) {
     }
    var isOwnPage = mw.config.get('wgUserName') === username;
     var editCount = (userData && userData.editcount) ? userData.editcount : 0;


     if (!document.getElementById('clbi-crop-modal')) {
     function escapeHtml(value) {
         var cModal = document.createElement('div');
         return String(value == null ? '' : value)
        cModal.id = 'clbi-crop-modal';
            .replace(/&/g, '&amp;')
        cModal.style.cssText =
            .replace(/</g, '&lt;')
            '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;';
            .replace(/>/g, '&gt;')
 
            .replace(/"/g, '&quot;')
        cModal.innerHTML =
            .replace(/'/g, '&#039;');
            '<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');
     container.classList.add('user-profile-portal');
    var cModal = document.getElementById('clbi-crop-modal');
    var cropImage = document.getElementById('clbi-crop-image');
    var pfpInput = document.getElementById('pref-pfp-input');


     function openGallery() {
     var safeUsername = escapeHtml(username);
         gModal.style.display = 'flex';
    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 username = mw.config.get('wgUserName');
    var progressHtml = isOwnPage
        api.get({
        ? '<div class="profile-page-progress is-syncing" data-profile-progress>' +
             action: 'query',
             '<div class="profile-section-title">LEVEL RECORD</div>' +
             titles: '파일:Pfp-' + username + '.png',
             '<div class="profile-page-progress-body">' +
            prop: 'imageinfo',
                '<div class="profile-page-progress-row">' +
            iiprop: 'url|timestamp',
                    '<span class="profile-page-level">SYNC</span>' +
            iilimit: 6
                    '<span class="profile-page-total-xp">— XP</span>' +
        }).then(function(data) {
                '</div>' +
            var pages = data.query.pages;
                '<div class="profile-page-xp-bar" aria-hidden="true"><div class="profile-page-xp-fill"></div></div>' +
             var page = pages[Object.keys(pages)[0]];
                '<div class="profile-page-progress-sub">SYNCING</div>' +
            if (!page.imageinfo || page.imageinfo.length === 0) return;
                '<div class="profile-page-progress-meta">TODAY — · DISCOVERED —</div>' +
             '</div>' +
        '</div>'
        : '';


            var historyEl = document.getElementById('clbi-gallery-history');
    var card = document.createElement('div');
            var sectionEl = document.getElementById('clbi-gallery-history-section');
    card.className = 'profile-card profile-page-console';
            historyEl.innerHTML = '';
    card.innerHTML =
 
        '<div class="profile-card-titlebar">' +
             page.imageinfo.forEach(function(info, idx) {
            '<span>USER PROFILE</span>' +
                var wrap = document.createElement('div');
             '<span>OFFICIAL ARCHIVE</span>' +
                 wrap.style.cssText = 'position:relative;cursor:pointer;';
        '</div>' +
 
        '<div class="profile-card-body">' +
                 var img = document.createElement('img');
            '<div class="profile-identity-row">' +
                 img.src = info.url;
                 '<div class="profile-avatar-bay">' +
                img.style.cssText =
                    '<img src="' + avatarSrc + '" onerror="this.onerror=null;this.src=\'' + fallbackSrc + '\';" alt="' + safeUsername + '">' +
                     'width:72px;height:72px;object-fit:cover;border-radius:8px;border:2px solid #444;flex-shrink:0;';
                 '</div>' +
 
                 '<div class="profile-info-panel">' +
                 if (idx === 0) {
                    '<div class="profile-nameplate">' +
                     img.style.borderColor = '#854369';
                        '<h2 class="profile-username">' + safeUsername + '</h2>' +
                    var badge = document.createElement('div');
                        editBtn +
                     badge.textContent = '현재';
                     '</div>' +
                     badge.style.cssText =
                    '<div class="profile-name" data-field="name"></div>' +
                         'position:absolute;bottom:4px;left:50%;transform:translateX(-50%);background:#854369;color:#fff;font-size:9px;padding:1px 6px;border-radius:10px;';
                    '<div class="profile-role" data-field="role"></div>' +
                    wrap.appendChild(badge);
                    '<div class="profile-discord" data-field="discord"></div>' +
                }
                 '</div>' +
 
            '</div>' +
                img.addEventListener('mouseenter', function() {
            '<div class="profile-lower-grid">' +
                    if (idx !== 0) img.style.borderColor = '#854369';
                '<div class="profile-bio-panel">' +
                });
                    '<div class="profile-section-title">BIOGRAPHY</div>' +
 
                     '<div class="profile-bio" data-field="bio"></div>' +
                img.addEventListener('mouseleave', function() {
                '</div>' +
                    if (idx !== 0) img.style.borderColor = '#444';
                '<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>';


                img.addEventListener('click', function() {
    $('.profile-card').remove();
                    fetch(info.url)
    container.insertBefore(card, container.firstChild);
                        .then(function(r) {
    loadProfileFields(username, card);
                            return r.blob();
    loadProfileContributionPages(username, card);
                        })
    updateProfilePageEnvironment(card, null);
                        .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);
    if (isOwnPage) {
                historyEl.appendChild(wrap);
        loadProfileProgressForUserPage(card);
            });
 
            sectionEl.style.display = 'block';
        });
     }
     }
}


    function openCrop(src) {
function getProfileLanguageLabel() {
        cropImage.src = src;
    var lang = getCurrentLang();
        cModal.style.display = 'flex';
    return SIDEBAR_LANGUAGE_LABELS[lang] || (lang ? lang.toUpperCase() : '');
}


        if (cropper) {
function updateProfilePageEnvironment(card, summary) {
             cropper.destroy();
    if (!card) return;
             cropper = null;
 
    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());
         }
         }
    }


        setTimeout(function() {
    if (langEl) {
            cropper = new Cropper(cropImage, {
        langEl.textContent = getProfileLanguageLabel();
                aspectRatio: 1,
                viewMode: 1,
                dragMode: 'move',
                autoCropArea: 0.8,
                cropBoxResizable: true,
                cropBoxMovable: true
            });
        }, 150);
     }
     }
}


    document.getElementById('pref-pfp-btn').addEventListener('click', function() {
function loadProfileContributionPages(username, card) {
        openGallery();
    if (!username || !card) return;
     });
     if (!mw.loader || typeof mw.loader.using !== 'function') return;


     document.getElementById('clbi-gallery-upload-btn').addEventListener('click', function() {
     var valueEl = card.querySelector('[data-contrib-pages-value]');
        pfpInput.click();
     if (valueEl) valueEl.textContent = 'SYNC';
     });


     document.getElementById('clbi-gallery-close').addEventListener('click', function() {
     mw.loader.using(['mediawiki.api']).then(function () {
         gModal.style.display = 'none';
         var api = new mw.Api();
    });
        var pages = Object.create(null);
        var cont = {};
        var guard = 0;


    pfpInput.addEventListener('change', function() {
        function requestNext() {
        var file = this.files[0];
            guard++;
        if (!file) return;


        gModal.style.display = 'none';
            var params = Object.assign({
 
                action: 'query',
        var reader = new FileReader();
                list: 'usercontribs',
        reader.onload = function(e) {
                ucuser: username,
            openCrop(e.target.result);
                ucnamespace: 0,
        };
                ucprop: 'title',
        reader.readAsDataURL(file);
                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 : [];


    document.getElementById('clbi-crop-cancel').addEventListener('click', function() {
                rows.forEach(function (row) {
        cModal.style.display = 'none';
                    if (row && row.title) pages[row.title] = true;
        if (cropper) {
                });
            cropper.destroy();
            cropper = null;
        }
        pfpInput.value = '';
    });


    document.getElementById('clbi-crop-confirm').addEventListener('click', function() {
                if (data && data.continue && data.continue.uccontinue && guard < 40) {
        if (!cropper) return;
                    cont = data.continue;
                    return requestNext();
                }


        var canvas = cropper.getCroppedCanvas({ width: 256, height: 256 });
                if (valueEl) valueEl.textContent = Object.keys(pages).length;
         if (!canvas) return;
            });
         }


         canvas.toBlob(function(blob) {
         requestNext().fail(function () {
             selectedFile = new File([blob], 'profile.png', { type: 'image/png' });
             if (valueEl) valueEl.textContent = '';
            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');
function loadProfileProgressForUserPage(card) {
     if (emailSaveBtn) {
     if (!mw.config.get('wgUserName')) return;
        emailSaveBtn.addEventListener('click', function() {
    if (!mw.loader || typeof mw.loader.using !== 'function') return;
            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) {
    mw.loader.using(['mediawiki.api']).then(function () {
                statusEl.textContent = '이메일과 비밀번호를 입력해주세요.';
        var api = new mw.Api();
                return;
        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);
        });
    });
}


            statusEl.textContent = '변경 중...';
function updateUserPageProgress(card, summary) {
    var panel = card.querySelector('[data-profile-progress]');
    if (!panel || !summary) return;


            api.postWithToken('csrf', {
    var level = summary.level || 1;
                action: 'changeemail',
    var totalXp = summary.totalXp || 0;
                email: newEmail,
    var xpIntoLevel = summary.xpIntoLevel || 0;
                password: password
    var xpForNext = summary.xpForNextLevel || 1;
            }).then(function() {
    var percent = Math.max(0, Math.min(100, summary.progressPercent || 0));
                statusEl.textContent = '✓ 이메일 변경됨';
    var isMaxLevel = !!summary.isMaxLevel;
                document.getElementById('pref-new-email').value = '';
    var dailyXp = summary.dailyXp || 0;
                document.getElementById('pref-email-password').value = '';
    var discoveries = summary.discoveryCount || 0;


                setTimeout(function() {
    panel.classList.remove('is-syncing');
                    statusEl.textContent = '';
    panel.classList.toggle('is-max-level', isMaxLevel);
                }, 3000);
            }).fail(function(code, data) {
                var msg = data && data.error && data.error.info ? data.error.info : '변경 실패';
                statusEl.textContent = msg;
            });
        });
    }


     saveBtn.addEventListener('click', function() {
     var levelEl = panel.querySelector('.profile-page-level');
        var statusEl = document.getElementById('pref-status');
    var totalEl = panel.querySelector('.profile-page-total-xp');
        statusEl.textContent = '저장 중...';
    var fillEl = panel.querySelector('.profile-page-xp-fill');
    var subEl = panel.querySelector('.profile-page-progress-sub');
    var metaEl = panel.querySelector('.profile-page-progress-meta');


        var promises = [];
    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;
}


        if (selectedFile) {
function loadProfileFields(username, card) {
            var username = mw.config.get('wgUserName');
    var api = new mw.Api();
             promises.push(
    api.get({
                api.postWithToken('csrf', {
        action: 'userprofile',
                    action: 'upload',
        user: username
                    filename: 'Pfp-' + username + '.png',
    }).then(function(data) {
                    ignorewarnings: true,
        var profile = data.userprofile;
                    file: selectedFile,
        updateProfileFields(card, {
                    format: 'json'
             name: profile.name || '',
                }, {
            discord: profile.discord || '',
                    contentType: 'multipart/form-data'
            role: profile.role || '',
                })
            bio: profile.bio || ''
            );
        });
        }
    }).fail(function() {
        updateProfileFields(card, {
            name: '',
            discord: '',
            role: '',
            bio: ''
        });
    });
}


        var fields = ['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 || '';
}
// ========== 프로필 시스템 끝 ==========


        for (var i = 0; i < fields.length; i++) {
// ========== 알림 시스템 ==========
            var el = document.getElementById('pref-' + fields[i]);
function ensureNotificationPopup() {
            if (!el) continue;
    if (document.getElementById('clbi-notification-popup')) return;


            promises.push(
    var popup = document.createElement('div');
                api.postWithToken('csrf', {
    popup.id = 'clbi-notification-popup';
                    action: 'options',
    popup.style.cssText =
                    optionname: 'profile-' + fields[i],
        'display:none;position:fixed;z-index:99999;width:320px;max-height:420px;' +
                    optionvalue: el.value
        '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;';
            );
        }


         $.when.apply($, promises)
    popup.innerHTML =
             .then(function() {
         '<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;">' +
                statusEl.textContent = '✓ 저장됨';
             '<span>알림</span>' +
                selectedFile = null;
            '<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>' +
                document.getElementById('pref-pfp-btn').textContent = '사진 선택';
        '</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>';


                setTimeout(function() {
    document.body.appendChild(popup);
                    statusEl.textContent = '';
                }, 2000);
            })
            .fail(function() {
                statusEl.textContent = '저장 실패';
            });
    });
}
}


/* =========================================
function positionNotificationPopup() {
  Banner / CRT Page Monitor thumbnail slices
    var btn = document.getElementById('profile-quick-notifications');
  - base 이미지는 틀에 들어간 파일 문법 그대로 사용
    var popup = document.getElementById('clbi-notification-popup');
  - slice 레이어에는 300px MediaWiki 썸네일만 삽입
    if (!btn || !popup) return;
  ========================================= */


(function ($, mw) {
    var rect = btn.getBoundingClientRect();
     var thumbCache = {};
    var top = rect.bottom + 6;
     var left = rect.left + (rect.width / 2) - (popup.offsetWidth / 2);


     function parseSliceWidth(value) {
     if (left < 8) left = 8;
        var parsed = parseInt(value, 10);
    if (left + popup.offsetWidth > window.innerWidth - 8) {
 
         left = window.innerWidth - popup.offsetWidth - 8;
        if (!isFinite(parsed) || parsed < 120) {
            return 300;
         }
 
        return parsed;
     }
     }
 
     if (top + popup.offsetHeight > window.innerHeight - 8) {
     function getImageSrc(img) {
         top = Math.max(8, rect.top - popup.offsetHeight - 6);
         return img ? (img.currentSrc || img.getAttribute('src') || img.src || '') : '';
     }
     }


     function getFileNameFromSrc(src) {
     popup.style.top = top + 'px';
        var a;
    popup.style.left = left + 'px';
        var parts;
}
        var fileName;


        if (!src) return '';
function parseNotificationItemsFromHtml(html) {
    var parser = new DOMParser();
    var doc = parser.parseFromString(html, 'text/html');


         a = document.createElement('a');
    var selectors = [
         a.href = src;
        '.mw-echo-ui-notificationItemWidget',
 
        '.mw-echo-ui-notificationsInboxWidgetRow',
         parts = (a.pathname || '').split('/').filter(function (part) {
        '.echo-ui-notificationItemWidget',
            return !!part;
        '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();


         if (!parts.length) return '';
         var notificationId =
            item.getAttribute('data-notification-id') ||
            item.getAttribute('data-id') ||
            item.getAttribute('data-notification') ||
            '';


         fileName = parts.pop();
         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) {
        * MediaWiki thumb URL 예시:
            href = href.charAt(0) === '/'
        * /images/thumb/a/ab/File.png/1000px-File.png
                ? href
        * /images/thumb/a/ab/File.svg/1000px-File.svg.png
                : '/index.php' + (href.charAt(0) === '?' ? href : '/' + href);
        *
        * 이 경우 실제 파일명은 마지막 조각이 아니라 그 앞 조각이다.
        */
        if (/^\d+px-/.test(fileName) && parts.length) {
            fileName = parts.pop();
         }
         }


         fileName = fileName.replace(/^\d+px-/, '');
         return {
            id: notificationId,
            href: href,
            text: text || '알림'
        };
    });
}


        try {
function setNotificationIcon(hasItems) {
            fileName = decodeURIComponent(fileName);
    var quickIcon = document.getElementById('profile-quick-notification-icon');
        } catch (e) {}
    var svg = hasItems ? CLBI_SVG_BELL_DOT : CLBI_SVG_BELL;


         return fileName;
    if (quickIcon) {
         quickIcon.innerHTML = svg;
        quickIcon.classList.toggle('has-notifications', !!hasItems);
     }
     }
}


    function resolveThumbUrl(img, width, callback) {
function renderNotificationPopup(items) {
        var src = getImageSrc(img);
    var list = document.getElementById('clbi-notification-list');
         var fileName = getFileNameFromSrc(src);
    var badge = document.getElementById('clbi-notification-badge');
         var cacheKey;
    if (!list) return;
         var entry;
 
    if (!items || !items.length) {
         list.innerHTML = '<div style="padding:14px 12px;color:#999;">표시할 알림이 없습니다.</div>';
        if (badge) badge.style.display = 'none';
         setNotificationIcon(false);
         return;
    }


         if (!src) 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 (!fileName || !mw || !mw.loader) {
    if (badge) {
            callback(src);
        badge.textContent = items.length;
            return;
        badge.style.display = 'block';
        }
    }
    setNotificationIcon(true);
}


        cacheKey = fileName + '|' + width;
function loadNotificationsIntoPopup() {
         entry = thumbCache[cacheKey];
    var list = document.getElementById('clbi-notification-list');
    if (list) {
         list.innerHTML = '<div style="padding:14px 12px;color:#999;">불러오는 중...</div>';
    }


         if (entry) {
    fetch('/index.php?title=Special:Notifications', { credentials: 'same-origin' })
             if (entry.resolved) {
         .then(function(res) {
                callback(entry.url || src);
             return res.text();
             } else {
        })
                 entry.callbacks.push(callback);
        .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>';
             }
             }
            return;
        });
        }
}


        entry = {
function markAllNotificationsRead() {
            resolved: false,
    return new mw.Api().postWithToken('csrf', {
            url: '',
        action: 'echomarkread',
            callbacks: [callback]
        list: 'all'
        };
    });
}


         thumbCache[cacheKey] = entry;
function markNotificationReadById(notificationId) {
    if (!notificationId) {
         return $.Deferred().resolve().promise();
    }


        function finish(url) {
    return new mw.Api().postWithToken('csrf', {
            var callbacks = entry.callbacks.slice();
        action: 'echomarkread',
            var i;
        list: notificationId
    });
}


            entry.resolved = true;
function initNotifications() {
            entry.url = url || src;
    var quickBtn = document.getElementById('profile-quick-notifications');
            entry.callbacks = [];


            for (i = 0; i < callbacks.length; i++) {
    if (!quickBtn) return;
                callbacks[i](entry.url);
            }
        }


        mw.loader.using('mediawiki.api').done(function () {
    ensureNotificationPopup();
            var api = new mw.Api();
    loadNotificationsIntoPopup();


            api.get({
    $(document)
                action: 'query',
        .off('click.clbiNotificationToggle')
                titles: 'File:' + fileName,
        .on('click.clbiNotificationToggle', '#profile-quick-notifications', function(e) {
                prop: 'imageinfo',
             e.preventDefault();
                iiprop: 'url',
            e.stopPropagation();
                iiurlwidth: width,
                formatversion: 2
             }).done(function (data) {
                var page;
                var info;


                if (
            var popup = document.getElementById('clbi-notification-popup');
                    data &&
            if (!popup) return;
                    data.query &&
                    data.query.pages &&
                    data.query.pages.length
                ) {
                    page = data.query.pages[0];


                    if (
            if (popup.style.display === 'none' || popup.style.display === '') {
                        page &&
                popup.style.display = 'block';
                        page.imageinfo &&
                positionNotificationPopup();
                        page.imageinfo.length
                loadNotificationsIntoPopup();
                    ) {
            } else {
                        info = page.imageinfo[0];
                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;


                finish((info && (info.thumburl || info.url)) || src);
            if (!popup.contains(e.target) && (!quickToggle || !quickToggle.contains(e.target))) {
            }).fail(function () {
                 popup.style.display = 'none';
                 finish(src);
             }
             });
        }).fail(function () {
            finish(src);
         });
         });
    }


     function applySliceImages(frame, thumbUrl) {
     $(document)
         var slices;
         .off('click.clbiNotificationReadAll')
         var i;
         .on('click.clbiNotificationReadAll', '#clbi-notification-readall', function(e) {
        var img;
            e.preventDefault();
            e.stopPropagation();


        if (!frame || !thumbUrl) return;
            var button = this;
            button.disabled = true;
            button.textContent = '처리 중...';


        slices = frame.querySelectorAll('.crt-page-monitor-slice');
            markAllNotificationsRead()
                .then(function() {
                    loadNotificationsIntoPopup();
                })
                .always(function() {
                    button.disabled = false;
                    button.textContent = '전체 읽음';
                });
        });


         for (i = 0; i < slices.length; i++) {
    $(document)
             slices[i].innerHTML = '';
         .off('click.clbiNotificationItem')
        .on('click.clbiNotificationItem', '.clbi-notification-item', function(e) {
             e.preventDefault();
            e.stopPropagation();


             img = document.createElement('img');
             var href = this.getAttribute('href');
             img.className = 'crt-page-monitor-slice-img';
             var notificationId = this.getAttribute('data-notification-id') || '';
            img.src = thumbUrl;
            img.alt = '';
            img.decoding = 'async';
            img.loading = 'eager';
            img.setAttribute('aria-hidden', 'true');


             slices[i].appendChild(img);
             markNotificationReadById(notificationId).always(function() {
         }
                loadNotificationsIntoPopup();
                if (href) {
                    window.location.href = href;
                }
            });
         });


         frame.setAttribute('data-crt-slices-ready', '1');
    $(window)
    }
         .off('resize.clbiNotification')
        .on('resize.clbiNotification', function() {
            var popup = document.getElementById('clbi-notification-popup');
            if (popup && popup.style.display === 'block') {
                positionNotificationPopup();
            }
        });
}
// ========== 알림 시스템 끝 ==========


    function initBannerFrame(frame) {
function initUserProfilePage() {
        var baseImg;
    $('body').addClass('user-profile-settings-page');
        var width;


        if (!frame) return;
    var saveBtn = document.getElementById('pref-save');
        if (frame.getAttribute('data-crt-slices-ready') === '1') return;
    if (!saveBtn) return;


         baseImg = frame.querySelector('.crt-page-monitor-image-base img');
    function getPrefRow(id) {
         var el = document.getElementById(id);
        if (!el) return null;
        return el.closest('.clbi-pref-row') || el.parentNode;
    }


         if (!baseImg) return;
    function removePrefRow(id) {
        var row = getPrefRow(id);
         if (row && row.parentNode) {
            row.parentNode.removeChild(row);
        }
    }


         width = parseSliceWidth(frame.getAttribute('data-crt-slice-width'));
    function createPrefSection(className, titleText) {
         var section = document.createElement('div');
        section.className = 'clbi-pref-section ' + className;


         resolveThumbUrl(baseImg, width, function (thumbUrl) {
         var title = document.createElement('div');
            if (!frame || !frame.parentNode) return;
        title.className = 'clbi-pref-section-title';
            applySliceImages(frame, thumbUrl);
         title.textContent = titleText;
         });
    }


    function initBannerFrames(root) {
         var body = document.createElement('div');
         var scope = root && root.querySelectorAll ? root : document;
         body.className = 'clbi-pref-section-body';
         var frames = scope.querySelectorAll('.crt-page-monitor-frame');
        var i;


         for (i = 0; i < frames.length; i++) {
         section.appendChild(title);
            initBannerFrame(frames[i]);
        section.appendChild(body);
        }
    }


     $(function () {
        return {
         initBannerFrames(document);
            section: section,
    });
            body: body
        };
    }
 
     function moveRowToSection(id, targetBody, className) {
         var row = getPrefRow(id);
        if (!row || !targetBody) return false;


    if (mw && mw.hook) {
        row.classList.add('clbi-pref-row-key-' + className);
        mw.hook('wikipage.content').add(function ($content) {
        targetBody.appendChild(row);
            initBannerFrames($content && $content[0] ? $content[0] : document);
         return true;
         });
     }
     }
})(jQuery, window.mw);


/* =========================================
    function rebuildProfileSettingsLayout() {
  Doc Tab System — tab switching UI
        var root = document.querySelector('.clbi-prefs-profile');
  글리치 플리커 + RGB split + 방향 슬라이드
        if (!root || root.dataset.profileSettingsReworked === '1') return;
  ========================================= */


(function () {
        root.dataset.profileSettingsReworked = '1';
    'use strict';
        root.classList.add('profile-settings-console');


    function initDocTabs() {
         removePrefRow('pref-badges');
         var tabBars = document.querySelectorAll('.doc-tab-bar');
        if (!tabBars.length) return;


         tabBars.forEach(function (bar) {
         var originalRows = Array.prototype.slice.call(root.querySelectorAll('.clbi-pref-row'));
            if (bar.getAttribute('data-tabs-init')) return;
        var actionNodes = [];
            bar.setAttribute('data-tabs-init', '1');


            var tabs = Array.from(bar.querySelectorAll('.doc-tab'));
        if (saveBtn.parentNode === root || saveBtn.closest('.clbi-prefs-profile') === root) {
             if (!tabs.length) return;
             actionNodes.push(saveBtn);
        }


            var panel = bar.closest('.doc-panel');
        var statusNode = document.getElementById('pref-status');
            var display = panel ? panel.querySelector('.doc-display') : null;
        if (statusNode && statusNode.closest('.clbi-prefs-profile') === root) {
             if (!display) display = document.getElementById('doc-main-display');
             actionNodes.push(statusNode);
            if (!display) return;
        }


            tabs.forEach(function (tab, i) {
        var main = document.createElement('div');
                tab.addEventListener('click', function () {
        main.className = 'clbi-pref-main-grid';
                    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'); });
        var media = createPrefSection('clbi-pref-section-media', 'PROFILE IMAGE');
            if (initIdx !== -1) {
        var identity = createPrefSection('clbi-pref-section-identity', 'IDENTITY RECORD');
                var initRef = tabs[initIdx].dataset.ref;
        var bio = createPrefSection('clbi-pref-section-bio', 'BIOGRAPHY');
                var initEl = initRef ? document.getElementById(initRef) : null;
        var account = createPrefSection('clbi-pref-section-account', 'ACCOUNT CONTACT');
                display.innerHTML = initEl ? initEl.innerHTML : (tabs[initIdx].dataset.content || '');
        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);


    var isAnimating = false;
        moveRowToSection('pref-pfp-preview', media.body, 'pfp');
        moveRowToSection('pref-pfp-btn', media.body, 'pfp');
        moveRowToSection('pref-pfp-input', media.body, 'pfp');


    function switchTab(tabs, display, nextIdx, dir) {
        moveRowToSection('pref-name', identity.body, 'name');
         if (isAnimating) return;
         moveRowToSection('pref-role', identity.body, 'role');
         isAnimating = true;
         moveRowToSection('pref-discord', identity.body, 'discord');


         tabs.forEach(function (t) { t.classList.remove('active'); });
         moveRowToSection('pref-bio', bio.body, 'bio');
        tabs[nextIdx].classList.add('active');


         var ref = tabs[nextIdx].dataset.ref;
         moveRowToSection('pref-new-email', account.body, 'email');
        var nextContent;
         moveRowToSection('pref-email-password', account.body, 'email');
         if (ref) {
        moveRowToSection('pref-email-save', account.body, 'email');
            var refEl = document.getElementById(ref);
            nextContent = refEl ? refEl.innerHTML : '';
        } else {
            nextContent = tabs[nextIdx].dataset.content || '';
        }


         glitchOut(display, dir, function () {
         originalRows.forEach(function (row) {
             display.innerHTML = nextContent;
             if (!row.parentNode && !row.className.match(/clbi-pref-row-key-/)) {
            glitchIn(display, dir, function () {
                 misc.body.appendChild(row);
                 isAnimating = false;
             }
             });
         });
         });
    }


    function glitchOut(el, dir, cb) {
        if (!misc.body.children.length) {
        var duration = 160;
            misc.section.parentNode.removeChild(misc.section);
        var start = null;
         }
         var slideX = dir * 16;


         function step(ts) {
         var actions = document.createElement('div');
            if (!start) start = ts;
        actions.className = 'clbi-pref-actions';
            var p = Math.min((ts - start) / duration, 1);
            var ease = p * p;


            var tx = slideX * ease;
        if (saveBtn) actions.appendChild(saveBtn);
            var skew = dir * ease * 1.0;
        if (statusNode) actions.appendChild(statusNode);
            var opacity = 1 - ease;
            var rgb = ease * 5;


            el.style.transform = 'translateX(' + tx + 'px) skewX(' + skew + 'deg)';
        root.appendChild(actions);
            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) {
    rebuildProfileSettingsLayout();
                requestAnimationFrame(step);
            } else {
                el.style.opacity = '0';
                cb();
            }
        }
        requestAnimationFrame(step);
    }


     function glitchIn(el, dir, cb) {
     var api = new mw.Api();
        var duration = 200;
    var selectedFile = null;
        var start = null;
    var cropper = null;
        var startX = -dir * 16;


        el.style.transform = 'translateX(' + startX + 'px) skewX(' + (-dir * 1.0) + 'deg)';
    if (!document.getElementById('clbi-gallery-modal')) {
         el.style.opacity = '0';
        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;';


         function step(ts) {
         gModal.innerHTML =
             if (!start) start = ts;
             '<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;">' +
            var p = Math.min((ts - start) / duration, 1);
                '<div style="display:flex;justify-content:space-between;align-items:center;">' +
            var ease = 1 - Math.pow(1 - p, 3);
                    '<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>';


            var tx = startX * (1 - ease);
        document.body.appendChild(gModal);
            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)';
    if (!document.getElementById('clbi-crop-modal')) {
            el.style.opacity = opacity;
        var cModal = document.createElement('div');
            el.style.filter =
        cModal.id = 'clbi-crop-modal';
                'drop-shadow(' + (-rgb) + 'px 0 0 rgba(80,160,255,0.65)) ' +
        cModal.style.cssText =
                 'drop-shadow(' + rgb + 'px 0 0 rgba(255,55,90,0.55)) ' +
            '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;';
                 'brightness(' + brightness + ')';
 
        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>';


            if (p < 1) {
        document.body.appendChild(cModal);
                requestAnimationFrame(step);
            } else {
                el.style.transform = '';
                el.style.opacity = '';
                el.style.filter = '';
                cb();
            }
        }
        requestAnimationFrame(step);
     }
     }


if (document.readyState === 'loading') {
    var gModal = document.getElementById('clbi-gallery-modal');
     document.addEventListener('DOMContentLoaded', initDocTabs);
    var cModal = document.getElementById('clbi-crop-modal');
} else {
     var cropImage = document.getElementById('clbi-crop-image');
     initDocTabs();
     var pfpInput = document.getElementById('pref-pfp-input');
}


if (typeof mw !== 'undefined' && mw.hook) {
    function openGallery() {
    mw.hook('wikipage.content').add(function () {
        gModal.style.display = 'flex';
        initDocTabs();
    });
}


})();
        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');
  Doc Section Switch — 좌측 섹션 전환
            var sectionEl = document.getElementById('clbi-gallery-history-section');
  ========================================= */
            historyEl.innerHTML = '';


$(document).on('click', '.doc-nav-item[data-section]', function () {
            page.imageinfo.forEach(function(info, idx) {
    var name = $(this).attr('data-section');
                var wrap = document.createElement('div');
    var display = document.getElementById('doc-main-display');
                wrap.style.cssText = 'position:relative;cursor:pointer;';
    var titleEl = document.getElementById('doc-center-title');
    var tabBar = document.getElementById('doc-tab-bar-text');


    if (!display) return;
                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;';


    $('.doc-nav-item[data-section]').removeClass('active');
                if (idx === 0) {
    $('.doc-nav-item[data-section="' + name + '"]').addClass('active');
                    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 (name === 'text') {
                img.addEventListener('mouseenter', function() {
        if (titleEl) titleEl.textContent = '개요';
                    if (idx !== 0) img.style.borderColor = '#854369';
        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 : '';
    }
});


/* =========================================
                img.addEventListener('mouseleave', function() {
  CRT WebGL Renderer — cool-retro-term IBM DOS style
                    if (idx !== 0) img.style.borderColor = '#444';
  ========================================= */
                });
(function () {
    'use strict';


    function createNoiseTexture(gl) {
                img.addEventListener('click', function() {
        var size = 512;
                    fetch(info.url)
        var data = new Uint8Array(size * size * 4);
                        .then(function(r) {
        var s = 12345;
                            return r.blob();
        function rand() {
                        })
            s = (s * 1664525 + 1013904223) & 0xffffffff;
                        .then(function(blob) {
            return (s >>> 0) / 0xffffffff;
                            selectedFile = new File([blob], 'profile.png', { type: 'image/png' });
        }
                            document.getElementById('pref-pfp-preview').src = URL.createObjectURL(blob);
        for (var i = 0; i < data.length; i++) {
                            gModal.style.display = 'none';
            data[i] = (rand() * 255) | 0;
                            document.getElementById('pref-pfp-btn').textContent = '✓ 사진 선택됨';
        }
                        });
        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);
                wrap.appendChild(img);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
                historyEl.appendChild(wrap);
        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);
            sectionEl.style.display = 'block';
         return tex;
         });
     }
     }


     var VERT = [
     function openCrop(src) {
        'attribute vec2 a_pos;',
         cropImage.src = src;
        'varying vec2 v_uv;',
         cModal.style.display = 'flex';
        '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 = [
         if (cropper) {
         'precision mediump float;',
            cropper.destroy();
        'uniform sampler2D u_tex;',
            cropper = null;
        '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; }',
         setTimeout(function() {
        'float min2(vec2 v) { return min(v.x, v.y); }',
            cropper = new Cropper(cropImage, {
        'float rgb2grey(vec3 v) { return dot(v, vec3(0.21, 0.72, 0.04)); }',
                aspectRatio: 1,
                viewMode: 1,
                dragMode: 'move',
                autoCropArea: 0.8,
                cropBoxResizable: true,
                cropBoxMovable: true
            });
        }, 150);
    }


        'vec2 coverUV(vec2 uv) {',
    document.getElementById('pref-pfp-btn').addEventListener('click', function() {
        ' float imgAR = u_imgSize.x / u_imgSize.y;',
         openGallery();
        ' 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) {',
    document.getElementById('clbi-gallery-upload-btn').addEventListener('click', function() {
        ' float ar = u_res.x / u_res.y;',
         pfpInput.click();
        '  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) {',
    document.getElementById('clbi-gallery-close').addEventListener('click', function() {
         '  return texture2D(u_noise, vec2(fract(t/2048.0), fract(t/1048576.0)));',
         gModal.style.display = 'none';
        '}',
    });


        'vec4 sampleScreenNoise(vec2 uv) {',
    pfpInput.addEventListener('change', function() {
         '  return texture2D(u_noise, u_noiseScale * uv);',
         var file = this.files[0];
        '}',
        if (!file) return;


         'vec3 applyRgbShift(vec2 texUV, float shift) {',
         gModal.style.display = 'none';
        '  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) {',
         var reader = new FileReader();
        '  vec2 px = 2.0 / u_res;',
         reader.onload = function(e) {
        '  vec3 acc = vec3(0.0);',
            openCrop(e.target.result);
         '  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;',
         reader.readAsDataURL(file);
        '  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) {',
    document.getElementById('clbi-crop-cancel').addEventListener('click', function() {
         '  float line = mod(uv.y * u_res.y, 2.0);',
         cModal.style.display = 'none';
         '  vec3 hi = ((1.0 + 0.30) - 0.2 * col) * col;',
         if (cropper) {
        '  vec3 lo = ((1.0 - 0.30) + 0.1 * col) * col;',
            cropper.destroy();
         ' return line < 1.0 ? lo : hi;',
            cropper = null;
        '}',
         }
        pfpInput.value = '';
    });


'vec3 applyRasterization(vec2 uv, vec3 col) {',
    document.getElementById('clbi-crop-confirm').addEventListener('click', function() {
' float t = u_time;',
        if (!cropper) return;
'  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) {',
         var canvas = cropper.getCroppedCanvas({ width: 256, height: 256 });
'  float pos = fract(t * 0.2);',
        if (!canvas) return;
'  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) {',
         canvas.toBlob(function(blob) {
        ' float randval = strength - noise.r;',
            selectedFile = new File([blob], 'profile.png', { type: 'image/png' });
        ' float scale = step(0.0, randval) * randval * strength;',
            document.getElementById('pref-pfp-preview').src = URL.createObjectURL(blob);
        '  float freq = mix(4.0, 40.0, noise.g);',
            cModal.style.display = 'none';
        ' uv.x += sin((uv.y + u_time * 0.001) * freq) * scale;',
            cropper.destroy();
         ' return uv;',
            cropper = null;
        '}',
            document.getElementById('pref-pfp-btn').textContent = '✓ 사진 선택됨';
         }, 'image/png');
    });


        'void main() {',
    var emailSaveBtn = document.getElementById('pref-email-save');
        ' vec2 cc = vec2(0.5) - v_uv;',
    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;


        ' float curvature = 0.18;',
            if (!newEmail || !password) {
        '  vec2 uv = barrel(v_uv, cc, curvature);',
                statusEl.textContent = '이메일과 비밀번호를 입력해주세요.';
                return;
            }


        '  float inScreen = min2(step(vec2(0.0), uv) - step(vec2(1.0), uv));',
            statusEl.textContent = '변경 중...';
        ' 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);',
            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 = '';


        '  vec4 initNoise = sampleInitialNoise(u_time);',
                setTimeout(function() {
        ' vec4 screenNoise = sampleScreenNoise(uv);',
                    statusEl.textContent = '';
                }, 3000);
            }).fail(function(code, data) {
                var msg = data && data.error && data.error.info ? data.error.info : '변경 실패';
                statusEl.textContent = msg;
            });
        });
    }


         '  texUV = applyHSync(texUV, initNoise, 0.006);',
    saveBtn.addEventListener('click', function() {
         ' texUV = clamp(texUV, 0.0, 1.0);',
         var statusEl = document.getElementById('pref-status');
         statusEl.textContent = '저장 중...';


         '  texUV += (vec2(screenNoise.b, screenNoise.a) - 0.5) * 0.0006;',
         var promises = [];
        '  texUV = clamp(texUV, 0.0, 1.0);',


         '  vec3 col = applyRgbShift(texUV, 0.003);',
         if (selectedFile) {
        ' col += applyBloom(texUV, 0.22);',
            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'
                })
            );
        }


         '  vec2 bpx = 1.5 / u_res;',
         var fields = ['name', 'discord', 'role', 'bio'];
        '  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);',
         for (var i = 0; i < fields.length; i++) {
        '  col = applyRasterization(texUV, col);',
            var el = document.getElementById('pref-' + fields[i]);
            if (!el) continue;


        ' float glow = glowingLine(uv, u_time);',
            promises.push(
' col += glow * 0.08 * vec3(0.85, 0.95, 1.0);',
                api.postWithToken('csrf', {
                    action: 'options',
                    optionname: 'profile-' + fields[i],
                    optionvalue: el.value
                })
            );
        }


         '  float dist = length(cc);',
         $.when.apply($, promises)
        '  col += screenNoise.a * 0.07 * (1.0 - dist * 1.3);',
            .then(function() {
                statusEl.textContent = '✓ 저장됨';
                selectedFile = null;
                document.getElementById('pref-pfp-btn').textContent = '사진 선택';


        '  float grey = rgb2grey(col);',
                setTimeout(function() {
        '  vec3 phosphor = vec3(0.75, 0.88, 1.0);',
                    statusEl.textContent = '';
        '  col = mix(col, grey * phosphor, 0.35);',
                }, 2000);
            })
            .fail(function() {
                statusEl.textContent = '저장 실패';
            });
    });
}


        '  vec2 vig = v_uv * (1.0 - v_uv);',
/* =========================================
        '  col *= pow(vig.x * vig.y * 15.0, 0.25);',
  Banner / CRT Page Monitor thumbnail slices
  - base 이미지는 틀에 들어간 파일 문법 그대로 사용
  - slice 레이어에는 300px MediaWiki 썸네일만 삽입
  ========================================= */


        '  col *= 1.0 + (initNoise.g - 0.5) * 0.06;',
(function ($, mw) {
    var thumbCache = {};


         '  col += vec3(0.012) * (1.0 - dist) * (1.0 - dist);',
    function parseSliceWidth(value) {
         var parsed = parseInt(value, 10);


         '  col = pow(clamp(col, 0.0, 1.0), vec3(0.90));',
         if (!isFinite(parsed) || parsed < 120) {
            return 300;
        }


         '  gl_FragColor = vec4(col, 1.0);',
         return parsed;
        '}'
    }
    ].join('\n');


     function initCRTCanvas(screen, imgEl) {
     function getImageSrc(img) {
         var existing = screen.querySelector('.crt-webgl-canvas');
         return img ? (img.currentSrc || img.getAttribute('src') || img.src || '') : '';
        if (existing) existing.remove();
    }


        var canvas = document.createElement('canvas');
    function getFileNameFromSrc(src) {
         canvas.className = 'crt-webgl-canvas';
         var a;
         canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;z-index:19;pointer-events:none;display:block;';
         var parts;
         screen.appendChild(canvas);
         var fileName;


        var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
         if (!src) return '';
         if (!gl) return;


         function compile(type, src) {
         a = document.createElement('a');
            var s = gl.createShader(type);
        a.href = src;
            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();
         parts = (a.pathname || '').split('/').filter(function (part) {
        gl.attachShader(prog, compile(gl.VERTEX_SHADER, VERT));
            return !!part;
        gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, FRAG));
         });
        gl.linkProgram(prog);
         gl.useProgram(prog);


         var buf = gl.createBuffer();
         if (!parts.length) return '';
        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');
         fileName = parts.pop();
        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);
        * MediaWiki thumb URL 예시:
        gl.bindTexture(gl.TEXTURE_2D, imgTex);
        * /images/thumb/a/ab/File.png/1000px-File.png
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        * /images/thumb/a/ab/File.svg/1000px-File.svg.png
         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);
        */
         if (/^\d+px-/.test(fileName) && parts.length) {
            fileName = parts.pop();
         }


         gl.activeTexture(gl.TEXTURE1);
         fileName = fileName.replace(/^\d+px-/, '');
        createNoiseTexture(gl);


         var texReady = false;
         try {
        function uploadImg() {
             fileName = decodeURIComponent(fileName);
             if (!imgEl || !imgEl.complete || !imgEl.naturalWidth) return;
        } catch (e) {}
            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;
         return fileName;
        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 t0 = performance.now();


        function render() {
    function resolveThumbUrl(img, width, callback) {
            raf = requestAnimationFrame(render);
        var src = getImageSrc(img);
            if (!texReady) { uploadImg(); return; }
        var fileName = getFileNameFromSrc(src);
            resize();
        var cacheKey;
            var t = (performance.now() - t0) / 1000;
        var entry;
            gl.uniform1i(uTex, 0);
 
            gl.uniform1i(uNoise, 1);
        if (!src) return;
            gl.uniform2f(uRes, canvas.width, canvas.height);
 
            gl.uniform2f(uImgSize, imgEl.naturalWidth, imgEl.naturalHeight);
        if (!fileName || !mw || !mw.loader) {
             gl.uniform1f(uTime, t);
             callback(src);
             gl.uniform2f(uNoiseSc, canvas.width / 512.0, canvas.height / 512.0);
             return;
            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
         }
         }


         if (imgEl.complete && imgEl.naturalWidth) { uploadImg(); }
         cacheKey = fileName + '|' + width;
         else { imgEl.addEventListener('load', uploadImg); }
         entry = thumbCache[cacheKey];


         render();
         if (entry) {
        screen._crtCleanup = function () { cancelAnimationFrame(raf); };
             if (entry.resolved) {
    }
                 callback(entry.url || src);
 
    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 {
             } else {
                 var obs = new MutationObserver(function () {
                 entry.callbacks.push(callback);
                    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 });
             }
             }
        });
            return;
    }
        }


    $(function () { initAllCRTScreens(document); });
        entry = {
            resolved: false,
            url: '',
            callbacks: [callback]
        };


    if (typeof mw !== 'undefined' && mw.hook) {
         thumbCache[cacheKey] = entry;
         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);
        });
    }
})();


/* =========================================
        function finish(url) {
Progress System UI
            var callbacks = entry.callbacks.slice();
MediaWiki:Common.js controlled frontend
            var i;
========================================= */
(function (mw, $) {
    'use strict';


    if (window.ProgressSystemWebUiInitialized) return;
            entry.resolved = true;
    window.ProgressSystemWebUiInitialized = true;
            entry.url = url || src;
            entry.callbacks = [];


    var api = null;
            for (i = 0; i < callbacks.length; i++) {
 
                callbacks[i](entry.url);
    function withApi(done, fail) {
             }
        if (api) {
            done(api);
             return;
         }
         }


         if (!mw.loader || typeof mw.loader.using !== 'function') {
         mw.loader.using('mediawiki.api').done(function () {
             if (typeof fail === 'function') fail();
             var api = new mw.Api();
            return;
        }


        mw.loader.using(['mediawiki.api']).then(function () {
            api.get({
             api = new mw.Api();
                action: 'query',
            done(api);
                titles: 'File:' + fileName,
        }, function () {
                prop: 'imageinfo',
            if (typeof fail === 'function') fail();
                iiprop: 'url',
        });
                iiurlwidth: width,
    }
                formatversion: 2
             }).done(function (data) {
                var page;
                var info;


    var inFlightPageIds = new Set();
                if (
    var handledPageIds = new Set();
                    data &&
    var notificationQueue = [];
                    data.query &&
    var notificationActive = false;
                    data.query.pages &&
    var summaryRequested = false;
                    data.query.pages.length
    var currentSummary = null;
                ) {
    var pendingSummary = null;
                    page = data.query.pages[0];
    var pendingOptions = null;
 
    var visibilityBound = false;
                    if (
    var barTimerA = null;
                        page &&
    var barTimerB = null;
                        page.imageinfo &&
    var barTimerC = null;
                        page.imageinfo.length
    var summaryRetryTimer = null;
                    ) {
    var summaryRetryAttempts = 0;
                        info = page.imageinfo[0];
                    }
                }


    function isLoggedIn() {
                finish((info && (info.thumburl || info.url)) || src);
         return !!mw.config.get('wgUserName');
            }).fail(function () {
                finish(src);
            });
         }).fail(function () {
            finish(src);
        });
     }
     }


     function getPageId() {
     function applySliceImages(frame, thumbUrl) {
         var id = parseInt(mw.config.get('wgArticleId') || 0, 10);
         var slices;
        return Number.isFinite(id) ? id : 0;
        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);
        }


    function isRewardableClientSide() {
         frame.setAttribute('data-crt-slices-ready', '1');
         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() {
     function initBannerFrame(frame) {
         return '' +
         var baseImg;
            '<div id="progress-panel" class="profile-progress-block is-syncing" aria-live="polite" data-progress-state="syncing">' +
        var width;
                '<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() {
        if (!frame) return;
         /* 프로필 패널 최신 규칙: 레벨 패널과 버튼 영역 사이에 별도 나눔선은 만들지 않는다. */
         if (frame.getAttribute('data-crt-slices-ready') === '1') return;
        return '';
    }


    function setPanelSync($panel) {
         baseImg = frame.querySelector('.crt-page-monitor-image-base img');
         if (!$panel || !$panel.length) return;


         $panel.addClass('is-syncing').removeClass('is-max-level').attr('data-progress-state', 'syncing');
         if (!baseImg) return;
        $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) {
         width = parseSliceWidth(frame.getAttribute('data-crt-slice-width'));
         var $right = $('#clbi-right-sidebar');
        if (!$right.length) return false;


         var $userBox = $right.children('.clbi-right-box').first();
         resolveThumbUrl(baseImg, width, function (thumbUrl) {
        if (!$userBox.length) return false;
            if (!frame || !frame.parentNode) return;
            applySliceImages(frame, thumbUrl);
        });
    }


         var $buttonArea = $userBox.children('.clbi-right-content').first();
    function initBannerFrames(root) {
         var $oldFallback = $panel.closest('.progress-panel-fallback');
         var scope = root && root.querySelectorAll ? root : document;
         var frames = scope.querySelectorAll('.crt-page-monitor-frame');
        var i;


         if ($buttonArea.length) {
         for (i = 0; i < frames.length; i++) {
             var $divider = $('#profile-progress-divider');
             initBannerFrame(frames[i]);
        }
    }


            $panel.insertBefore($buttonArea);
    $(function () {
        initBannerFrames(document);
    });


            if (!$divider.length) {
    if (mw && mw.hook) {
                $divider = $(getDividerHtml());
        mw.hook('wikipage.content').add(function ($content) {
            }
            initBannerFrames($content && $content[0] ? $content[0] : document);
        });
    }
})(jQuery, window.mw);


            $divider.insertAfter($panel);
/* =========================================
        } else {
  Doc Tab System — tab switching UI
            $('#profile-progress-divider').remove();
  글리치 플리커 + RGB split + 방향 슬라이드
            $userBox.append($panel);
  ========================================= */
        }


        if ($oldFallback.length && !$oldFallback.find('#progress-panel').length) {
(function () {
            $oldFallback.remove();
    'use strict';
        }


         return true;
    function initDocTabs() {
    }
         var tabBars = document.querySelectorAll('.doc-tab-bar');
        if (!tabBars.length) return;


    function ensurePanel() {
        tabBars.forEach(function (bar) {
        if (!isLoggedIn()) return $();
            if (bar.getAttribute('data-tabs-init')) return;
            bar.setAttribute('data-tabs-init', '1');


        var $right = $('#clbi-right-sidebar');
            var tabs = Array.from(bar.querySelectorAll('.doc-tab'));
        if (!$right.length) return $();
            if (!tabs.length) return;


        var $panel = $('#progress-panel');
            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;


        if (!$panel.length) {
            tabs.forEach(function (tab, i) {
            $panel = $(getPanelHtml());
                tab.addEventListener('click', function () {
            if (!placePanel($panel)) return $();
                    var currentIdx = tabs.findIndex(function (t) {
            setPanelSync($panel);
                        return t.classList.contains('active');
        } else {
                    });
            $panel.addClass('profile-progress-block');
                    if (currentIdx === i) return;
             placePanel($panel);
                    switchTab(tabs, display, i, i > currentIdx ? 1 : -1);
                });
             });


             if (!currentSummary && $panel.attr('data-progress-state') !== 'syncing') {
             var initIdx = tabs.findIndex(function (t) { return t.classList.contains('active'); });
                 setPanelSync($panel);
            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 || '');
             }
             }
         }
         });


        return $('#progress-panel');
     }
     }


     function clampPercent(value) {
    var isAnimating = false;
         return Math.max(0, Math.min(100, value || 0));
 
    }
     function switchTab(tabs, display, nextIdx, dir) {
         if (isAnimating) return;
        isAnimating = true;
 
        tabs.forEach(function (t) { t.classList.remove('active'); });
        tabs[nextIdx].classList.add('active');


    function hasXpNotification(items) {
        var ref = tabs[nextIdx].dataset.ref;
         if (!items || !items.length) return false;
        var nextContent;
        return items.some(function (item) {
         if (ref) {
             return item && item.type === 'xp' && parseInt(item.amount || 0, 10) > 0;
            var refEl = document.getElementById(ref);
         });
             nextContent = refEl ? refEl.innerHTML : '';
    }
        } else {
            nextContent = tabs[nextIdx].dataset.content || '';
         }


    function clearBarTimers() {
        glitchOut(display, dir, function () {
        [barTimerA, barTimerB, barTimerC].forEach(function (timer) {
            display.innerHTML = nextContent;
             if (timer) clearTimeout(timer);
            glitchIn(display, dir, function () {
                isAnimating = false;
             });
         });
         });
        barTimerA = null;
        barTimerB = null;
        barTimerC = null;
     }
     }


     function setBarInstant($fill, $gain, percent) {
     function glitchOut(el, dir, cb) {
         clearBarTimers();
         var duration = 160;
         percent = clampPercent(percent);
         var start = null;
         $fill.css({ transition: 'none', width: percent + '%' });
         var slideX = dir * 16;
        $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) {
        function step(ts) {
        clearBarTimers();
            if (!start) start = ts;
            var p = Math.min((ts - start) / duration, 1);
            var ease = p * p;


        fromPercent = clampPercent(fromPercent);
            var tx = slideX * ease;
        toPercent = clampPercent(toPercent);
            var skew = dir * ease * 1.0;
            var opacity = 1 - ease;
            var rgb = ease * 5;


        $fill.css({ transition: 'none', width: fromPercent + '%' });
            el.style.transform = 'translateX(' + tx + 'px) skewX(' + skew + 'deg)';
 
            el.style.opacity = opacity;
        if (levelChanged) {
            el.style.filter =
            var firstDelta = Math.max(0, 100 - fromPercent);
                '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) + ')';


             $gain.css({
             if (p < 1) {
                 transition: 'none',
                 requestAnimationFrame(step);
                 opacity: firstDelta > 0 ? 1 : 0,
            } else {
                left: fromPercent + '%',
                 el.style.opacity = '0';
                 width: firstDelta + '%'
                 cb();
             });
             }
        }
        requestAnimationFrame(step);
    }


            if ($fill[0]) $fill[0].offsetHeight;
    function glitchIn(el, dir, cb) {
        var duration = 200;
        var start = null;
        var startX = -dir * 16;


            barTimerA = setTimeout(function () {
        el.style.transform = 'translateX(' + startX + 'px) skewX(' + (-dir * 1.0) + 'deg)';
                $fill.css({
        el.style.opacity = '0';
                    transition: 'width 540ms cubic-bezier(0.22, 0.7, 0.18, 1)',
                    width: '100%'
                });
            }, 260);


            barTimerB = setTimeout(function () {
        function step(ts) {
                $fill.css({ transition: 'none', width: '0%' });
            if (!start) start = ts;
                $gain.css({ transition: 'none', opacity: toPercent > 0 ? 1 : 0, left: '0%', width: toPercent + '%' });
            var p = Math.min((ts - start) / duration, 1);
            var ease = 1 - Math.pow(1 - p, 3);


                if ($fill[0]) $fill[0].offsetHeight;
            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;


                $fill.css({
            el.style.transform = 'translateX(' + tx + 'px) skewX(' + skew + 'deg)';
                    transition: 'width 460ms cubic-bezier(0.22, 0.7, 0.18, 1)',
            el.style.opacity = opacity;
                    width: toPercent + '%'
            el.style.filter =
                 });
                'drop-shadow(' + (-rgb) + 'px 0 0 rgba(80,160,255,0.65)) ' +
            }, 860);
                'drop-shadow(' + rgb + 'px 0 0 rgba(255,55,90,0.55)) ' +
                 'brightness(' + brightness + ')';


             barTimerC = setTimeout(function () {
             if (p < 1) {
                 $gain.css({ transition: 'opacity 180ms ease', opacity: 0 });
                requestAnimationFrame(step);
            }, 1380);
            } else {
 
                 el.style.transform = '';
             return;
                el.style.opacity = '';
                el.style.filter = '';
                cb();
             }
         }
         }
        requestAnimationFrame(step);
    }


        var delta = Math.max(0, toPercent - fromPercent);
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initDocTabs);
} else {
    initDocTabs();
}


        if (delta <= 0.15) {
if (typeof mw !== 'undefined' && mw.hook) {
            setBarInstant($fill, $gain, toPercent);
    mw.hook('wikipage.content').add(function () {
            return;
        initDocTabs();
        }
    });
}


        $gain.css({
})();
            transition: 'none',
            opacity: 1,
            left: fromPercent + '%',
            width: delta + '%'
        });


        if ($fill[0]) $fill[0].offsetHeight;
/* =========================================
  Doc Section Switch — 좌측 섹션 전환
  ========================================= */


        barTimerA = setTimeout(function () {
$(document).on('click', '.doc-nav-item[data-section]', function () {
            $fill.css({
    var name = $(this).attr('data-section');
                transition: 'width 560ms cubic-bezier(0.22, 0.7, 0.18, 1)',
    var display = document.getElementById('doc-main-display');
                width: toPercent + '%'
    var titleEl = document.getElementById('doc-center-title');
            });
    var tabBar = document.getElementById('doc-tab-bar-text');
        }, 260);


        barTimerB = setTimeout(function () {
    if (!display) return;
            $gain.css({ transition: 'opacity 180ms ease', opacity: 0 });
        }, 940);
    }


     function updatePanel(summary, options) {
     $('.doc-nav-item[data-section]').removeClass('active');
        if (!summary) return;
    $('.doc-nav-item[data-section="' + name + '"]').addClass('active');


         options = options || {};
    if (name === 'text') {
 
         if (titleEl) titleEl.textContent = '개요';
         var $panel = ensurePanel();
        if (tabBar) $(tabBar).show();
         if (!$panel.length) {
         var activeTab = tabBar ? tabBar.querySelector('.doc-tab.active') : null;
             pendingSummary = $.extend({}, summary);
         if (!activeTab && tabBar) activeTab = tabBar.querySelector('.doc-tab');
             pendingOptions = $.extend({}, options);
        if (activeTab) {
             return;
             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 : '';
    }
});


        var level = summary.level || 1;
/* =========================================
        var totalXp = summary.totalXp || 0;
  CRT WebGL Renderer — cool-retro-term IBM DOS style
        var xpIntoLevel = summary.xpIntoLevel || 0;
  ========================================= */
        var xpForNext = summary.xpForNextLevel || 1;
(function () {
        var percent = clampPercent(summary.progressPercent);
    'use strict';
        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');
    function createNoiseTexture(gl) {
         $panel.find('.progress-level-label').text((isMaxLevel ? 'MAX ' : 'LVL ') + level);
         var size = 512;
         $panel.find('.progress-total-xp').text(totalXp + ' XP');
         var data = new Uint8Array(size * size * 4);
         $panel.find('.progress-xp-next').text(isMaxLevel ? 'MAX LEVEL' : (xpIntoLevel + ' / ' + xpForNext + ' TO NEXT'));
         var s = 12345;
         $panel.find('.progress-daily-xp').text('TODAY ' + dailyXp + ' XP');
         function rand() {
        $panel.find('.progress-discovery-row').text('DISCOVERED ' + discoveries);
            s = (s * 1664525 + 1013904223) & 0xffffffff;
 
            return (s >>> 0) / 0xffffffff;
         var $title = $panel.find('.progress-title-row');
        }
        if (title) {
         for (var i = 0; i < data.length; i++) {
             $title.text(title).prop('hidden', false);
             data[i] = (rand() * 255) | 0;
        } else {
            $title.text('').prop('hidden', true);
         }
         }
        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 $fill = $panel.find('.progress-xp-fill');
    var VERT = [
         var $gain = $panel.find('.progress-xp-gain');
        'attribute vec2 a_pos;',
         var animate = !!options.animateGain && currentSummary && totalXp > (currentSummary.totalXp || 0);
        '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');


         if (animate) {
    var FRAG = [
            animateGain(
         'precision mediump float;',
                $fill,
        'uniform sampler2D u_tex;',
                $gain,
        'uniform sampler2D u_noise;',
                clampPercent(currentSummary.progressPercent),
        'uniform vec2 u_res;',
                percent,
        'uniform vec2 u_imgSize;',
                level !== (currentSummary.level || 1)
        'uniform float u_time;',
            );
         'uniform vec2 u_noiseScale;',
         } else {
         'varying vec2 v_uv;',
            setBarInstant($fill, $gain, percent);
         }


         currentSummary = $.extend({}, summary);
         'float sum2(vec2 v) { return v.x + v.y; }',
        pendingSummary = null;
         'float min2(vec2 v) { return min(v.x, v.y); }',
         pendingOptions = null;
         'float rgb2grey(vec3 v) { return dot(v, vec3(0.21, 0.72, 0.04)); }',
        if (summaryRetryTimer) {
            clearTimeout(summaryRetryTimer);
            summaryRetryTimer = null;
        }
         summaryRetryAttempts = 0;
    }


    function clearSummaryRetry() {
        'vec2 coverUV(vec2 uv) {',
         if (summaryRetryTimer) clearTimeout(summaryRetryTimer);
        '  float imgAR = u_imgSize.x / u_imgSize.y;',
         summaryRetryTimer = null;
         '  float scrAR = u_res.x / u_res.y;',
         summaryRetryAttempts = 0;
         '  float scale = imgAR / scrAR;',
    }
         '  float offsetY = (1.0 - scale) * 0.5;',
        '  return vec2(uv.x, uv.y * scale + offsetY);',
        '}',


    function scheduleSummaryRetry(delay) {
        'vec2 barrel(vec2 v, vec2 cc, float k) {',
         if (!isLoggedIn()) return;
         '  float ar = u_res.x / u_res.y;',
         if (summaryRetryTimer) return;
        '  vec2 c2 = cc;',
         if (summaryRetryAttempts >= 12) return;
        '  if (ar > 1.0) c2.x /= ar; else c2.y *= ar;',
         '  float dist = dot(c2, c2) * k;',
         '  return v - cc * (1.0 + dist) * dist;',
        '}',


         summaryRetryAttempts += 1;
         'vec4 sampleInitialNoise(float t) {',
         summaryRetryTimer = setTimeout(function () {
         '  return texture2D(u_noise, vec2(fract(t/2048.0), fract(t/1048576.0)));',
            summaryRetryTimer = null;
         '}',
            requestSummary();
         }, delay || 1800);
    }


    function requestSummary() {
        'vec4 sampleScreenNoise(vec2 uv) {',
         if (!isLoggedIn()) return;
         '  return texture2D(u_noise, u_noiseScale * uv);',
         if (summaryRequested) return;
         '}',


         summaryRequested = true;
         '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',
        '  );',
        '}',


         withApi(function (api) {
         'vec3 applyBloom(vec2 texUV, float strength) {',
            api.get({
        '  vec2 px = 2.0 / u_res;',
                action: 'progress_summary',
        ' vec3 acc = vec3(0.0);',
                format: 'json',
        ' acc += texture2D(u_tex, clamp(texUV + vec2( px.x, 0.0), 0.0, 1.0)).rgb;',
                formatversion: 2
        '  acc += texture2D(u_tex, clamp(texUV + vec2(-px.x,  0.0), 0.0, 1.0)).rgb;',
            }).then(function (data) {
        '  acc += texture2D(u_tex, clamp(texUV + vec2( 0.0,  px.y), 0.0, 1.0)).rgb;',
                var payload = data && data.progress_summary;
        '  acc += texture2D(u_tex, clamp(texUV + vec2( 0.0, -px.y), 0.0, 1.0)).rgb;',
                if (payload && payload.available && payload.summary) {
        '  acc += texture2D(u_tex, clamp(texUV + vec2( px.x,  px.y), 0.0, 1.0)).rgb * 0.5;',
                    clearSummaryRetry();
        '  acc += texture2D(u_tex, clamp(texUV + vec2(-px.x,  px.y), 0.0, 1.0)).rgb * 0.5;',
                    updatePanel(payload.summary, { animateGain: false });
         '  acc += texture2D(u_tex, clamp(texUV + vec2( px.x, -px.y), 0.0, 1.0)).rgb * 0.5;',
                } else {
        '  acc += texture2D(u_tex, clamp(texUV + vec2(-px.x, -px.y), 0.0, 1.0)).rgb * 0.5;',
                    scheduleSummaryRetry(2200);
         '  return acc / 6.0 * strength;',
                }
        '}',
            }).catch(function () {
                scheduleSummaryRetry(2200);
            }).always(function () {
                summaryRequested = false;
            });
         }, function () {
            summaryRequested = false;
            scheduleSummaryRetry(2200);
         });
    }


    function queueNotifications(items) {
        'vec3 applyScanlines(vec2 uv, vec3 col) {',
         if (!items || !items.length) return;
         '  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;',
        '}',


        items.forEach(function (item) {
'vec3 applyRasterization(vec2 uv, vec3 col) {',
            if (!item) return;
'  float t = u_time;',
            notificationQueue.push(item);
'  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);',
'}',


         showNextNotification();
         '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));',
        '}',


    function notificationText(item) {
        'vec2 applyHSync(vec2 uv, vec4 noise, float strength) {',
         if (item.type === 'xp') {
         '  float randval = strength - noise.r;',
            return '+' + (item.amount || 0) + ' XP · ' + (item.label || '문서 열람');
        ' 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 (item.type === 'achievement') {
         'void main() {',
            var xp = item.amount ? ' · +' + item.amount + ' XP' : '';
        ' vec2 cc = vec2(0.5) - v_uv;',
            return '업적 달성 · ' + (item.label || '새 업적') + xp;
        }


         if (item.type === 'level') {
         '  float curvature = 0.18;',
            return item.label || '레벨 상승';
        ' vec2 uv = barrel(v_uv, cc, curvature);',
        }


         return item.label || '보상 획득';
         '  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; }',


    function showNextNotification() {
        '  vec2 texUV = clamp(coverUV(uv), 0.0, 1.0);',
        if (notificationActive) return;
        if (!notificationQueue.length) return;


         notificationActive = true;
         '  vec4 initNoise = sampleInitialNoise(u_time);',
        var item = notificationQueue.shift();
         '  vec4 screenNoise = sampleScreenNoise(uv);',
         var $root = $('#progress-toast-root');


         if (!$root.length) {
         '  texUV = applyHSync(texUV, initNoise, 0.006);',
            $('body').append('<div id="progress-toast-root"></div>');
        '  texUV = clamp(texUV, 0.0, 1.0);',
            $root = $('#progress-toast-root');
        }


         var $toast = $('<div class="progress-toast"></div>');
         ' texUV += (vec2(screenNoise.b, screenNoise.a) - 0.5) * 0.0006;',
        $toast.text(notificationText(item));
         '  texUV = clamp(texUV, 0.0, 1.0);',
         $root.append($toast);


         requestAnimationFrame(function () {
         '  vec3 col = applyRgbShift(texUV, 0.003);',
            $toast.addClass('is-visible');
         '  col += applyBloom(texUV, 0.22);',
         });


         setTimeout(function () {
         '  vec2 bpx = 1.5 / u_res;',
            $toast.removeClass('is-visible');
        '  vec3 blurCol = vec3(0.0);',
            setTimeout(function () {
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2(-bpx.x, -bpx.y), 0.0, 1.0)).rgb;',
                $toast.remove();
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( 0.0,  -bpx.y), 0.0, 1.0)).rgb;',
                notificationActive = false;
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( bpx.x, -bpx.y), 0.0, 1.0)).rgb;',
                showNextNotification();
        ' blurCol += texture2D(u_tex, clamp(texUV + vec2(-bpx.x,  0.0  ), 0.0, 1.0)).rgb;',
            }, 220);
        '  blurCol += texture2D(u_tex, clamp(texUV + vec2( bpx.x,  0.0  ), 0.0, 1.0)).rgb;',
         }, 2600);
        '  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);',


    function applyPendingSummaryIfPossible() {
         '  col = applyScanlines(uv, col);',
         if (!pendingSummary) return;
         '  col = applyRasterization(texUV, col);',
         updatePanel(pendingSummary, pendingOptions || { animateGain: false });
    }


    function handlePageView() {
         '  float glow = glowingLine(uv, u_time);',
         ensurePanel();
'  col += glow * 0.08 * vec3(0.85, 0.95, 1.0);',
        applyPendingSummaryIfPossible();


         if (!isRewardableClientSide()) {
         '  float dist = length(cc);',
            requestSummary();
        '  col += screenNoise.a * 0.07 * (1.0 - dist * 1.3);',
            return;
        }


         var pageId = getPageId();
         '  float grey = rgb2grey(col);',
         if (handledPageIds.has(pageId)) {
         '  vec3 phosphor = vec3(0.75, 0.88, 1.0);',
            requestSummary();
        '  col = mix(col, grey * phosphor, 0.35);',
            return;
        }


         if (inFlightPageIds.has(pageId)) {
         '  vec2 vig = v_uv * (1.0 - v_uv);',
            requestSummary();
        '  col *= pow(vig.x * vig.y * 15.0, 0.25);',
            return;
        }


         inFlightPageIds.add(pageId);
         '  col *= 1.0 + (initNoise.g - 0.5) * 0.06;',


         withApi(function (api) {
         '  col += vec3(0.012) * (1.0 - dist) * (1.0 - dist);',
            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);
        '  col = pow(clamp(col, 0.0, 1.0), vec3(0.90));',


                var animate = hasXpNotification(payload.notifications);
        '  gl_FragColor = vec4(col, 1.0);',
        '}'
    ].join('\n');


                if (payload.summary) {
    function initCRTCanvas(screen, imgEl) {
                    updatePanel(payload.summary, { animateGain: animate });
        var existing = screen.querySelector('.crt-webgl-canvas');
                }
        if (existing) existing.remove();


                if (payload.notifications && payload.notifications.length) {
        var canvas = document.createElement('canvas');
                    queueNotifications(payload.notifications);
        canvas.className = 'crt-webgl-canvas';
                }
        canvas.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;z-index:19;pointer-events:none;display:block;';
            }).catch(function () {
         screen.appendChild(canvas);
                requestSummary();
            }).always(function () {
                inFlightPageIds.delete(pageId);
            });
         }, function () {
            inFlightPageIds.delete(pageId);
            requestSummary();
        });
    }


    function bindVisibilitySync() {
        var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
         if (visibilityBound) return;
         if (!gl) return;
        visibilityBound = true;


         document.addEventListener('visibilitychange', function () {
         function compile(type, src) {
             if (document.visibilityState === 'visible') {
            var s = gl.createShader(type);
                 requestSummary();
            gl.shaderSource(s, src);
            gl.compileShader(s);
             if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) {
                 console.error('[CRT shader]', gl.getShaderInfoLog(s));
             }
             }
        });
             return s;
    }
 
    function bootProgressSystem(reason) {
        ensurePanel();
        applyPendingSummaryIfPossible();
 
        if (isRewardableClientSide()) {
             handlePageView();
        } else {
            requestSummary();
         }
         }


         setTimeout(function () {
         var prog = gl.createProgram();
            ensurePanel();
        gl.attachShader(prog, compile(gl.VERTEX_SHADER, VERT));
            applyPendingSummaryIfPossible();
        gl.attachShader(prog, compile(gl.FRAGMENT_SHADER, FRAG));
            requestSummary();
        gl.linkProgram(prog);
         }, 350);
         gl.useProgram(prog);


         setTimeout(function () {
         var buf = gl.createBuffer();
            ensurePanel();
        gl.bindBuffer(gl.ARRAY_BUFFER, buf);
            applyPendingSummaryIfPossible();
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1,-1, 1,-1, -1,1, 1,1]), gl.STATIC_DRAW);
            requestSummary();
        var aPos = gl.getAttribLocation(prog, 'a_pos');
         }, 1500);
        gl.enableVertexAttribArray(aPos);
    }
         gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);


     function handleSpaPageView() {
        var uTex    = gl.getUniformLocation(prog, 'u_tex');
         ensurePanel();
        var uNoise  = gl.getUniformLocation(prog, 'u_noise');
         applyPendingSummaryIfPossible();
        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');


         requestAnimationFrame(function () {
         var imgTex = gl.createTexture();
            setTimeout(function () {
        gl.activeTexture(gl.TEXTURE0);
                handlePageView();
        gl.bindTexture(gl.TEXTURE_2D, imgTex);
            }, 80);
        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 applySummary(summary, options) {
        gl.activeTexture(gl.TEXTURE1);
         updatePanel(summary, options || { animateGain: false });
         createNoiseTexture(gl);
    }


    window.ProgressSystemWebUi = {
        var texReady = false;
        boot: bootProgressSystem,
        function uploadImg() {
        requestSummary: requestSummary,
            if (!imgEl || !imgEl.complete || !imgEl.naturalWidth) return;
        applySummary: applySummary,
            try {
        handlePageView: handlePageView,
                gl.activeTexture(gl.TEXTURE0);
        handleSpaPageView: handleSpaPageView,
                gl.bindTexture(gl.TEXTURE_2D, imgTex);
         ensurePanel: ensurePanel
                gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, imgEl);
    };
                texReady = true;
            } catch(e) { console.error('[CRT] tex:', e); }
         }


    $(function () {
        var lastW = 0, lastH = 0;
        bindVisibilitySync();
        function resize() {
        bootProgressSystem('documentReady');
            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);
        }


    mw.hook('wikipage.content').add(function () {
         var raf;
         ensurePanel();
         var visualTime = 0;
         applyPendingSummaryIfPossible();
         var lastVisualNow = 0;
         setTimeout(function () {
            ensurePanel();
            applyPendingSummaryIfPossible();
            requestSummary();
        }, 120);
    });
})(mediaWiki, jQuery);


        function render(now) {
            var delta;
            raf = requestAnimationFrame(render);


/* CLBI Nations / Historical Events year tabs
            if (!lastVisualNow) lastVisualNow = now;
* Mirrors the country information panel model:
            delta = Math.max(0, Math.min(100, now - lastVisualNow));
* active tab uses .is-active/aria-selected and inactive pages use hidden.
            lastVisualNow = now;
*/
(function (mw, $) {
    'use strict';


    function activateClbiNationsHistoryYear(panel, targetYear) {
            if (document.hidden || isClbiCompositorBusy()) return;
        var tabs;
            if (!texReady) { uploadImg(); return; }
        var pages;


        if (!panel || !targetYear) return false;
            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);
        }


         tabs = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-year-button[data-year]'));
         if (imgEl.complete && imgEl.naturalWidth) { uploadImg(); }
         pages = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-page[data-year-panel]'));
         else { imgEl.addEventListener('load', uploadImg); }


         if (!tabs.length || !pages.length) return false;
         render();
 
         screen._crtCleanup = function () { cancelAnimationFrame(raf); };
         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) {
     function initAllCRTScreens(root) {
         var tabs;
         var scope = root && root.querySelectorAll ? root : document;
         var activeIndex;
         scope.querySelectorAll('.crt-page-monitor-screen').forEach(function (screen) {
        var nextIndex;
            if (screen.getAttribute('data-crt-webgl') === '1') return;
         var target;
            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 });
            }
         });
    }


        if (!panel) return false;
    $(function () { initAllCRTScreens(document); });


         tabs = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-year-button[data-year]'));
    if (typeof mw !== 'undefined' && mw.hook) {
         if (!tabs.length) return false;
         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);
         });
    }
})();


        activeIndex = tabs.findIndex(function (tab) {
/* =========================================
            return tab.classList.contains('is-active') || tab.getAttribute('aria-selected') === 'true';
Progress System UI
        });
MediaWiki:Common.js controlled frontend
========================================= */
(function (mw, $) {
    'use strict';


        if (activeIndex < 0) activeIndex = 0;
    if (window.ProgressSystemWebUiInitialized) return;
    window.ProgressSystemWebUiInitialized = true;


        nextIndex = (activeIndex + direction + tabs.length) % tabs.length;
    var api = null;
        target = tabs[nextIndex].getAttribute('data-year');


         if (activateClbiNationsHistoryYear(panel, target)) {
    function withApi(done, fail) {
             tabs[nextIndex].focus();
         if (api) {
             return true;
             done(api);
             return;
         }
         }


         return false;
         if (!mw.loader || typeof mw.loader.using !== 'function') {
    }
            if (typeof fail === 'function') fail();
            return;
        }


    function initClbiNationsHistoryYearTabs(root) {
        mw.loader.using(['mediawiki.api']).then(function () {
        var scope = root && root.querySelectorAll ? root : document;
            api = new mw.Api();
         var panels = scope.querySelectorAll('.clbi-nations-history-panel');
            done(api);
         }, function () {
            if (typeof fail === 'function') fail();
        });
    }


        Array.prototype.forEach.call(panels, function (panel) {
    var inFlightPageIds = new Set();
            if (panel.getAttribute('data-clbi-history-tabs-ready') === '1') return;
    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;


            panel.setAttribute('data-clbi-history-tabs-ready', '1');
    function isLoggedIn() {
        return !!mw.config.get('wgUserName');
    }


            panel.addEventListener('click', function (event) {
    function getPageId() {
                var tab = event.target.closest ? event.target.closest('.clbi-nations-history-year-button[data-year]') : null;
        var id = parseInt(mw.config.get('wgArticleId') || 0, 10);
        return Number.isFinite(id) ? id : 0;
    }


                if (!tab || !panel.contains(tab)) return;
    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;
    }


                if (activateClbiNationsHistoryYear(panel, tab.getAttribute('data-year'))) {
    function getPanelHtml() {
                    event.preventDefault();
        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">' +
             panel.addEventListener('keydown', function (event) {
                    '<span class="progress-level-label">SYNC</span>' +
                var tab = event.target.closest ? event.target.closest('.clbi-nations-history-year-button[data-year]') : null;
                    '<span class="progress-total-xp">— XP</span>' +
                 var handled = false;
                 '</div>' +
 
                 '<div class="progress-xp-bar" aria-hidden="true">' +
                 if (!tab || !panel.contains(tab)) return;
                    '<div class="progress-xp-gain"></div>' +
 
                    '<div class="progress-xp-fill"></div>' +
                if (event.key === 'ArrowLeft') handled = moveClbiNationsHistoryYear(panel, -1);
                '</div>' +
                 else if (event.key === 'ArrowRight') handled = moveClbiNationsHistoryYear(panel, 1);
                 '<div class="progress-sub-row">' +
                 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'));
                     '<span class="progress-xp-next">SYNCING</span>' +
                 else if (event.key === 'End') {
                     '<span class="progress-daily-xp">TODAY —</span>' +
                     var tabs = panel.querySelectorAll('.clbi-nations-history-year-button[data-year]');
                '</div>' +
                     var last = tabs[tabs.length - 1];
                '<div class="progress-discovery-row">DISCOVERED —</div>' +
                    handled = last ? activateClbiNationsHistoryYear(panel, last.getAttribute('data-year')) : false;
            '</div>';
                    if (handled) last.focus();
    }
                }


                if (handled) {
    function getDividerHtml() {
                    event.preventDefault();
        /* 프로필 패널 최신 규칙: 레벨 패널과 버튼 영역 사이에 별도 나눔선은 만들지 않는다. */
                    event.stopPropagation();
         return '';
                }
            });
         });
     }
     }


     window.initClbiNationsHistoryYearTabs = initClbiNationsHistoryYearTabs;
     function setPanelSync($panel) {
        if (!$panel || !$panel.length) return;


    $(function () {
        $panel.addClass('is-syncing').removeClass('is-max-level').attr('data-progress-state', 'syncing');
         initClbiNationsHistoryYearTabs(document);
        $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 });
     }


     if (mw && mw.hook) {
     function placePanel($panel) {
         mw.hook('wikipage.content').add(function ($content) {
         var $right = $('#clbi-right-sidebar');
            initClbiNationsHistoryYearTabs($content && $content[0] ? $content[0] : document);
         if (!$right.length) return false;
         });
    }
})(mediaWiki, jQuery);


        var $userBox = $right.children('.clbi-right-box').first();
        if (!$userBox.length) return false;


/* =========================================
        var $buttonArea = $userBox.children('.clbi-right-content').first();
  Decoration runtime renderer
        var $oldFallback = $panel.closest('.progress-panel-fallback');
  ========================================= */
(function (mw) {
    'use strict';


    var REGISTRY_TITLE = 'MediaWiki:Decorations.json';
        if ($buttonArea.length) {
    var RENDERED_ATTR = 'data-wiki-decoration-rendered';
            var $divider = $('#profile-progress-divider');
    var HOST_ATTR = 'data-wiki-decoration-host';
 
    var runtimeToken = 0;
            $panel.insertBefore($buttonArea);
    var lastRegistry = null;
    var lastRenderedPageKey = '';
    var scheduledRender = 0;
    var nationsPlacementObserver = null;
    var observedNationsStack = null;
    var pixelAssetCache = {};
    var pixelCanvasCache = {};


    function normalizePageName(value) {
            if (!$divider.length) {
        return String(value || '')
                $divider = $(getDividerHtml());
            .split('?')[0]
            }
            .replace(/^\/index\.php\//, '')
            .replace(/_/g, ' ')
            .trim();
    }


    function currentPageKey() {
            $divider.insertAfter($panel);
        var raw = mw && mw.config ? String(mw.config.get('wgPageName') || '') : '';
        } else {
        return normalizePageName(raw) || raw || '대문';
            $('#profile-progress-divider').remove();
    }
            $userBox.append($panel);
        }


        if ($oldFallback.length && !$oldFallback.find('#progress-panel').length) {
            $oldFallback.remove();
        }


    function cssAttrEscape(value) {
         return true;
         return String(value || '').replace(/\\/g, '\\\\').replace(/"/g, '\\"');
     }
     }


     function getActiveNationsEra() {
     function ensurePanel() {
         var content = document.querySelector('.clbi-nations-era-content.is-active[data-era-content]:not([hidden])');
        if (!isLoggedIn()) return $();
         var title;
 
        var globe;
         var $right = $('#clbi-right-sidebar');
         if (!$right.length) return $();


         if (content) return content.getAttribute('data-era-content') || '';
         var $panel = $('#progress-panel');


         title = document.querySelector('.clbi-nations-era-title-plate.is-active[data-era]');
         if (!$panel.length) {
        if (title) return title.getAttribute('data-era') || '';
            $panel = $(getPanelHtml());
            if (!placePanel($panel)) return $();
            setPanelSync($panel);
        } else {
            $panel.addClass('profile-progress-block');
            placePanel($panel);


        globe = document.querySelector('.clbi-nations-globe-window[data-nations-globe]');
            if (!currentSummary && $panel.attr('data-progress-state') !== 'syncing') {
        if (globe) {
                setPanelSync($panel);
            return globe.getAttribute('data-current-era') || globe.getAttribute('data-nations-current-era') || globe.getAttribute('data-era-year') || '';
            }
         }
         }


         return '';
         return $('#progress-panel');
     }
     }


     function getActiveNationsEraPanel() {
     function clampPercent(value) {
         var era = getActiveNationsEra();
         return Math.max(0, Math.min(100, value || 0));
        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() {
     function hasXpNotification(items) {
         var eraPanel = getActiveNationsEraPanel();
         if (!items || !items.length) return false;
        var root = eraPanel || document;
         return items.some(function (item) {
         var tab = root.querySelector('.clbi-nations-tabpanel-tab.is-active[data-continent], .clbi-nations-tabpanel-tab[aria-selected="true"][data-continent]');
            return item && item.type === 'xp' && parseInt(item.amount || 0, 10) > 0;
         var panel;
         });
    }


         if (tab) return tab.getAttribute('data-continent') || '';
    function clearBarTimers() {
 
         [barTimerA, barTimerB, barTimerC].forEach(function (timer) {
         panel = root.querySelector('.clbi-nations-tabpanel-continent.is-active[data-continent-panel]');
            if (timer) clearTimeout(timer);
         if (panel) return panel.getAttribute('data-continent-panel') || '';
        });
 
         barTimerA = null;
         return '';
         barTimerB = null;
         barTimerC = null;
     }
     }


     function getDecorationNationsBodySelector(era) {
     function setBarInstant($fill, $gain, percent) {
         if (era) {
         clearBarTimers();
            return '.clbi-nations-era-content[data-era-content="' + cssAttrEscape(era) + '"] .clbi-nations-tabpanel-body';
        percent = clampPercent(percent);
         }
        $fill.css({ transition: 'none', width: percent + '%' });
         return '.clbi-nations-era-content.is-active[data-era-content]:not([hidden]) .clbi-nations-tabpanel-body, .clbi-nations-tabpanel-body';
         $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) {
    Decoration semantic placement resolver
        clearBarTimers();
    -----------------------------------------
    장식 저장 데이터의 placement 값은 "사용자가 고른 의미상 위치"를 나타낸다.
    resolver는 그 의미값을 실제 DOM 부착 위치와 표시 조건으로 번역한다.


    예: 국가 및 조합에서 사용자가 1950년 / 아메리카를 지정하면 의미상 scope는
        fromPercent = clampPercent(fromPercent);
    그 조합이지만, 이미지를 붙일 기준면은 대륙 패널 자체가 아니라
        toPercent = clampPercent(toPercent);
    .clbi-nations-tabpanel-body이다. 따라서 placement=nations-continent-body는
    .clbi-nations-tabpanel-body에 이미지를 붙이고, 현재 활성 연도와 대륙이 저장값과
    일치할 때만 렌더링한다.


    유지보수 규칙:
        $fill.css({ transition: 'none', width: fromPercent + '%' });
    - 새 조합형 문서가 생기면 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 (levelChanged) {
        if (placement === 'nations-continent-body') return true;
            var firstDelta = Math.max(0, 100 - fromPercent);
        if (era || continent) return true;
 
        if (target.indexOf('clbi-nations-tabpanel-continent') !== -1) return true;
            $gain.css({
        return false;
                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 + '%' });


    function resolveDecorationPlacement(entry) {
                if ($fill[0]) $fill[0].offsetHeight;
        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)) {
                $fill.css({
            placement = 'nations-continent-body';
                    transition: 'width 460ms cubic-bezier(0.22, 0.7, 0.18, 1)',
        }
                    width: toPercent + '%'
                });
            }, 860);


        if (placement === 'boot-gate' || placement === 'loading-screen') {
             barTimerC = setTimeout(function () {
             selector = '#boot-gate-screen .boot-gate-decoration-layer, #boot-gate-screen';
                 $gain.css({ transition: 'opacity 180ms ease', opacity: 0 });
            target = document.querySelector(selector);
             }, 1380);
            return {
                 placement: placement,
                target: target,
                targetSelector: selector,
                visible: !!document.getElementById('boot-gate-screen')
             };
        }


        if (placement === 'nations-continent-body') {
             return;
            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())
            };
         }
         }


         return {
         var delta = Math.max(0, toPercent - fromPercent);
            placement: placement,
            target: document.querySelector(selector),
            targetSelector: selector,
            visible: true
        };
    }


    function normalizeNumber(value, fallback) {
        if (delta <= 0.15) {
        var n = parseFloat(value);
            setBarInstant($fill, $gain, toPercent);
        return Number.isFinite(n) ? n : fallback;
            return;
    }
        }


    function normalizeBool(value, fallback) {
        $gain.css({
        if (value === true || value === 'true' || value === '1' || value === 1) return true;
            transition: 'none',
        if (value === false || value === 'false' || value === '0' || value === 0) return false;
            opacity: 1,
         return fallback;
            left: fromPercent + '%',
    }
            width: delta + '%'
         });


    function normalizeSrc(src) {
         if ($fill[0]) $fill[0].offsetHeight;
        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);
    }


        barTimerA = setTimeout(function () {
            $fill.css({
                transition: 'width 560ms cubic-bezier(0.22, 0.7, 0.18, 1)',
                width: toPercent + '%'
            });
        }, 260);


    function normalizeAssetType(entry) {
         barTimerB = setTimeout(function () {
         var type = String(entry && entry.assetType || '').trim().toLowerCase();
            $gain.css({ transition: 'opacity 180ms ease', opacity: 0 });
        var ref = String(entry && (entry.asset || entry.src) || '').trim();
         }, 940);
 
        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) {
     function updatePanel(summary, options) {
         return normalizeAssetType(entry) === 'pixel-json';
         if (!summary) return;
    }


    function getPixelJsonRef(entry) {
         options = options || {};
         return String(entry && (entry.asset || entry.src) || '').trim();
    }


    function normalizePixelJsonUrl(ref) {
         var $panel = ensurePanel();
         ref = String(ref || '').trim();
         if (!$panel.length) {
         if (!ref) return '';
            pendingSummary = $.extend({}, summary);
        if (/^(?:https?:)?\/\//i.test(ref) || ref.charAt(0) === '/' || ref.indexOf('data:') === 0 || ref.indexOf('blob:') === 0) return ref;
             pendingOptions = $.extend({}, options);
        if (/^(?:file|파일):/i.test(ref)) return '/index.php/Special:Redirect/file/' + encodeURIComponent(ref.replace(/^(?:file|파일):/i, ''));
             return;
        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 level = summary.level || 1;
         var text;
        var totalXp = summary.totalXp || 0;
         var m;
         var xpIntoLevel = summary.xpIntoLevel || 0;
         if (Array.isArray(value)) {
         var xpForNext = summary.xpForNextLevel || 1;
            return [
         var percent = clampPercent(summary.progressPercent);
                Math.max(0, Math.min(255, Number(value[0]) || 0)),
        var isMaxLevel = !!summary.isMaxLevel;
                Math.max(0, Math.min(255, Number(value[1]) || 0)),
        var dailyXp = summary.dailyXp || 0;
                Math.max(0, Math.min(255, Number(value[2]) || 0)),
        var discoveries = summary.discoveryCount || 0;
                value.length > 3 ? Math.max(0, Math.min(255, Number(value[3]) || 0)) : 255
        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);
         }
         }
        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 $fill = $panel.find('.progress-xp-fill');
        var $gain = $panel.find('.progress-xp-gain');
        var animate = !!options.animateGain && currentSummary && totalXp > (currentSummary.totalXp || 0);


    function decodePixelRle36(value) {
        if (animate) {
        var text = String(value || '').trim();
            animateGain(
        var parts;
                $fill,
        var runs = [];
                $gain,
        var i;
                clampPercent(currentSummary.progressPercent),
         var x;
                percent,
        var y;
                level !== (currentSummary.level || 1)
        var len;
            );
         var colorIndex;
         } else {
            setBarInstant($fill, $gain, percent);
         }


         if (!text) return runs;
         currentSummary = $.extend({}, summary);
        parts = text.split(',');
         pendingSummary = null;
         for (i = 0; i + 3 < parts.length; i += 4) {
        pendingOptions = null;
            x = parseInt(parts[i], 36);
        if (summaryRetryTimer) {
            y = parseInt(parts[i + 1], 36);
             clearTimeout(summaryRetryTimer);
             len = parseInt(parts[i + 2], 36);
             summaryRetryTimer = null;
             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;
         summaryRetryAttempts = 0;
     }
     }


     function normalizePixelAsset(doc) {
     function clearSummaryRetry() {
         var encoding = String(doc && (doc.encoding || doc.e) || '').trim().toLowerCase();
         if (summaryRetryTimer) clearTimeout(summaryRetryTimer);
         var width = Math.round(Number(doc && (doc.width || doc.w)) || 0);
         summaryRetryTimer = null;
         var height = Math.round(Number(doc && (doc.height || doc.h)) || 0);
         summaryRetryAttempts = 0;
        var paletteSource = Array.isArray(doc && doc.palette) ? doc.palette : (Array.isArray(doc && doc.p) ? doc.p : []);
    }
        var palette = paletteSource.map(parsePixelColor);
        var runs;


        /*
    function scheduleSummaryRetry(delay) {
        CLBI Pixel Forge v0.2.3 compact format:
         if (!isLoggedIn()) return;
        - MediaWiki 단일 문서 크기 제한을 피하기 위해 사람이 읽기 쉬운 [[x,y,len,c], ...] 배열 대신
        if (summaryRetryTimer) return;
          base36 토큰 문자열을 쓴다.
         if (summaryRetryAttempts >= 12) return;
        - 형식은 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');
         summaryRetryAttempts += 1;
         if (width > 8192 || height > 8192) throw new Error('pixel decoration too large');
         summaryRetryTimer = setTimeout(function () {
        return {
             summaryRetryTimer = null;
             type: String(doc && (doc.type || doc.t) || 'clbi-pixel-decoration'),
             requestSummary();
             version: Number(doc && (doc.version || doc.v)) || 1,
        }, delay || 1800);
            encoding: encoding || 'runs',
            width: width,
            height: height,
            palette: palette,
            runs: runs
        };
     }
     }


     function fetchPixelAsset(ref) {
     function requestSummary() {
        var url = normalizePixelJsonUrl(ref);
         if (!isLoggedIn()) return;
        var cached;
         if (summaryRequested) return;
         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) {
         summaryRequested = true;
         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;
         withApi(function (api) {
        canvas.height = asset.height;
            api.get({
        ctx = canvas.getContext('2d');
                action: 'progress_summary',
        ctx.imageSmoothingEnabled = false;
                format: 'json',
         image = ctx.createImageData(asset.width, asset.height);
                formatversion: 2
         data = image.data;
            }).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);
         });
    }


        for (i = 0; i < asset.runs.length; i += 1) {
    function queueNotifications(items) {
            run = asset.runs[i];
        if (!items || !items.length) return;
            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);
         items.forEach(function (item) {
    }
            if (!item) return;
 
             notificationQueue.push(item);
    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) {
         showNextNotification();
         var url = normalizePixelJsonUrl(ref);
        var cached = url ? pixelCanvasCache[url] : null;
        return cached && cached.canvas ? cached.canvas : null;
     }
     }


     function applyDecorationBaseStyle(node, entry) {
     function notificationText(item) {
         node.style.left = normalizeNumber(entry.x, 0) + 'px';
         if (item.type === 'xp') {
        node.style.top = normalizeNumber(entry.y, 0) + 'px';
            return '+' + (item.amount || 0) + ' XP · ' + (item.label || '문서 열람');
        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 (item.type === 'achievement') {
         if (entry.blendMode) node.style.mixBlendMode = String(entry.blendMode);
            var xp = item.amount ? ' · +' + item.amount + ' XP' : '';
        if (entry.filter) node.style.filter = String(entry.filter);
            return '업적 달성 · ' + (item.label || '새 업적') + xp;
        if (entry.transform) node.style.transform = String(entry.transform);
        }
    }


    function isDecorationNodeActiveForNationsState(node) {
         if (item.type === 'level') {
         var era = node ? String(node.getAttribute('data-decoration-era') || '').trim() : '';
            return item.label || '레벨 상승';
        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) {
         return item.label || '보상 획득';
         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) {
     function showNextNotification() {
         var scope = root && root.querySelectorAll ? root : document;
         if (notificationActive) return;
        var count = 0;
         if (!notificationQueue.length) return;
         Array.prototype.forEach.call(scope.querySelectorAll('[' + RENDERED_ATTR + '="1"]'), function (node) {
            setDecorationNodeVisibility(node, isDecorationNodeActiveForNationsState(node));
            count += 1;
        });
        return count;
    }


    function hasRenderedDecorations(root) {
        notificationActive = true;
         var scope = root && root.querySelector ? root : document;
         var item = notificationQueue.shift();
         return !!(scope && scope.querySelector && scope.querySelector('[' + RENDERED_ATTR + '="1"]'));
         var $root = $('#progress-toast-root');
    }


    function applyPixelJsonDecoration(entry, target, visible) {
        if (!$root.length) {
        var ref = getPixelJsonRef(entry);
            $('body').append('<div id="progress-toast-root"></div>');
        var template;
            $root = $('#progress-toast-root');
         var canvas;
         }
        var ctx;
        if (!ref) return false;


         function makeCanvasFromTemplate(source) {
         var $toast = $('<div class="progress-toast"></div>');
            var out = document.createElement('canvas');
        $toast.text(notificationText(item));
            var outCtx;
        $root.append($toast);
            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);
         requestAnimationFrame(function () {
        if (template) {
             $toast.addClass('is-visible');
             target.appendChild(makeCanvasFromTemplate(template));
         });
            return true;
         }


         /* Fallback path only.  A full entry pack should prepare the template before the
         setTimeout(function () {
          normal UI is released, so users should not see a blank decoration canvas. */
            $toast.removeClass('is-visible');
        preparePixelCanvas(ref).then(function (source) {
            setTimeout(function () {
            if (!target || !target.parentNode || !source) return;
                $toast.remove();
            target.appendChild(makeCanvasFromTemplate(source));
                notificationActive = false;
         }).catch(function () {});
                showNextNotification();
            }, 220);
         }, 2600);
    }


         return true;
    function applyPendingSummaryIfPossible() {
         if (!pendingSummary) return;
        updatePanel(pendingSummary, pendingOptions || { animateGain: false });
     }
     }


     function preloadPixelAssetsForRegistry(registry) {
     function handlePageView() {
         var promises = [];
         ensurePanel();
        decorationList(registry).forEach(function (entry) {
         applyPendingSummaryIfPossible();
            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 (!isRewardableClientSide()) {
         if (!registry || typeof registry !== 'object') return [];
            requestSummary();
        if (Array.isArray(registry)) return registry;
            return;
        if (Array.isArray(registry.decorations)) return registry.decorations;
        }
        return [];
    }


    function matchesPage(entry) {
         var pageId = getPageId();
         var page = currentPageKey();
         if (handledPageIds.has(pageId)) {
         var underscored = page.replace(/ /g, '_');
            requestSummary();
        var pages = entry && entry.pages;
             return;
        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)) {
         if (inFlightPageIds.has(pageId)) {
             for (i = 0; i < pages.length; i += 1) {
             requestSummary();
                if (normalizePageName(pages[i]) === page || String(pages[i] || '') === underscored) return true;
            return;
            }
         }
         }


         target = normalizePageName(target);
         inFlightPageIds.add(pageId);
        return target === page || target === underscored;
    }


    function clearRendered(root) {
        withApi(function (api) {
        var scope = root && root.querySelectorAll ? root : document;
            api.postWithToken('csrf', {
        Array.prototype.forEach.call(scope.querySelectorAll('[' + RENDERED_ATTR + '="1"]'), function (node) {
                action: 'progress_view',
            if (node.parentNode) node.parentNode.removeChild(node);
                format: 'json',
        });
                formatversion: 2,
    }
                errorformat: 'plaintext',
                pageid: pageId
            }).then(function (data) {
                var payload = data && data.progress_view;
                if (!payload) return;


    function ensureHost(target) {
                handledPageIds.add(pageId);
        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 animate = hasXpNotification(payload.notifications);
        var resolved;
        var target;
        var src;
        var img;
        var width;
        var height;


        if (!entry || typeof entry !== 'object' || normalizeBool(entry.enabled, true) === false) return false;
                if (payload.summary) {
        resolved = resolveDecorationPlacement(entry);
                    updatePanel(payload.summary, { animateGain: animate });
        if (!resolved) return false;
                }
        target = resolved.target;
        if (!target) return false;


         ensureHost(target);
                if (payload.notifications && payload.notifications.length) {
                    queueNotifications(payload.notifications);
                }
            }).catch(function () {
                requestSummary();
            }).always(function () {
                inFlightPageIds.delete(pageId);
            });
         }, function () {
            inFlightPageIds.delete(pageId);
            requestSummary();
        });
    }


        if (isPixelJsonDecoration(entry)) {
    function bindVisibilitySync() {
            return applyPixelJsonDecoration(entry, target, resolved.visible !== false);
        if (visibilityBound) return;
         }
         visibilityBound = true;


         src = normalizeSrc(entry.src);
         document.addEventListener('visibilitychange', function () {
         if (!src) return false;
            if (document.visibilityState === 'visible') {
                requestSummary();
            }
         });
    }


        img = document.createElement('img');
    function bootProgressSystem(reason) {
        img.className = 'wiki-decoration';
         ensurePanel();
         img.setAttribute(RENDERED_ATTR, '1');
         applyPendingSummaryIfPossible();
         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 (isRewardableClientSide()) {
        width = normalizeNumber(entry.width, NaN);
            handlePageView();
        height = normalizeNumber(entry.height, NaN);
         } else {
        if (Number.isFinite(width) && width > 0) img.style.width = width + 'px';
            requestSummary();
         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);
         setTimeout(function () {
        return true;
            ensurePanel();
    }
            applyPendingSummaryIfPossible();
            requestSummary();
        }, 350);


    function render(registry) {
        setTimeout(function () {
        var token = runtimeToken;
            ensurePanel();
        lastRegistry = registry || { decorations: [] };
            applyPendingSummaryIfPossible();
        lastRenderedPageKey = currentPageKey();
             requestSummary();
        bindNationsPlacementRefresh();
         }, 1500);
        clearRendered(document);
        decorationList(lastRegistry).forEach(function (entry) {
             if (token === runtimeToken && matchesPage(entry)) applyDecoration(entry);
         });
     }
     }


     function renderPrepared() {
     function handleSpaPageView() {
         var registry = getPreparedRegistrySync() || lastRegistry;
         ensurePanel();
         if (!registry) return false;
         applyPendingSummaryIfPossible();
        render(registry);
        return true;
    }


    function syncDecorationState() {
        requestAnimationFrame(function () {
        if (lastRenderedPageKey === currentPageKey() && hasRenderedDecorations(document)) {
            setTimeout(function () {
            updateDecorationVisibility(document);
                handlePageView();
             return true;
             }, 80);
        }
         });
        if (lastRegistry) {
            render(lastRegistry);
            return true;
         }
        return renderPrepared();
     }
     }


     function scheduleRenderFromCache() {
     function applySummary(summary, options) {
         if (scheduledRender) return;
         updatePanel(summary, options || { animateGain: false });
        scheduledRender = window.requestAnimationFrame ? window.requestAnimationFrame(function () {
            scheduledRender = 0;
            if (!syncDecorationState()) reload();
        }) : window.setTimeout(function () {
            scheduledRender = 0;
            if (!syncDecorationState()) reload();
        }, 0);
     }
     }


     function scheduleDecorationVisibilityUpdate() {
     window.ProgressSystemWebUi = {
         if (scheduledRender) return;
         boot: bootProgressSystem,
         scheduledRender = window.requestAnimationFrame ? window.requestAnimationFrame(function () {
         requestSummary: requestSummary,
            scheduledRender = 0;
        applySummary: applySummary,
            if (lastRenderedPageKey !== currentPageKey() || !hasRenderedDecorations(document)) {
        handlePageView: handlePageView,
                if (!syncDecorationState()) reload();
        handleSpaPageView: handleSpaPageView,
                return;
        ensurePanel: ensurePanel
            }
    };
            updateDecorationVisibility(document);
 
        }) : window.setTimeout(function () {
    $(function () {
            scheduledRender = 0;
        bindVisibilitySync();
            if (lastRenderedPageKey !== currentPageKey() || !hasRenderedDecorations(document)) {
        bootProgressSystem('documentReady');
                if (!syncDecorationState()) reload();
    });
                return;
            }
            updateDecorationVisibility(document);
        }, 0);
    }


     function bindNationsPlacementRefresh() {
     mw.hook('wikipage.content').add(function () {
         var stack = document.querySelector('.clbi-nations-panel-stack');
         ensurePanel();
        applyPendingSummaryIfPossible();
        setTimeout(function () {
            ensurePanel();
            applyPendingSummaryIfPossible();
            requestSummary();
        }, 120);
    });
})(mediaWiki, jQuery);


        if (!stack || observedNationsStack === stack) return;
        observedNationsStack = stack;


        if (nationsPlacementObserver) {
/* CLBI Nations / Historical Events year tabs
            nationsPlacementObserver.disconnect();
* Mirrors the country information panel model:
        }
* active tab uses .is-active/aria-selected and inactive pages use hidden.
*/
(function (mw, $) {
    'use strict';


        if (typeof MutationObserver === 'function') {
    function activateClbiNationsHistoryYear(panel, targetYear) {
            nationsPlacementObserver = new MutationObserver(scheduleDecorationVisibilityUpdate);
        var tabs;
            nationsPlacementObserver.observe(stack, {
         var pages;
                subtree: true,
                attributes: true,
                attributeFilter: ['class', 'hidden', 'aria-selected', 'data-current-era', 'data-nations-current-era', 'data-era-year']
            });
         }
    }


    function getPreparedRegistrySync() {
         if (!panel || !targetYear) return false;
        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() {
         tabs = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-year-button[data-year]'));
        var url;
         pages = Array.prototype.slice.call(panel.querySelectorAll('.clbi-nations-history-page[data-year-panel]'));
         var prepared = getPreparedRegistrySync();
 
         if (prepared) return Promise.resolve(prepared);
         if (!tabs.length || !pages.length) return false;
         if (!mw || !mw.util || typeof fetch !== 'function') return Promise.resolve({ decorations: [] });
 
        url = mw.util.getUrl(REGISTRY_TITLE, {
        tabs.forEach(function (tab) {
             action: 'raw',
            var active = tab.getAttribute('data-year') === targetYear;
             ctype: 'application/json'
            tab.classList.toggle('is-active', active);
             tab.setAttribute('aria-selected', active ? 'true' : 'false');
             tab.setAttribute('tabindex', active ? '0' : '-1');
         });
         });
        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() {
        pages.forEach(function (page) {
        var token;
            var active = page.getAttribute('data-year-panel') === targetYear;
        runtimeToken += 1;
            page.classList.toggle('is-active', active);
        token = runtimeToken;
 
        return fetchRegistry().then(function (registry) {
             if (active) {
             return preloadPixelAssetsForRegistry(registry).then(function () {
                page.removeAttribute('hidden');
                 if (token === runtimeToken) render(registry);
            } else {
                return registry;
                 page.setAttribute('hidden', 'hidden');
             });
             }
         });
         });
        return true;
     }
     }


     document.addEventListener('click', function (event) {
    function moveClbiNationsHistoryYear(panel, direction) {
         var target = event.target && event.target.closest ? event.target.closest('.clbi-nations-tabpanel-tab[data-continent], [data-nations-era-move]') : null;
        var tabs;
         if (target) window.setTimeout(scheduleDecorationVisibilityUpdate, 0);
        var activeIndex;
     }, true);
        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() {
     function decorationDiagnostics() {
         return {
         return {
             build: '20260708-boot-skip-preview-and-manager-save-001',
             build: '20260713-main-body-well-coordinate-003',
             hasRegistry: !!lastRegistry,
             hasRegistry: !!lastRegistry,
             entries: decorationList(lastRegistry).length,
             entries: decorationList(lastRegistry).length,
             rendered: document.querySelectorAll('[' + RENDERED_ATTR + '="1"]').length,
             rendered: document.querySelectorAll('[' + RENDERED_ATTR + '="1"]').length,
             preparedRegistry: !!getPreparedRegistrySync(),
             preparedRegistry: !!getPreparedRegistrySync(),
             pixelAssets: Object.keys(pixelAssetCache || {}).length,
             pixelAssets: Object.keys(pixelAssetCache || {}).length,
             pixelCanvases: Object.keys(pixelCanvasCache || {}).length,
             pixelCanvases: Object.keys(pixelCanvasCache || {}).length,
             visibilityOnlySync: true,
             visibilityOnlySync: true,
             lastRenderedPage: lastRenderedPageKey,
            mainPageCoordinateSurface: MAIN_PAGE_TARGET,
             visibleRendered: document.querySelectorAll('[' + RENDERED_ATTR + '="1"][data-decoration-visible="1"]').length,
            mainPagePlacementObserved: !!observedMainPagePortal,
             scheduled: !!scheduledRender
             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 = window.Decorations || {};
     window.Decorations.renderPrepared = renderPrepared;
     window.Decorations.reload = reload;
     window.Decorations.sync = syncDecorationState;
     window.Decorations.render = render;
     window.Decorations.updateVisibility = updateDecorationVisibility;
     window.Decorations.renderPrepared = renderPrepared;
     window.Decorations.diagnostics = decorationDiagnostics;
     window.Decorations.sync = syncDecorationState;
     window.Decorations.clear = clearRendered;
     window.Decorations.updateVisibility = updateDecorationVisibility;
     window.Decorations.apply = applyDecoration;
     window.Decorations.diagnostics = decorationDiagnostics;
     window.Decorations.pageKey = currentPageKey;
     window.Decorations.clear = clearRendered;
     window.Decorations.loadPixelAsset = fetchPixelAsset;
     window.Decorations.apply = applyDecoration;
     window.Decorations.preparePixelCanvas = preparePixelCanvas;
     window.Decorations.pageKey = currentPageKey;
     window.Decorations.getPreparedPixelCanvasSync = getPreparedPixelCanvasSync;
     window.Decorations.loadPixelAsset = fetchPixelAsset;
     window.Decorations.drawPixelAssetToCanvas = drawPixelAssetToCanvas;
     window.Decorations.preparePixelCanvas = preparePixelCanvas;
 
     window.Decorations.getPreparedPixelCanvasSync = getPreparedPixelCanvasSync;
     window.CLBI_DECORATIONS = window.CLBI_DECORATIONS || {};
     window.Decorations.drawPixelAssetToCanvas = drawPixelAssetToCanvas;
     window.CLBI_DECORATIONS.reload = reload;
 
     window.CLBI_DECORATIONS.render = render;
     window.CLBI_DECORATIONS = window.CLBI_DECORATIONS || {};
     window.CLBI_DECORATIONS.renderPrepared = renderPrepared;
     window.CLBI_DECORATIONS.reload = reload;
     window.CLBI_DECORATIONS.sync = syncDecorationState;
     window.CLBI_DECORATIONS.render = render;
     window.CLBI_DECORATIONS.updateVisibility = updateDecorationVisibility;
     window.CLBI_DECORATIONS.renderPrepared = renderPrepared;
     window.CLBI_DECORATIONS.diagnostics = decorationDiagnostics;
     window.CLBI_DECORATIONS.sync = syncDecorationState;
     window.CLBI_DECORATIONS.clear = clearRendered;
     window.CLBI_DECORATIONS.updateVisibility = updateDecorationVisibility;
     window.CLBI_DECORATIONS.apply = applyDecoration;
     window.CLBI_DECORATIONS.diagnostics = decorationDiagnostics;
     window.CLBI_DECORATIONS.pageKey = currentPageKey;
     window.CLBI_DECORATIONS.clear = clearRendered;
     window.CLBI_DECORATIONS.loadPixelAsset = fetchPixelAsset;
     window.CLBI_DECORATIONS.apply = applyDecoration;
     window.CLBI_DECORATIONS.preparePixelCanvas = preparePixelCanvas;
     window.CLBI_DECORATIONS.pageKey = currentPageKey;
     window.CLBI_DECORATIONS.getPreparedPixelCanvasSync = getPreparedPixelCanvasSync;
     window.CLBI_DECORATIONS.loadPixelAsset = fetchPixelAsset;
     window.CLBI_DECORATIONS.drawPixelAssetToCanvas = drawPixelAssetToCanvas;
     window.CLBI_DECORATIONS.preparePixelCanvas = preparePixelCanvas;
 
     window.CLBI_DECORATIONS.getPreparedPixelCanvasSync = getPreparedPixelCanvasSync;
     if (document.readyState === 'loading') {
     window.CLBI_DECORATIONS.drawPixelAssetToCanvas = drawPixelAssetToCanvas;
         document.addEventListener('DOMContentLoaded', reload);
 
     } else {
     if (document.readyState === 'loading') {
         reload();
         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' };
        }
    };


     if (mw && mw.hook) {
     window.MainPageManifesto = window.MainPageManifesto || {};
        mw.hook('wikipage.content').add(function () {
     window.MainPageManifesto.recalculate = recalculate;
            reload();
})(window, document, window.mw);
        });
    }
})(mediaWiki);
 
/* =========================================
  Unified Shortcuts loader
  ========================================= */
(function () {
    'use strict';
 
    if (!window.mw || !mw.loader) return;
     loadClbiRawScript('MediaWiki:Nation_List_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);