auto-champion-select 1.11.2 → 1.11.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +17 -17
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -4,16 +4,16 @@
|
|
|
4
4
|
* @name auto-champion-select
|
|
5
5
|
* @link https://github.com/controlado/auto-champion-select#readme
|
|
6
6
|
* @description Pick or ban automatically! 🐧
|
|
7
|
-
* @version 1.11.
|
|
7
|
+
* @version 1.11.4
|
|
8
8
|
* @license GPL-3.0-or-later
|
|
9
9
|
*/
|
|
10
|
-
import{request as O,sleep as v,linkEndpoint as Et}from"https://cdn.jsdelivr.net/npm/balaclava-utils@latest";const Ee="1.11.2",Oe={enabled:!1,hideAutoAcceptPrompt:!0},we={minMs:2e3,maxMs:4e3},Te={enabled:!1,force:!1,pickIntent:!0,respectManualPick:!1,champions:[432,235],randomAssignedPositions:[],randomPoolPositions:[],positionsByChampionId:{235:["BOTTOM","UTILITY"],432:["UTILITY"]}},ke={enabled:!1,force:!1,champions:[157,777,238,38],randomPoolPositions:[]},Ie={controladoAutoAccept:Oe,controladoActionDelay:we,controladoPick:Te,controladoBan:ke},Zt=0,te=8e3,at=100,rt=2e3,Le=4e3;function ct(o,t){const e=Number(o),n=Number.isFinite(t)?t:rt;if(!Number.isFinite(e))return ct(n,rt);const i=Math.round(e/at)*at;return Math.max(Zt,Math.min(te,i))}function z(o,t,e=rt,n=Le){const i=ct(o,e),s=ct(t,n);return{minMs:Math.min(i,s),maxMs:Math.max(i,s)}}function _e(o){const{minMs:t,maxMs:e}=z(o.minMs,o.maxMs),n=e-t;return t+Math.floor(Math.random()*(n+1))}function U(o){const t=o/1e3;return`${Number.isInteger(t)?t.toFixed(0):t.toFixed(1)}s`}function m(o){const t=Number(o);return Number.isSafeInteger(t)&&t>0?t:null}function ve(o,t=null){const e=[],n=new Set,i=Re(t);if(!Array.isArray(o))return e;for(const s of o){const a=m(s);a===null||n.has(a)||i&&!i.has(a)||(e.push(a),n.add(a))}return e}function Re(o){return o?new Set(Array.from(o,m).filter(t=>t!==null)):null}const D=[{value:"TOP",label:"Top",iconPath:"/fe/lol-parties/icon-position-top.png"},{value:"JUNGLE",label:"Jungle",iconPath:"/fe/lol-parties/icon-position-jungle.png"},{value:"MIDDLE",label:"Mid",iconPath:"/fe/lol-parties/icon-position-middle.png"},{value:"BOTTOM",label:"ADC",iconPath:"/fe/lol-parties/icon-position-bottom.png"},{value:"UTILITY",label:"Support",iconPath:"/fe/lol-parties/icon-position-utility.png"}],Me=new Set(D.map(o=>o.value));function x(o){const t=String(o??"").toUpperCase();return Me.has(t)?t:null}function T(o){if(!Array.isArray(o))return[];const t=new Set;for(const e of o){const n=x(e);n&&t.add(n)}return D.map(e=>e.value).filter(e=>t.has(e))}function W(o,t=null){const e={};if(!o||typeof o!="object"||Array.isArray(o))return e;const n=Ne(t);for(const[i,s]of Object.entries(o)){const a=m(i);if(a===null||!Array.isArray(s))continue;const r=String(a);if(n&&!n.has(r))continue;const l=[],u=new Set;for(const A of s){const V=x(A);!V||u.has(V)||(l.push(V),u.add(V))}l.length>0&&(e[r]=l)}return e}function Ne(o){if(!o)return null;const t=new Set;for(const e of o){const n=m(e);n!==null&&t.add(String(n))}return t}function ee(o){return D.find(t=>t.value===o)}function ne(o,t){var n;const e=m(t);return e===null?[]:((n=o==null?void 0:o.positionsByChampionId)==null?void 0:n[String(e)])||[]}function Be(o,t,e){const n=ne(o,t);if(n.length===0)return!0;const i=x(e);return i!==null&&n.includes(i)}const E="random",L="bravery";function P(o){return o===E}function k(o){return o===L}function M(o){return P(o)?E:k(o)?L:m(o)}function I(o){const t=M(o);return t===null?null:String(t)}function gt(o,t=null){const e=[],n=new Set,i=De(t);if(!Array.isArray(o))return e;for(const s of o){const a=M(s);if(a===null)continue;const r=String(a);n.has(r)||typeof a=="number"&&i&&!i.has(a)||(e.push(a),n.add(r))}return e}function $(o){return o?Array.from(o,m).filter(t=>t!==null):[]}function De(o){return o?new Set(Array.from(o,m).filter(t=>t!==null)):null}const Ot=new Set;function oe(o,t){return Object.prototype.hasOwnProperty.call(o,t)}function C(o,t){return oe(o,t)}function xe(o){return Array.isArray(o.priorityOptions)?o.priorityOptions:o.champions}function Fe(o,t){return oe(o,"randomPoolPositions")?o.randomPoolPositions:t.randomPositions}function ft(){if(!DataStore)throw new Error("DataStore is not available");return DataStore}function $e(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}function yt(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function ie(o){const t=Ie[o];if(!t)throw new Error(`Unknown auto-champion-select config key: ${o}`);return yt(t)}function se(o,t,e={}){const n=ie(o),i=$e(t)?yt(t):{},s={...n,...i},a={};if(C(n,"enabled")&&(a.enabled=s.enabled===!0),C(n,"hideAutoAcceptPrompt")&&(a.hideAutoAcceptPrompt=s.hideAutoAcceptPrompt===!0),C(n,"minMs")&&C(n,"maxMs")){const{minMs:r,maxMs:l}=z(s.minMs,s.maxMs,n.minMs,n.maxMs);a.minMs=r,a.maxMs=l}return C(n,"force")&&(a.force=s.force===!0),C(n,"pickIntent")&&(a.pickIntent=s.pickIntent!==!1),C(n,"respectManualPick")&&(a.respectManualPick=s.respectManualPick===!0),C(n,"champions")&&(a.priorityOptions=gt(xe(s),e.allowedChampionIds),a.champions=$(a.priorityOptions)),C(n,"randomAssignedPositions")&&(a.randomAssignedPositions=T(s.randomAssignedPositions)),C(n,"randomPoolPositions")&&(a.randomPoolPositions=T(Fe(i,s))),C(n,"positionsByChampionId")&&(a.positionsByChampionId=W(s.positionsByChampionId,e.selectedChampionIds||a.champions)),a}function ae(o,t,e={}){const n=t===void 0?ie(o):t;return se(o,n,e)}function y(o,t={}){const n=ft().get(o);return ae(o,n,t)}function He(o,t,e={}){const n=ft(),i=se(o,t,e);return n.set(o,i),i}function ze(o,t){return JSON.stringify(o)===JSON.stringify(t)}function Ve(o,t,e){Ot.has(o)||(Ot.add(o),console.warn(`auto-champion-select: Repaired ${o} in DataStore. The stored value used a different schema; plugins like reynbow/auto-champ-lock write this shape. Saved normalized config.`,{storedConfig:t,normalizedConfig:e}))}function re(o,t={}){const e=ft(),n=e.get(o),i=ae(o,n,t);return(n===void 0||!ze(n,i))&&(n!==void 0&&Ve(o,n,i),e.set(o,i)),i}function R(o,t,e={}){const n=y(o,e),i=yt(n),s=t(i)||i;return He(o,s,e)}const f=Object.freeze({readyCheckAccept:"/lol-matchmaking/v1/ready-check/accept",regionLocale:"/riotclient/region-locale",gameflowPhase:"/lol-gameflow/v1/gameflow-phase",wallet:"/lol-inventory/v1/wallet",ownedChampions:"/lol-champions/v1/owned-champions-minimal",championSummary:"/lol-game-data/assets/v1/champion-summary.json",recommendedChampionPositions:"/lol-perks/v1/recommended-champion-positions",champSelectSession:"/lol-champ-select/v1/session",pickableChampionIds:"/lol-champ-select/v1/pickable-champion-ids",bannableChampionIds:"/lol-champ-select/v1/bannable-champion-ids",championIcon(o){return`/lol-game-data/assets/v1/champion-icons/${o}.png`},champSelectAction(o){return`/lol-champ-select/v1/session/actions/${o}`}}),Ue=1e3;function Pt(o){let t=null;return function(){return t||(t=Promise.resolve().then(o).finally(()=>{t=null})),t}}function ce(o,t={}){const e=[],n=new Set;if(!Array.isArray(o))return e;for(const i of o){if(!i||typeof i!="object")continue;const s=m(i.id),a=typeof i.name=="string"?i.name:"";s===null||!a||n.has(a)||(e.push({...i,id:s,name:a,squarePortraitPath:i.squarePortraitPath||f.championIcon(s),recommendedPositions:t[String(s)]||[]}),n.add(a))}return e.sort((i,s)=>i.name.localeCompare(s.name)),e}function Ge(o){const t={};if(!o||typeof o!="object"||Array.isArray(o))return t;for(const[e,n]of Object.entries(o))!n||typeof n!="object"||Array.isArray(n)||(t[e]=n.recommendedPositions);return W(t)}async function Ye(){try{const o=await O("GET",f.recommendedChampionPositions);return o.ok?Ge(await o.json()):(console.warn("auto-champion-select(recommended-champion-positions): Request failed",o),{})}catch(o){return console.warn("auto-champion-select(recommended-champion-positions): Failed to load",o),{}}}const X=Pt(Ye);async function qe(){let o=await O("GET",f.ownedChampions);for(;!o.ok;)console.debug("auto-champion-select(owned-champions-minimal): Retrying..."),o=await O("GET",f.ownedChampions),await v(Ue);return ce(await o.json(),await X())}async function je(){const[o,t]=await Promise.all([O("GET",f.championSummary),X()]);return ce(await o.json(),t)}const Ke=Pt(qe),le=Pt(je),wt=300,We=-1,H=-3,b=Object.freeze({SATISFIED:"satisfied",TRY_NEXT_CHAMPION:"try-next-champion",STOP_CYCLE:"stop-cycle"}),N=Object.freeze({CONTINUE:"continue-cycle",STOP:"stop-cycle"}),h=Object.freeze({READY:"ready",SKIP_ACTION:"skip-action",STOP_CYCLE:"stop-cycle"}),S=Object.freeze({SATISFIED:"satisfied",TRY_NEXT_PRIORITY_OPTION:"try-next-priority-option",STOP_CYCLE:"stop-cycle"});function lt(o){return Array.isArray(o)?o.flat():[]}function Xe(o){return lt(o).filter(t=>t.type==="ban"&&t.completed===!0).map(t=>t.championId)}function Tt(o){return Array.isArray(o)?o:[]}function G(o){const t=new Set;for(const e of o){const n=m(e);n!==null&&t.add(n)}return t}function kt(o){return o.type==="pick"?0:1}function It(){return{pickConfig:y("controladoPick"),banConfig:y("controladoBan"),actionDelayConfig:y("controladoActionDelay")}}function Je(o){const t=[...o];for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}function Qe(o){return Array.isArray(o)&&o.length===1&&o[0]===We}function Y(o){return Number(o)===H}class Ze{constructor(){this.session=null,this.actions=null,this.localPlayerCellId=null,this.alliedIntentChampionIds=new Set,this.teammateIntentChampionIds=new Set,this.localPlayerIntentChampionId=null,this.localPlayerIntentIsBravery=!1,this.pickedChampionIds=new Set,this.bannedChampionIds=new Set,this.localPlayerAssignedPosition=null,this.rejectedBraveryActionIds=new Set,this.pluginPickSelectionId=null,this.manualPickBlocked=!1,this.watchTask=null,this.watchVersion=0,this.mounted=!1}mount(){this.mounted||(this.mounted=!0,this.rejectedBraveryActionIds.clear(),this.resetPickTracking(),this.watchVersion+=1,this.watchTask||(this.watchTask=this.watch()))}unmount(){this.mounted&&(this.mounted=!1,this.rejectedBraveryActionIds.clear(),this.resetPickTracking(),this.watchVersion+=1)}async watch(){try{for(;this.mounted;){const t=this.watchVersion;let e=!1;try{await this.refreshSessionState(),e=!0}catch(n){console.debug("auto-champion-select: Failed to update champion select",n)}if(!e||!this.mounted||t!==this.watchVersion){this.mounted&&t===this.watchVersion&&await v(wt);continue}try{await this.runAutoSelectCycle()}catch(n){console.debug("auto-champion-select: Failed to run champion select cycle",n)}this.mounted&&t===this.watchVersion&&await v(wt)}}finally{this.watchTask=null}}async refreshSessionState(){var a,r;const t=await O("GET",f.champSelectSession);if(!t.ok)throw new Error(`Session request failed with status ${t.status}`);this.session=await t.json(),this.actions=this.session.actions,this.localPlayerCellId=this.session.localPlayerCellId;const e=Tt(this.session.myTeam),n=Tt(this.session.theirTeam),i=e.find(l=>l.cellId===this.localPlayerCellId),s=e.filter(l=>l.cellId!==this.localPlayerCellId);this.localPlayerAssignedPosition=x(i==null?void 0:i.assignedPosition),this.localPlayerIntentChampionId=m(i==null?void 0:i.championPickIntent),this.localPlayerIntentIsBravery=Y(i==null?void 0:i.championPickIntent),this.pickedChampionIds=G([...e,...n].map(l=>l.championId)),this.bannedChampionIds=G([...((a=this.session.bans)==null?void 0:a.myTeamBans)||[],...((r=this.session.bans)==null?void 0:r.theirTeamBans)||[],...Xe(this.actions)]),this.alliedIntentChampionIds=G(e.map(l=>l.championPickIntent)),this.teammateIntentChampionIds=G(s.map(l=>l.championPickIntent))}async runAutoSelectCycle(){const t=It();if(!t.pickConfig.enabled&&!t.banConfig.enabled)return;const e=this.getLocalPlayerActions();if(e.length===0){console.debug("auto-champion-select: No local player sub actions found, skipping..."),this.unmount();return}for(const n of e)if(await this.runAutoSelectForAction(n,t)===N.STOP)return}async runAutoSelectForAction(t,e){const n=await this.prepareActionForAutoSelect(t,e);switch(n.status){case h.READY:return this.tryAutoSelectPlan(n.plan);case h.SKIP_ACTION:return N.CONTINUE;case h.STOP_CYCLE:return N.STOP;default:throw new Error(`Unexpected auto-select plan status: ${n.status}`)}}async prepareActionForAutoSelect(t,e){const n=this.getConfigForActionType(t.type,e);if(!(n!=null&&n.enabled))return{status:h.SKIP_ACTION};if(!this.isActionAvailable(t,n))return{status:h.SKIP_ACTION};if(this.shouldSkipPickForManualSelection(t,n))return{status:h.SKIP_ACTION};const i=this.createAutoSelectPlan(t,n);if(!i)return{status:h.SKIP_ACTION};const s=this.createPlanLimitedToAlreadySatisfiedPriorityOption(i);if(s)return{status:h.READY,plan:s};const a=await this.delayAndRefreshAutoSelectPlan(t,n,e.actionDelayConfig);return a.status!==h.READY?a:{status:h.READY,plan:this.createPlanLimitedToAlreadySatisfiedPriorityOption(a.plan)||a.plan}}async tryAutoSelectPlan(t){for(const e of t.priorityOptions){const n=await this.tryPriorityOptionForAction(t.action,e,t.config);if(n===S.SATISFIED)return N.CONTINUE;if(n===S.STOP_CYCLE)return N.STOP}return N.CONTINUE}async tryPriorityOptionForAction(t,e,n){if(this.isPriorityOptionAlreadySatisfied(t,e))return S.SATISFIED;if(k(e))return this.tryBraveryForAction(t,n);const i=await this.resolveChampionIdsForPriorityOption(t,e,n),s=P(e)&&!this.isLockingExistingPickIntent(t,i);for(const a of i){const r={tryNextRandomCandidateOnFailure:s},l=await this.attemptChampionForAction(t,a,n,r);if(l===b.SATISFIED)return S.SATISFIED;if(l===b.STOP_CYCLE)return S.STOP_CYCLE}return S.TRY_NEXT_PRIORITY_OPTION}async tryBraveryForAction(t,e){if(t.type!=="pick")return S.TRY_NEXT_PRIORITY_OPTION;if(this.isBraveryPickIntentSet(t))return S.SATISFIED;console.debug("auto-champion-select: Trying to pick Bravery...");const n=await this.selectChampion(t.id,H);console.debug(n.ok?"auto-champion-select: Bravery request accepted, refreshing champ select state...":"auto-champion-select: Failed to pick Bravery, refreshing champ select state..."),n.ok&&(this.pluginPickSelectionId=H);const i=await this.refreshPendingAction(t);return!i||!this.isActionAvailable(i,e)?n.ok?S.SATISFIED:S.STOP_CYCLE:this.isBraveryPickIntentSet(i)?S.SATISFIED:(this.pluginPickSelectionId=null,this.rejectedBraveryActionIds.add(t.id),console.debug("auto-champion-select: Bravery was not applied after refresh, trying next pick..."),S.TRY_NEXT_PRIORITY_OPTION)}getLocalPlayerActions(){return lt(this.actions).filter(t=>this.isPendingLocalPlayerAction(t)).sort((t,e)=>kt(t)-kt(e))}isPendingLocalPlayerAction(t){return t.actorCellId===this.localPlayerCellId&&t.completed===!1}isActionAvailable(t,e){return t.type==="pick"?t.isInProgress===!0||e.pickIntent!==!1:t.isInProgress===!0}getConfigForActionType(t,e){return t==="pick"?e.pickConfig:t==="ban"?e.banConfig:null}createAutoSelectPlan(t,e){const n=this.getAvailablePriorityOptionsForAction(t,e);return n.length===0?null:{action:t,config:e,priorityOptions:n}}getAvailablePriorityOptionsForAction(t,e){return gt(e.priorityOptions||e.champions).filter(n=>!this.isPriorityOptionUnavailableForAction(t,n,e))}isPriorityOptionUnavailableForAction(t,e,n){return P(e)?this.isRandomPriorityOptionUnavailableForAction(t,n):k(e)?t.type!=="pick"||this.rejectedBraveryActionIds.has(t.id):this.isChampionUnavailableForAction(t,e,n)}isRandomPriorityOptionUnavailableForAction(t,e){if(t.type!=="pick")return!1;const n=T(e.randomAssignedPositions);return n.length===0?!1:this.localPlayerAssignedPosition?n.includes(this.localPlayerAssignedPosition)?!1:(console.debug(`auto-champion-select: Skipping random pick because assigned position ${this.localPlayerAssignedPosition} is not in ${n.join(", ")}.`),!0):(console.debug(`auto-champion-select: Skipping random pick because no assigned position is available for ${n.join(", ")} restriction.`),!0)}createPlanLimitedToAlreadySatisfiedPriorityOption(t){const e=t.priorityOptions.find(n=>this.isPriorityOptionAlreadySatisfied(t.action,n));return e===void 0?null:{...t,priorityOptions:[e]}}isPriorityOptionAlreadySatisfied(t,e){return P(e)?this.hasAnyPickIntentSet(t):k(e)?this.isBraveryPickIntentSet(t):this.isPickIntentSetToChampion(t,e)}hasAnyPickIntentSet(t){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentChampionId!==null||this.localPlayerIntentIsBravery||m(t.championId)!==null||Y(t.championId))}isBraveryPickIntentSet(t){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentIsBravery||Y(t.championId))}isLockingExistingPickIntent(t,e){return t.type==="pick"&&t.isInProgress===!0&&e.length===1&&e[0]===this.getPickIntentChampionId(t)}getPickIntentChampionId(t){return t.type!=="pick"?null:m(t.championId)??this.localPlayerIntentChampionId}getCurrentLocalPickOrIntentSelectionId(t){if(t.type!=="pick")return null;const e=m(t.championId);return e!==null?e:Y(t.championId)?H:this.localPlayerIntentChampionId!==null?this.localPlayerIntentChampionId:this.localPlayerIntentIsBravery?H:null}shouldSkipPickForManualSelection(t,e){if(t.type!=="pick"||e.respectManualPick!==!0)return!1;if(this.manualPickBlocked)return!0;const n=this.getCurrentLocalPickOrIntentSelectionId(t);return n===null||this.pluginPickSelectionId===n?!1:(this.manualPickBlocked=!0,console.debug(`auto-champion-select: Skipping pick action ${t.id} because manual pick ${n} was detected.`),!0)}resetPickTracking(){this.pluginPickSelectionId=null,this.manualPickBlocked=!1}async delayAndRefreshAutoSelectPlan(t,e,n){const i=_e(n);if(i<=0){console.debug(`auto-champion-select: Action delay is instant for ${t.type}.`);const u=this.createAutoSelectPlan(t,e);return u?{status:h.READY,plan:u}:{status:h.STOP_CYCLE}}console.debug(`auto-champion-select: Waiting ${i}ms before ${t.type}...`);const s=this.watchVersion;if(await v(i),!this.mounted||s!==this.watchVersion)return{status:h.STOP_CYCLE};let a=null;try{await this.refreshSessionState(),a=this.findPendingAction(t)}catch(u){return console.debug("auto-champion-select: Failed to refresh champion select after action delay",u),{status:h.STOP_CYCLE}}const r=this.getConfigForActionType(t.type,It());if(!(r!=null&&r.enabled))return{status:h.STOP_CYCLE};if(!a||!this.isActionAvailable(a,r))return{status:h.STOP_CYCLE};if(this.shouldSkipPickForManualSelection(a,r))return{status:h.SKIP_ACTION};const l=this.createAutoSelectPlan(a,r);return l?{status:h.READY,plan:l}:{status:h.STOP_CYCLE}}async resolveChampionIdsForPriorityOption(t,e,n){return k(e)?[]:P(e)?this.resolveRandomChampionIdsForAction(t,n):[e]}async resolveRandomChampionIdsForAction(t,e){if(t.type==="pick"&&t.isInProgress===!0){const a=this.getPickIntentChampionId(t);if(a!==null&&!this.isChampionUnavailableForAction(t,a,e))return[a]}const n=await this.fetchRandomCandidateChampionIds(t);if(n.length===0)return[];const i=n.filter(a=>!this.isChampionUnavailableForAction(t,a,e)),s=t.type==="pick"&&!this.hasConfiguredRandomPoolPositions(e)?await this.preferAssignedPositionRandomPickCandidates(i):await this.filterRandomChampionIdsByConfiguredPoolPositions(i,e);return Je(s)}async fetchRandomCandidateChampionIds(t){const e=t.type==="pick"?f.pickableChampionIds:f.bannableChampionIds;try{const n=await O("GET",e);if(!n.ok)return console.debug(`auto-champion-select: Failed to load random ${t.type} candidates`,n),[];const i=await n.json();return t.type==="ban"&&Qe(i)?(console.debug("auto-champion-select: Random ban endpoint returned unrestricted sentinel, falling back to all champions..."),await this.fetchAllChampionIdsForRandomBan()):ve(i)}catch(n){return console.debug(`auto-champion-select: Failed to load random ${t.type} candidates`,n),[]}}async fetchAllChampionIdsForRandomBan(){return(await le()).map(e=>e.id)}hasConfiguredRandomPoolPositions(t){return T(t.randomPoolPositions).length>0}async filterRandomChampionIdsByConfiguredPoolPositions(t,e){const n=T(e.randomPoolPositions);if(n.length===0)return t;const i=new Set(n),s=await X(),a=t.filter(r=>{var l;return(l=s[String(r)])==null?void 0:l.some(u=>i.has(u))});return a.length===0&&console.debug(`auto-champion-select: No random candidates matched ${n.join(", ")} restriction.`),a}async preferAssignedPositionRandomPickCandidates(t){if(!this.localPlayerAssignedPosition)return t;const e=await X(),n=t.filter(i=>{var s;return(s=e[String(i)])==null?void 0:s.includes(this.localPlayerAssignedPosition)});return n.length>0?n:t}async attemptChampionForAction(t,e,n,i={}){const s=m(e);if(s===null||this.isChampionUnavailableForAction(t,s,n))return b.TRY_NEXT_CHAMPION;if(this.isPickIntentSetToChampion(t,s))return b.SATISFIED;if(console.debug(`auto-champion-select: Trying to ${t.type} ${s}...`),(await this.selectChampion(t.id,s)).ok)return t.type==="pick"&&(this.pluginPickSelectionId=s),b.SATISFIED;console.debug(`auto-champion-select: Failed to ${t.type} ${s}, refreshing champ select state...`);const r=await this.refreshPendingAction(t);return!r||!this.isActionAvailable(r,n)?b.STOP_CYCLE:i.tryNextRandomCandidateOnFailure===!0?this.hasAnyPickIntentSet(r)?b.SATISFIED:(console.debug(`auto-champion-select: Failed random ${t.type} candidate ${s}, trying next ${t.type}...`),b.TRY_NEXT_CHAMPION):this.isChampionUnavailableForAction(r,s,n)?(console.debug(`auto-champion-select: ${s} is unavailable after refresh, trying next ${t.type}...`),b.TRY_NEXT_CHAMPION):b.STOP_CYCLE}isPickIntentSetToChampion(t,e){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentChampionId===e||m(t.championId)===e)}async refreshPendingAction(t){try{await this.refreshSessionState()}catch(e){return console.debug("auto-champion-select: Failed to refresh champion select action",e),null}return this.findPendingAction(t)}findPendingAction(t){return lt(this.actions).find(e=>e.id===t.id&&e.actorCellId===t.actorCellId&&e.type===t.type&&e.completed===!1)||null}isChampionUnavailableForAction(t,e,n){if(t.type==="pick"&&!Be(n,e,this.localPlayerAssignedPosition)){const i=ne(n,e);return this.localPlayerAssignedPosition?console.debug(`auto-champion-select: Picking ${e} but assigned position ${this.localPlayerAssignedPosition} is not in ${i.join(", ")}, skipping...`):console.debug(`auto-champion-select: Picking ${e} but no assigned position is available for ${i.join(", ")} restriction, skipping...`),!0}if(this.bannedChampionIds.has(e))return console.debug(`auto-champion-select: Banning ${e} but it's already banned, skipping...`),!0;if(t.type==="ban"&&this.alliedIntentChampionIds.has(e))if(n.force===!0)console.debug(`auto-champion-select: Banning ${e} but it has an allied pick intent, forcing...`);else return console.debug(`auto-champion-select: Banning ${e} but it has an allied pick intent, skipping...`),!0;if(t.type==="pick"&&this.teammateIntentChampionIds.has(e))if(n.force===!0)console.debug(`auto-champion-select: Picking ${e} but it has a teammate pick intent, forcing...`);else return console.debug(`auto-champion-select: Picking ${e} but it has a teammate pick intent, skipping...`),!0;return t.type==="pick"&&this.pickedChampionIds.has(e)?(console.debug(`auto-champion-select: Picking ${e} but it's already picked, skipping...`),!0):!1}selectChampion(t,e){const n=f.champSelectAction(t);return O("PATCH",n,{body:{championId:e,completed:!0}})}}const tn={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},en={autoAccept:"Accept",pick:"Pick",ban:"Ban"},nn={on:"ON",off:"OFF"},on={pick:"Pick",ban:"Ban"},sn={TOP:"Top",JUNGLE:"Jungle",MIDDLE:"Mid",BOTTOM:"ADC",UTILITY:"Support"},an={two:"{first} or {second}",many:"{items}, or {last}"},rn={pickPlaceholder:"Add pick",banPlaceholder:"Add ban",search:"Search",emptyTitle:"No champions",pickEmptyHint:"Use the menu to add a pick",banEmptyHint:"Use the menu to add a ban",remove:"Remove {name}",positionFilterLabel:"Filter champions by position",random:{label:"Random",assignedTitlePart:"runs only when assigned role matches {positions}",poolTitlePart:"limits Random pool to {positions}"},bravery:{label:"Bravery",description:"For Arena mode"},positionBadge:{randomAssignedAny:"The plugin can use Random in any role. Click to run it only in selected draft roles.",randomAssignedSome:"The plugin will use Random only when your assigned role matches {positions}. Draft modes only. Click to edit.",randomPoolAny:"The plugin can choose any available champion at random. Click to filter the pool first.",randomPoolSome:"The plugin filters Random to champions for {positions}, then picks one. Click to edit.",championSome:"The plugin will pick this champion only when your assigned role matches {positions}. Draft modes only. Click to edit.",championAny:"The plugin can pick this champion in any role. Click to limit it to selected draft roles."}},cn={triggerLabel:"Auto champion select settings",empty:"No settings available",actionDelay:"Action delay",pickIntent:"Set pick intent",respectManualPick:"Respect manual pick",forcePick:"Ignore ally pick intent",forceBan:"Ignore ally pick intent when banning",hideAutoAcceptPrompt:"Hide auto-accept prompt",handleLabel:"{label} {handle}",handles:{min:"min",max:"max"},actionDelayValue:{instant:"Instant",exact:"Delays actions for {delay}",upTo:"Delays actions up to {delay}",range:"Delays actions {min}-{max}"}},ln={readyCheckAccepted:"Match accepted!",readyCheckAcceptFailed:"Failed to accept match. Check console."},dn={group:"Balaclava: Auto Champion Select",autoSwitchName:"Auto {name} [{state}]",turnOn:"Turn ON",turnOff:"Turn OFF",autoSwitchOn:"Auto {name} is ON!",autoSwitchOff:"Auto {name} is OFF!",autoSwitchError:"Failed to toggle Auto {name}. Check console.",forcePickName:"Ignore Team Intent Pick",forceBanName:"Ignore Team Intent Ban",forceSwitchName:"{name} [{state}]",forcePickLegend:"Pick even if a teammate intends that champion",forceBanLegend:"Ban even if a teammate intends that champion",forceSwitchOn:"{name} is ON!",forceSwitchOff:"{name} is OFF!",forceSwitchError:"Failed to toggle {name}. Check console.",refreshChampionsName:"Refresh Champions",refreshChampionsLegend:"Normally champion selectors refresh automatically...",refreshChampionsSuccess:"Refreshed Champions!",refreshChampionsError:"Failed to refresh Champions. Check console."},un={plugin:tn,toggles:en,states:nn,actions:on,positions:sn,list:an,selectors:rn,settings:cn,toasts:ln,commandBar:dn},hn={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},pn={autoAccept:"Aceptar",pick:"Pick",ban:"Ban"},mn={on:"ON",off:"OFF"},gn={pick:"Pick",ban:"Ban"},fn={TOP:"Top",JUNGLE:"Jungla",MIDDLE:"Mid",BOTTOM:"ADC",UTILITY:"Soporte"},yn={two:"{first} o {second}",many:"{items} o {last}"},Pn={pickPlaceholder:"Agregar pick",banPlaceholder:"Agregar ban",search:"Buscar",emptyTitle:"Sin campeones",pickEmptyHint:"Usa el menú para agregar",banEmptyHint:"Usa el menú para agregar",remove:"Quitar {name}",positionFilterLabel:"Filtrar campeones por posición",random:{label:"Aleatorio",assignedTitlePart:"solo si la posición asignada es {positions}",poolTitlePart:"filtra el pool a {positions}"},bravery:{label:"Valentía",description:"Para Arena"},positionBadge:{randomAssignedAny:"Aleatorio sirve en cualquier posición. Haz clic para limitar posiciones de draft.",randomAssignedSome:"Aleatorio solo si tu posición es {positions}. Solo draft; haz clic para editar.",randomPoolAny:"Aleatorio puede elegir cualquier campeón disponible. Haz clic para filtrar.",randomPoolSome:"Aleatorio elige campeones de {positions}. Haz clic para editar.",championSome:"Este campeón solo se elige si tu posición es {positions}. Solo draft; haz clic para editar.",championAny:"Este campeón sirve en cualquier posición. Haz clic para limitar posiciones."}},Sn={triggerLabel:"Ajustes de Auto Champion Select",empty:"Sin ajustes",actionDelay:"Retraso de acción",pickIntent:"Marcar intención de selección",respectManualPick:"Respetar selección manual",forcePick:"Ignorar intención aliada al pickear",forceBan:"Ignorar intención aliada al banear",hideAutoAcceptPrompt:"Ocultar confirmación de partida",handleLabel:"{label} {handle}",handles:{min:"mín",max:"máx"},actionDelayValue:{instant:"Sin retraso",exact:"Retraso de {delay}",upTo:"Hasta {delay}",range:"Retraso de {min}-{max}"}},An={readyCheckAccepted:"¡Partida aceptada!",readyCheckAcceptFailed:"No se pudo aceptar la partida. Revisa la consola."},Cn={group:"Balaclava: Auto Champion Select",autoSwitchName:"Auto {name} [{state}]",turnOn:"Activar",turnOff:"Desactivar",autoSwitchOn:"Auto {name} está ON!",autoSwitchOff:"Auto {name} está OFF!",autoSwitchError:"No se pudo cambiar Auto {name}. Revisa la consola.",forcePickName:"Ignorar intención aliada al pickear",forceBanName:"Ignorar intención aliada al banear",forceSwitchName:"{name} [{state}]",forcePickLegend:"Pickea aunque un aliado quiera el mismo campeón",forceBanLegend:"Banea aunque un aliado quiera ese campeón",forceSwitchOn:"{name} está ON!",forceSwitchOff:"{name} está OFF!",forceSwitchError:"No se pudo cambiar {name}. Revisa la consola.",refreshChampionsName:"Actualizar campeones",refreshChampionsLegend:"Normalmente los selectores se actualizan solos...",refreshChampionsSuccess:"¡Campeones actualizados!",refreshChampionsError:"No se actualizaron campeones. Revisa la consola."},bn={plugin:hn,toggles:pn,states:mn,actions:gn,positions:fn,list:yn,selectors:Pn,settings:Sn,toasts:An,commandBar:Cn},En={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},On={autoAccept:"수락",pick:"선택",ban:"밴"},wn={on:"ON",off:"OFF"},Tn={pick:"선택",ban:"밴"},kn={TOP:"탑",JUNGLE:"정글",MIDDLE:"미드",BOTTOM:"원딜",UTILITY:"서폿"},In={two:"{first} 또는 {second}",many:"{items} 또는 {last}"},Ln={pickPlaceholder:"픽 추가",banPlaceholder:"밴 추가",search:"검색",emptyTitle:"챔피언 없음",pickEmptyHint:"메뉴에서 추가",banEmptyHint:"메뉴에서 추가",remove:"{name} 제거",positionFilterLabel:"포지션별 챔피언 필터",random:{label:"랜덤",assignedTitlePart:"배정 포지션이 {positions}일 때만 실행",poolTitlePart:"랜덤 풀을 {positions}로 제한"},bravery:{label:"용기",description:"아레나용"},positionBadge:{randomAssignedAny:"랜덤은 모든 포지션에서 사용 가능. 클릭해 드래프트 포지션 제한.",randomAssignedSome:"랜덤은 배정 포지션이 {positions}일 때만 사용. 드래프트 전용; 클릭해 편집.",randomPoolAny:"랜덤은 가능한 모든 챔피언 중 선택 가능. 클릭해 풀 필터.",randomPoolSome:"랜덤은 {positions} 챔피언 중 선택. 클릭해 편집.",championSome:"이 챔피언은 배정 포지션이 {positions}일 때만 선택. 드래프트 전용; 클릭해 편집.",championAny:"이 챔피언은 모든 포지션에서 선택 가능. 클릭해 포지션 제한."}},_n={triggerLabel:"Auto Champion Select 설정",empty:"설정 없음",actionDelay:"동작 지연",pickIntent:"선택 의도 설정",respectManualPick:"수동 선택 존중",forcePick:"아군 희망 챔피언 무시하고 선택",forceBan:"아군 희망 챔피언 무시하고 밴",hideAutoAcceptPrompt:"자동 수락 알림 숨기기",handleLabel:"{label} {handle}",handles:{min:"최소",max:"최대"},actionDelayValue:{instant:"즉시",exact:"{delay} 지연",upTo:"{delay}까지 지연",range:"{min}-{max} 지연"}},vn={readyCheckAccepted:"게임 수락됨!",readyCheckAcceptFailed:"게임 수락 실패. 콘솔 확인."},Rn={group:"Balaclava: Auto Champion Select",autoSwitchName:"자동 {name} [{state}]",turnOn:"켜기",turnOff:"끄기",autoSwitchOn:"자동 {name} 켜짐!",autoSwitchOff:"자동 {name} 꺼짐!",autoSwitchError:"자동 {name} 전환 실패. 콘솔 확인.",forcePickName:"희망 챔피언 무시 선택",forceBanName:"희망 챔피언 무시 밴",forceSwitchName:"{name} [{state}]",forcePickLegend:"팀원이 같은 챔피언을 희망해도 선택",forceBanLegend:"팀원이 같은 챔피언을 희망해도 밴",forceSwitchOn:"{name} 켜짐!",forceSwitchOff:"{name} 꺼짐!",forceSwitchError:"{name} 전환 실패. 콘솔 확인.",refreshChampionsName:"챔피언 새로고침",refreshChampionsLegend:"챔피언 목록은 보통 자동으로 새로고침됩니다...",refreshChampionsSuccess:"챔피언 새로고침 완료!",refreshChampionsError:"챔피언 새로고침 실패. 콘솔 확인."},Mn={plugin:En,toggles:On,states:wn,actions:Tn,positions:kn,list:In,selectors:Ln,settings:_n,toasts:vn,commandBar:Rn},Nn={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},Bn={autoAccept:"Aceitar",pick:"Pick",ban:"Ban"},Dn={on:"ON",off:"OFF"},xn={pick:"Pick",ban:"Ban"},Fn={TOP:"Top",JUNGLE:"Jungle",MIDDLE:"Mid",BOTTOM:"ADC",UTILITY:"Suporte"},$n={two:"{first} ou {second}",many:"{items} ou {last}"},Hn={pickPlaceholder:"Adicionar pick",banPlaceholder:"Adicionar ban",search:"Buscar",emptyTitle:"Nenhum campeão",pickEmptyHint:"Use o menu para adicionar um pick",banEmptyHint:"Use o menu para adicionar um ban",remove:"Remover {name}",positionFilterLabel:"Filtrar campeões por posição",random:{label:"Aleatório",assignedTitlePart:"só roda quando sua rota for {positions}",poolTitlePart:"limita o pool a {positions}"},bravery:{label:"Bravura",description:"Para o modo Arena"},positionBadge:{randomAssignedAny:"Aleatório pode rodar em qualquer rota. Clique para limitar às rotas do draft.",randomAssignedSome:"Aleatório só roda se sua rota for {positions}. Draft apenas. Clique para editar.",randomPoolAny:"Aleatório pode escolher qualquer campeão disponível. Clique para filtrar o pool.",randomPoolSome:"Aleatório escolhe campeões de {positions}. Clique para editar.",championSome:"Este campeão só será escolhido se sua rota for {positions}. Draft apenas. Clique para editar.",championAny:"Este campeão pode ser escolhido em qualquer rota. Clique para limitar às rotas do draft."}},zn={triggerLabel:"Configurações do Auto Champion Select",empty:"Nenhuma configuração disponível",actionDelay:"Delay de ação",pickIntent:"Marcar intenção de pick",respectManualPick:"Respeitar pick manual",forcePick:"Ignorar intenção aliada no pick",forceBan:"Ignorar intenção aliada no ban",hideAutoAcceptPrompt:"Ocultar confirmação da fila",handleLabel:"{label} {handle}",handles:{min:"mínimo",max:"máximo"},actionDelayValue:{instant:"Sem delay",exact:"Delay de {delay}",upTo:"Delay de até {delay}",range:"Delay de {min}-{max}"}},Vn={readyCheckAccepted:"Fila aceita!",readyCheckAcceptFailed:"Falha ao aceitar a fila. Verifique o console."},Un={group:"Balaclava: Auto Champion Select",autoSwitchName:"Auto {name} [{state}]",turnOn:"Ativar",turnOff:"Desativar",autoSwitchOn:"Auto {name} está ON!",autoSwitchOff:"Auto {name} está OFF!",autoSwitchError:"Falha ao alternar Auto {name}. Verifique o console.",forcePickName:"Ignorar intenção aliada no pick",forceBanName:"Ignorar intenção aliada no ban",forceSwitchName:"{name} [{state}]",forcePickLegend:"Escolhe mesmo se um aliado indicar o mesmo campeão",forceBanLegend:"Bane mesmo se um aliado indicar o campeão",forceSwitchOn:"{name} está ON!",forceSwitchOff:"{name} está OFF!",forceSwitchError:"Falha ao alternar {name}. Verifique o console.",refreshChampionsName:"Atualizar campeões",refreshChampionsLegend:"Normalmente as listas de campeões atualizam automaticamente...",refreshChampionsSuccess:"Campeões atualizados!",refreshChampionsError:"Falha ao atualizar campeões. Verifique o console."},Gn={plugin:Nn,toggles:Bn,states:Dn,actions:xn,positions:Fn,list:$n,selectors:Hn,settings:zn,toasts:Vn,commandBar:Un},Yn={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},qn={autoAccept:"Принять",pick:"Пик",ban:"Бан"},jn={on:"ON",off:"OFF"},Kn={pick:"Пик",ban:"Бан"},Wn={TOP:"Топ",JUNGLE:"Лес",MIDDLE:"Мид",BOTTOM:"Бот",UTILITY:"Саппорт"},Xn={two:"{first} или {second}",many:"{items} или {last}"},Jn={pickPlaceholder:"Добавить пик",banPlaceholder:"Добавить бан",search:"Поиск",emptyTitle:"Нет чемпионов",pickEmptyHint:"Добавьте пик через меню",banEmptyHint:"Добавьте бан через меню",remove:"Удалить {name}",positionFilterLabel:"Фильтр чемпионов по позиции",random:{label:"Случайный",assignedTitlePart:"только если позиция — {positions}",poolTitlePart:"пул: {positions}"},bravery:{label:"Храбрость",description:"Для Арены"},positionBadge:{randomAssignedAny:"Случайный выбор работает на любой позиции. Нажмите, чтобы ограничить позиции.",randomAssignedSome:"Случайный выбор только если позиция — {positions}. Только в драфте; нажмите для изменения.",randomPoolAny:"Пул: все доступные чемпионы. Нажмите, чтобы отфильтровать.",randomPoolSome:"Пул: {positions}. Нажмите для изменения.",championSome:"Чемпион выбирается только если позиция — {positions}. Только в драфте; нажмите для изменения.",championAny:"Чемпион доступен на любой позиции. Нажмите, чтобы ограничить позиции."}},Qn={triggerLabel:"Настройки Auto Champion Select",empty:"Настроек нет",actionDelay:"Задержка действий",pickIntent:"Показывать препик",respectManualPick:"Уважать ручной пик",forcePick:"Игнорировать препик при пике",forceBan:"Игнорировать препик при бане",hideAutoAcceptPrompt:"Скрывать окно принятия матча",handleLabel:"{label} {handle}",handles:{min:"мин",max:"макс"},actionDelayValue:{instant:"Без задержки",exact:"Задержка {delay}",upTo:"Задержка до {delay}",range:"Задержка {min}-{max}"}},Zn={readyCheckAccepted:"Матч принят!",readyCheckAcceptFailed:"Не удалось принять матч. Проверьте консоль."},to={group:"Balaclava: Auto Champion Select",autoSwitchName:"Авто {name} [{state}]",turnOn:"Включить",turnOff:"Выключить",autoSwitchOn:"Авто {name} включен!",autoSwitchOff:"Авто {name} выключен!",autoSwitchError:"Не удалось переключить Авто {name}. Проверьте консоль.",forcePickName:"Игнор препика при пике",forceBanName:"Игнор препика при бане",forceSwitchName:"{name} [{state}]",forcePickLegend:"Пикать, даже если союзник препикнул чемпиона",forceBanLegend:"Банить, даже если союзник препикнул чемпиона",forceSwitchOn:"Включено: {name}!",forceSwitchOff:"Выключено: {name}!",forceSwitchError:"Не удалось переключить {name}. Проверьте консоль.",refreshChampionsName:"Обновить список чемпионов",refreshChampionsLegend:"Обычно список чемпионов обновляется автоматически...",refreshChampionsSuccess:"Список чемпионов обновлен!",refreshChampionsError:"Не удалось обновить список чемпионов. Проверьте консоль."},eo={plugin:Yn,toggles:qn,states:jn,actions:Kn,positions:Wn,list:Xn,selectors:Jn,settings:Qn,toasts:Zn,commandBar:to},no={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},oo={autoAccept:"Kabul Et",pick:"Seç",ban:"Yasakla"},io={on:"ON",off:"OFF"},so={pick:"Seç",ban:"Yasakla"},ao={TOP:"Üst",JUNGLE:"Orman",MIDDLE:"Orta",BOTTOM:"Alt",UTILITY:"Destek"},ro={two:"{first} veya {second}",many:"{items} veya {last}"},co={pickPlaceholder:"Seçim ekle",banPlaceholder:"Yasaklama ekle",search:"Ara",emptyTitle:"Şampiyon yok",pickEmptyHint:"Menüden seçenek ekle",banEmptyHint:"Menüden seçenek ekle",remove:"{name} kaldır",positionFilterLabel:"Şampiyonları konuma göre filtrele",random:{label:"Rastgele",assignedTitlePart:"atanan konum {positions} ise çalışır",poolTitlePart:"rastgele havuzu {positions} ile sınırlar"},bravery:{label:"Cesaret",description:"Arena modu için"},positionBadge:{randomAssignedAny:"Rastgele her konumda kullanılabilir. Draft konumlarıyla sınırla.",randomAssignedSome:"Rastgele yalnız atanan konum {positions} ise kullanılır. Sadece draft; düzenle.",randomPoolAny:"Rastgele tüm uygun şampiyonlardan seçebilir. Havuzu filtrele.",randomPoolSome:"Rastgele, {positions} şampiyonlarından seçer. Düzenle.",championSome:"Bu şampiyon yalnız atanan konum {positions} ise seçilir. Sadece draft; düzenle.",championAny:"Bu şampiyon her konumda seçilebilir. Konumları sınırla."}},lo={triggerLabel:"Auto Champion Select ayarları",empty:"Ayar yok",actionDelay:"İşlem gecikmesi",pickIntent:"Seçim niyeti ayarla",respectManualPick:"Manuel seçimi koru",forcePick:"Seçim niyetini yok sayarak seç",forceBan:"Seçim niyetini yok sayarak yasakla",hideAutoAcceptPrompt:"Karşılaşma kabul penceresini gizle",handleLabel:"{label} {handle}",handles:{min:"min",max:"maks"},actionDelayValue:{instant:"Anında",exact:"{delay} gecikme",upTo:"{delay} kadar gecikme",range:"{min}-{max} gecikme"}},uo={readyCheckAccepted:"Karşılaşma kabul edildi!",readyCheckAcceptFailed:"Karşılaşma kabul edilemedi. Konsola bakın."},ho={group:"Balaclava: Auto Champion Select",autoSwitchName:"Oto {name} [{state}]",turnOn:"Aç",turnOff:"Kapat",autoSwitchOn:"Oto {name} açık!",autoSwitchOff:"Oto {name} kapalı!",autoSwitchError:"Oto {name} değiştirilemedi. Konsola bakın.",forcePickName:"Seçim niyetini yok sayarak seç",forceBanName:"Seçim niyetini yok sayarak yasakla",forceSwitchName:"{name} [{state}]",forcePickLegend:"Takım arkadaşı aynı şampiyonu istese de seçer",forceBanLegend:"Takım arkadaşı aynı şampiyonu istese de yasaklar",forceSwitchOn:"{name} açık!",forceSwitchOff:"{name} kapalı!",forceSwitchError:"{name} değiştirilemedi. Konsola bakın.",refreshChampionsName:"Şampiyonları yenile",refreshChampionsLegend:"Seçiciler normalde otomatik yenilenir...",refreshChampionsSuccess:"Şampiyonlar yenilendi!",refreshChampionsError:"Şampiyonlar yenilenemedi. Konsola bakın."},po={plugin:no,toggles:oo,states:io,actions:so,positions:ao,list:ro,selectors:co,settings:lo,toasts:uo,commandBar:ho},mo={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},go={autoAccept:"Chấp nhận",pick:"Chọn",ban:"Cấm"},fo={on:"ON",off:"OFF"},yo={pick:"Chọn",ban:"Cấm"},Po={TOP:"Đường trên",JUNGLE:"Rừng",MIDDLE:"Đường giữa",BOTTOM:"Đường dưới",UTILITY:"Hỗ trợ"},So={two:"{first} hoặc {second}",many:"{items} hoặc {last}"},Ao={pickPlaceholder:"Thêm tướng chọn",banPlaceholder:"Thêm tướng cấm",search:"Tìm",emptyTitle:"Không có tướng",pickEmptyHint:"Dùng menu để thêm",banEmptyHint:"Dùng menu để thêm",remove:"Xóa {name}",positionFilterLabel:"Lọc tướng theo vị trí",random:{label:"Ngẫu nhiên",assignedTitlePart:"chỉ chạy khi vị trí là {positions}",poolTitlePart:"lọc bể tướng theo {positions}"},bravery:{label:"Quả Cảm",description:"Cho chế độ Võ Đài"},positionBadge:{randomAssignedAny:"Ngẫu nhiên dùng được mọi vị trí. Bấm để giới hạn vị trí Cấm Chọn.",randomAssignedSome:"Ngẫu nhiên chỉ dùng khi vị trí là {positions}. Chỉ Cấm Chọn; bấm để sửa.",randomPoolAny:"Ngẫu nhiên có thể chọn mọi tướng hợp lệ. Bấm để lọc nhóm.",randomPoolSome:"Ngẫu nhiên chọn tướng thuộc {positions}. Bấm để sửa.",championSome:"Tướng này chỉ được chọn khi vị trí là {positions}. Chỉ Cấm Chọn; bấm để sửa.",championAny:"Tướng này dùng được mọi vị trí. Bấm để giới hạn."}},Co={triggerLabel:"Cài đặt Auto Champion Select",empty:"Không có cài đặt",actionDelay:"Độ trễ thao tác",pickIntent:"Đặt ý định chọn tướng",respectManualPick:"Tôn trọng chọn thủ công",forcePick:"Bỏ qua ý định chọn tướng",forceBan:"Bỏ qua ý định chọn khi cấm",hideAutoAcceptPrompt:"Ẩn lời nhắc chấp nhận trận",handleLabel:"{label} {handle}",handles:{min:"tối thiểu",max:"tối đa"},actionDelayValue:{instant:"Ngay",exact:"Trễ {delay}",upTo:"Tới {delay}",range:"Trễ {min}-{max}"}},bo={readyCheckAccepted:"Đã chấp nhận trận!",readyCheckAcceptFailed:"Không thể chấp nhận trận. Xem console."},Eo={group:"Balaclava: Auto Champion Select",autoSwitchName:"Tự động {name} [{state}]",turnOn:"Bật",turnOff:"Tắt",autoSwitchOn:"Tự động {name} đã bật!",autoSwitchOff:"Tự động {name} đã tắt!",autoSwitchError:"Không đổi được tự động {name}. Xem console.",forcePickName:"Bỏ qua ý định chọn tướng",forceBanName:"Bỏ qua ý định chọn khi cấm",forceSwitchName:"{name} [{state}]",forcePickLegend:"Vẫn chọn dù đồng đội cũng định chọn",forceBanLegend:"Vẫn cấm dù đồng đội định chọn",forceSwitchOn:"{name} đã bật!",forceSwitchOff:"{name} đã tắt!",forceSwitchError:"Không đổi được {name}. Xem console.",refreshChampionsName:"Làm mới tướng",refreshChampionsLegend:"Danh sách tướng thường tự làm mới...",refreshChampionsSuccess:"Đã làm mới tướng!",refreshChampionsError:"Không thể làm mới tướng. Xem console."},Lt={plugin:mo,toggles:go,states:fo,actions:yo,positions:Po,list:So,selectors:Ao,settings:Co,toasts:bo,commandBar:Eo},Oo={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},wo={autoAccept:"接受",pick:"选择",ban:"禁用"},To={on:"ON",off:"OFF"},ko={pick:"选择",ban:"禁用"},Io={TOP:"上路",JUNGLE:"打野",MIDDLE:"中路",BOTTOM:"下路",UTILITY:"辅助"},Lo={two:"{first}或{second}",many:"{items}或{last}"},_o={pickPlaceholder:"添加选用英雄",banPlaceholder:"添加禁用英雄",search:"搜索",emptyTitle:"无英雄",pickEmptyHint:"用菜单添加",banEmptyHint:"用菜单添加",remove:"移除{name}",positionFilterLabel:"按分路筛选英雄",random:{label:"随机",assignedTitlePart:"仅在分配位置为{positions}时执行",poolTitlePart:"将随机英雄池限制为{positions}"},bravery:{label:"勇敢举动",description:"用于斗魂竞技场"},positionBadge:{randomAssignedAny:"随机可用于任意位置。点击限制为选定征召位置。",randomAssignedSome:"随机仅在分配位置为{positions}时使用。仅征召;点击编辑。",randomPoolAny:"随机可从所有可用英雄中选择。点击筛选英雄池。",randomPoolSome:"随机从{positions}英雄中选择。点击编辑。",championSome:"仅当分配位置为{positions}时选择此英雄。仅征召;点击编辑。",championAny:"此英雄可用于任意位置。点击限制位置。"}},vo={triggerLabel:"Auto Champion Select 设置",empty:"无设置",actionDelay:"操作延迟",pickIntent:"设置选用意向",respectManualPick:"尊重手动选择",forcePick:"无视队友意向并选用",forceBan:"无视队友意向并禁用",hideAutoAcceptPrompt:"隐藏对局接受提示",handleLabel:"{label} {handle}",handles:{min:"最小",max:"最大"},actionDelayValue:{instant:"立即",exact:"延迟{delay}",upTo:"最多{delay}",range:"延迟{min}-{max}"}},Ro={readyCheckAccepted:"对局已接受!",readyCheckAcceptFailed:"接受对局失败。查看控制台。"},Mo={group:"Balaclava: Auto Champion Select",autoSwitchName:"自动{name} [{state}]",turnOn:"开启",turnOff:"关闭",autoSwitchOn:"自动{name}已开启!",autoSwitchOff:"自动{name}已关闭!",autoSwitchError:"切换自动{name}失败。查看控制台。",forcePickName:"无视队友意向选用",forceBanName:"无视队友意向禁用",forceSwitchName:"{name} [{state}]",forcePickLegend:"即使队友也想用该英雄也会选用",forceBanLegend:"即使队友想用该英雄也会禁用",forceSwitchOn:"{name}已开启!",forceSwitchOff:"{name}已关闭!",forceSwitchError:"切换{name}失败。查看控制台。",refreshChampionsName:"刷新英雄列表",refreshChampionsLegend:"英雄列表通常会自动刷新...",refreshChampionsSuccess:"英雄列表已刷新!",refreshChampionsError:"刷新英雄列表失败。查看控制台。"},No={plugin:Oo,toggles:wo,states:To,actions:ko,positions:Io,list:Lo,selectors:_o,settings:vo,toasts:Ro,commandBar:Mo},St="en-US",J=Object.freeze({"en-US":un,"es-MX":bn,"ko-KR":Mn,"pt-BR":Gn,"ru-RU":eo,"tr-TR":po,"vi-VN":Lt,"vn-VN":Lt,"zh-CN":No});let dt=St,de=!1;function Bo(){var o,t,e;return typeof document<"u"?((t=(o=document.body)==null?void 0:o.dataset)==null?void 0:t.locale)||((e=document.documentElement)==null?void 0:e.lang)||"":typeof navigator<"u"&&navigator.language||""}async function Do(){try{const o=await O("GET",f.regionLocale);if(!o.ok)return"";const t=await o.json();return typeof(t==null?void 0:t.locale)=="string"?t.locale:""}catch{return""}}function xo(o){var s;const t=String(o||"").replace("_","-"),e=Object.keys(J).find(a=>a.toLowerCase()===t.toLowerCase());if(e)return e;const n=(s=t.split("-")[0])==null?void 0:s.toLowerCase();return Object.keys(J).find(a=>a.toLowerCase().startsWith(`${n}-`))||St}function ue(o){return dt=xo(o),dt}function _t(o,t){return t.split(".").reduce((e,n)=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e[n]},o)}function Fo(o,t){return o.replace(/\{(\w+)\}/g,(e,n)=>Object.prototype.hasOwnProperty.call(t,n)?String(t[n]):e)}function he(){return de||ue(Bo()),dt}async function $o(){const o=await Do();return o?(de=!0,ue(o)):he()}function c(o,t={}){const e=he(),n=_t(J[e],o),i=_t(J[St],o);return Fo(typeof n=="string"?n:typeof i=="string"?i:o,t)}function Ho(o){const t=o.map(e=>String(e));return t.length===0?"":t.length===1?t[0]:t.length===2?c("list.two",{first:t[0],second:t[1]}):c("list.many",{items:t.slice(0,-1).join(", "),last:t[t.length-1]})}function Q(o){const t=`positions.${o.value}`,e=c(t);return e===t?o.label:e}function zo(o){const t=ee(o);return t?Q(t):""}const w=Object.freeze({dropdown:"lol-uikit-framed-dropdown",dropdownOption:"lol-uikit-dropdown-option",radioInputOption:"lol-uikit-radio-input-option",scrollable:"lol-uikit-scrollable",socialRosterGroup:"lol-social-roster-group"}),d=Object.freeze({socialRoster:".lol-social-roster",champSelectButtons:".bottom-right-buttons",firstChampSelectSquareButton:"lol-social-chat-toggle-button, .missions-tracker-button-component, .champ-select-voice-button-wrapper",dropdownRoot:".ui-dropdown",dropdownCurrent:".ui-dropdown-current",dropdownCurrentContent:".ui-dropdown-current-content",dropdownOption:w.dropdownOption,dropdownOptionSelected:`${w.dropdownOption}[selected]`,dropdownOptionsContainer:".ui-dropdown-options-container",dropdownOptions:".ui-dropdown-options",dropdownScrollable:w.scrollable,socialRosterGroupArrow:".arrow",socialRosterGroupHeader:".group-header",socialRosterGroupLabel:"span"});function vt(){return document.querySelector(d.socialRoster)}function ut(){return document.querySelector(d.champSelectButtons)}const Vo=50,Uo=100,Z=210,tt=40,K="controlado-position-filter",ht="controlado-position-filter-visible",_="controlado-position-filter__badge",pt="controlado-position-filter__badge--active",Rt="controlado-placeholder",Mt="controlado-search",pe="controlado-filter-input",me="controlado-tag--search",ge="controlado-tag",fe="controlado-filter-icon",B="controlado-filter-icon--trash",Nt="controlado-champion-option__content",Bt="controlado-champion-option__icon",Go="controlado-champion-option__text",Dt="controlado-champion-option__name",Yo="controlado-champion-option__description",qo="controlado-champion-option__static-icon",xt=`
|
|
10
|
+
import{request as O,sleep as v,linkEndpoint as Ot}from"https://cdn.jsdelivr.net/npm/balaclava-utils@latest";const Oe="1.11.4",we={enabled:!1,hideAutoAcceptPrompt:!0},Te={minMs:2e3,maxMs:4e3},ke={enabled:!1,force:!1,pickIntent:!0,respectManualPick:!1,champions:[432,235],randomAssignedPositions:[],randomPoolPositions:[],positionsByChampionId:{235:["BOTTOM","UTILITY"],432:["UTILITY"]}},Ie={enabled:!1,force:!1,champions:[157,777,238,38],randomPoolPositions:[]},Le={controladoAutoAccept:we,controladoActionDelay:Te,controladoPick:ke,controladoBan:Ie},te=0,ee=8e3,rt=100,ct=2e3,_e=4e3;function lt(o,t){const e=Number(o),n=Number.isFinite(t)?t:ct;if(!Number.isFinite(e))return lt(n,ct);const i=Math.round(e/rt)*rt;return Math.max(te,Math.min(ee,i))}function z(o,t,e=ct,n=_e){const i=lt(o,e),s=lt(t,n);return{minMs:Math.min(i,s),maxMs:Math.max(i,s)}}function ve(o){const{minMs:t,maxMs:e}=z(o.minMs,o.maxMs),n=e-t;return t+Math.floor(Math.random()*(n+1))}function U(o){const t=o/1e3;return`${Number.isInteger(t)?t.toFixed(0):t.toFixed(1)}s`}function m(o){const t=Number(o);return Number.isSafeInteger(t)&&t>0?t:null}function Re(o,t=null){const e=[],n=new Set,i=Me(t);if(!Array.isArray(o))return e;for(const s of o){const a=m(s);a===null||n.has(a)||i&&!i.has(a)||(e.push(a),n.add(a))}return e}function Me(o){return o?new Set(Array.from(o,m).filter(t=>t!==null)):null}const x=[{value:"TOP",label:"Top",iconPath:"/fe/lol-parties/icon-position-top.png"},{value:"JUNGLE",label:"Jungle",iconPath:"/fe/lol-parties/icon-position-jungle.png"},{value:"MIDDLE",label:"Mid",iconPath:"/fe/lol-parties/icon-position-middle.png"},{value:"BOTTOM",label:"ADC",iconPath:"/fe/lol-parties/icon-position-bottom.png"},{value:"UTILITY",label:"Support",iconPath:"/fe/lol-parties/icon-position-utility.png"}],Ne=new Set(x.map(o=>o.value));function F(o){const t=String(o??"").toUpperCase();return Ne.has(t)?t:null}function T(o){if(!Array.isArray(o))return[];const t=new Set;for(const e of o){const n=F(e);n&&t.add(n)}return x.map(e=>e.value).filter(e=>t.has(e))}function W(o,t=null){const e={};if(!o||typeof o!="object"||Array.isArray(o))return e;const n=Be(t);for(const[i,s]of Object.entries(o)){const a=m(i);if(a===null||!Array.isArray(s))continue;const r=String(a);if(n&&!n.has(r))continue;const l=[],u=new Set;for(const A of s){const V=F(A);!V||u.has(V)||(l.push(V),u.add(V))}l.length>0&&(e[r]=l)}return e}function Be(o){if(!o)return null;const t=new Set;for(const e of o){const n=m(e);n!==null&&t.add(String(n))}return t}function ne(o){return x.find(t=>t.value===o)}function oe(o,t){var n;const e=m(t);return e===null?[]:((n=o==null?void 0:o.positionsByChampionId)==null?void 0:n[String(e)])||[]}function De(o,t,e){const n=oe(o,t);if(n.length===0)return!0;const i=F(e);return i!==null&&n.includes(i)}const E="random",L="bravery";function P(o){return o===E}function k(o){return o===L}function M(o){return P(o)?E:k(o)?L:m(o)}function I(o){const t=M(o);return t===null?null:String(t)}function ft(o,t=null){const e=[],n=new Set,i=xe(t);if(!Array.isArray(o))return e;for(const s of o){const a=M(s);if(a===null)continue;const r=String(a);n.has(r)||typeof a=="number"&&i&&!i.has(a)||(e.push(a),n.add(r))}return e}function H(o){return o?Array.from(o,m).filter(t=>t!==null):[]}function xe(o){return o?new Set(Array.from(o,m).filter(t=>t!==null)):null}const wt=new Set;function ie(o,t){return Object.prototype.hasOwnProperty.call(o,t)}function C(o,t){return ie(o,t)}function Fe(o){return Array.isArray(o.priorityOptions)?o.priorityOptions:o.champions}function $e(o,t){return ie(o,"randomPoolPositions")?o.randomPoolPositions:t.randomPositions}function yt(){if(!DataStore)throw new Error("DataStore is not available");return DataStore}function He(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}function Pt(o){if(o!==void 0)return JSON.parse(JSON.stringify(o))}function se(o){const t=Le[o];if(!t)throw new Error(`Unknown auto-champion-select config key: ${o}`);return Pt(t)}function ae(o,t,e={}){const n=se(o),i=He(t)?Pt(t):{},s={...n,...i},a={};if(C(n,"enabled")&&(a.enabled=s.enabled===!0),C(n,"hideAutoAcceptPrompt")&&(a.hideAutoAcceptPrompt=s.hideAutoAcceptPrompt===!0),C(n,"minMs")&&C(n,"maxMs")){const{minMs:r,maxMs:l}=z(s.minMs,s.maxMs,n.minMs,n.maxMs);a.minMs=r,a.maxMs=l}return C(n,"force")&&(a.force=s.force===!0),C(n,"pickIntent")&&(a.pickIntent=s.pickIntent!==!1),C(n,"respectManualPick")&&(a.respectManualPick=s.respectManualPick===!0),C(n,"champions")&&(a.priorityOptions=ft(Fe(s),e.allowedChampionIds),a.champions=H(a.priorityOptions)),C(n,"randomAssignedPositions")&&(a.randomAssignedPositions=T(s.randomAssignedPositions)),C(n,"randomPoolPositions")&&(a.randomPoolPositions=T($e(i,s))),C(n,"positionsByChampionId")&&(a.positionsByChampionId=W(s.positionsByChampionId,e.selectedChampionIds||a.champions)),a}function re(o,t,e={}){const n=t===void 0?se(o):t;return ae(o,n,e)}function y(o,t={}){const n=yt().get(o);return re(o,n,t)}function ze(o,t,e={}){const n=yt(),i=ae(o,t,e);return n.set(o,i),i}function Ve(o,t){return JSON.stringify(o)===JSON.stringify(t)}function Ue(o,t,e){wt.has(o)||(wt.add(o),console.warn(`auto-champion-select: Repaired ${o} in DataStore. The stored value used a different schema; plugins like reynbow/auto-champ-lock write this shape. Saved normalized config.`,{storedConfig:t,normalizedConfig:e}))}function ce(o,t={}){const e=yt(),n=e.get(o),i=re(o,n,t);return(n===void 0||!Ve(n,i))&&(n!==void 0&&Ue(o,n,i),e.set(o,i)),i}function R(o,t,e={}){const n=y(o,e),i=Pt(n),s=t(i)||i;return ze(o,s,e)}const f=Object.freeze({readyCheckAccept:"/lol-matchmaking/v1/ready-check/accept",regionLocale:"/riotclient/region-locale",gameflowPhase:"/lol-gameflow/v1/gameflow-phase",wallet:"/lol-inventory/v1/wallet",ownedChampions:"/lol-champions/v1/owned-champions-minimal",championSummary:"/lol-game-data/assets/v1/champion-summary.json",recommendedChampionPositions:"/lol-perks/v1/recommended-champion-positions",champSelectSession:"/lol-champ-select/v1/session",pickableChampionIds:"/lol-champ-select/v1/pickable-champion-ids",bannableChampionIds:"/lol-champ-select/v1/bannable-champion-ids",championIcon(o){return`/lol-game-data/assets/v1/champion-icons/${o}.png`},champSelectAction(o){return`/lol-champ-select/v1/session/actions/${o}`}}),Ge=1e3;function St(o){let t=null;return function(){return t||(t=Promise.resolve().then(o).finally(()=>{t=null})),t}}function le(o,t={}){const e=[],n=new Set;if(!Array.isArray(o))return e;for(const i of o){if(!i||typeof i!="object")continue;const s=m(i.id),a=typeof i.name=="string"?i.name:"";s===null||!a||n.has(a)||(e.push({...i,id:s,name:a,squarePortraitPath:i.squarePortraitPath||f.championIcon(s),recommendedPositions:t[String(s)]||[]}),n.add(a))}return e.sort((i,s)=>i.name.localeCompare(s.name)),e}function Ye(o){const t={};if(!o||typeof o!="object"||Array.isArray(o))return t;for(const[e,n]of Object.entries(o))!n||typeof n!="object"||Array.isArray(n)||(t[e]=n.recommendedPositions);return W(t)}async function qe(){try{const o=await O("GET",f.recommendedChampionPositions);return o.ok?Ye(await o.json()):(console.warn("auto-champion-select(recommended-champion-positions): Request failed",o),{})}catch(o){return console.warn("auto-champion-select(recommended-champion-positions): Failed to load",o),{}}}const X=St(qe);async function je(){let o=await O("GET",f.ownedChampions);for(;!o.ok;)console.debug("auto-champion-select(owned-champions-minimal): Retrying..."),o=await O("GET",f.ownedChampions),await v(Ge);return le(await o.json(),await X())}async function Ke(){const[o,t]=await Promise.all([O("GET",f.championSummary),X()]);return le(await o.json(),t)}const We=St(je),de=St(Ke),Tt=300,Xe=-1,B=-3,Z=Object.freeze({INTENT:"intent",COMPLETION:"completion"}),b=Object.freeze({SATISFIED:"satisfied",TRY_NEXT_CHAMPION:"try-next-champion",STOP_CYCLE:"stop-cycle"}),N=Object.freeze({CONTINUE:"continue-cycle",STOP:"stop-cycle"}),h=Object.freeze({READY:"ready",SKIP_ACTION:"skip-action",STOP_CYCLE:"stop-cycle"}),S=Object.freeze({SATISFIED:"satisfied",TRY_NEXT_PRIORITY_OPTION:"try-next-priority-option",STOP_CYCLE:"stop-cycle"});function dt(o){return Array.isArray(o)?o.flat():[]}function Je(o){return dt(o).filter(t=>t.type==="ban"&&t.completed===!0).map(t=>t.championId)}function kt(o){return Array.isArray(o)?o:[]}function G(o){const t=new Set;for(const e of o){const n=m(e);n!==null&&t.add(n)}return t}function It(o){return o.type==="pick"?0:1}function Lt(){return{pickConfig:y("controladoPick"),banConfig:y("controladoBan"),actionDelayConfig:y("controladoActionDelay")}}function Qe(o){const t=[...o];for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return t}function Ze(o){return Array.isArray(o)&&o.length===1&&o[0]===Xe}function Y(o){return Number(o)===B}function tn(o){return o.type!=="pick"||o.isInProgress===!0}class en{constructor(){this.session=null,this.actions=null,this.localPlayerCellId=null,this.alliedIntentChampionIds=new Set,this.teammateIntentChampionIds=new Set,this.localPlayerIntentChampionId=null,this.localPlayerIntentIsBravery=!1,this.pickedChampionIds=new Set,this.bannedChampionIds=new Set,this.localPlayerAssignedPosition=null,this.rejectedBraveryActionPhases=new Map,this.pluginPickSelectionId=null,this.manualPickBlocked=!1,this.watchTask=null,this.watchVersion=0,this.mounted=!1}mount(){this.mounted||(this.mounted=!0,this.rejectedBraveryActionPhases.clear(),this.resetPickTracking(),this.watchVersion+=1,this.watchTask||(this.watchTask=this.watch()))}unmount(){this.mounted&&(this.mounted=!1,this.rejectedBraveryActionPhases.clear(),this.resetPickTracking(),this.watchVersion+=1)}async watch(){try{for(;this.mounted;){const t=this.watchVersion;let e=!1;try{await this.refreshSessionState(),e=!0}catch(n){console.debug("auto-champion-select: Failed to update champion select",n)}if(!e||!this.mounted||t!==this.watchVersion){this.mounted&&t===this.watchVersion&&await v(Tt);continue}try{await this.runAutoSelectCycle()}catch(n){console.debug("auto-champion-select: Failed to run champion select cycle",n)}this.mounted&&t===this.watchVersion&&await v(Tt)}}finally{this.watchTask=null}}async refreshSessionState(){var a,r;const t=await O("GET",f.champSelectSession);if(!t.ok)throw new Error(`Session request failed with status ${t.status}`);this.session=await t.json(),this.actions=this.session.actions,this.localPlayerCellId=this.session.localPlayerCellId;const e=kt(this.session.myTeam),n=kt(this.session.theirTeam),i=e.find(l=>l.cellId===this.localPlayerCellId),s=e.filter(l=>l.cellId!==this.localPlayerCellId);this.localPlayerAssignedPosition=F(i==null?void 0:i.assignedPosition),this.localPlayerIntentChampionId=m(i==null?void 0:i.championPickIntent),this.localPlayerIntentIsBravery=Y(i==null?void 0:i.championPickIntent),this.pickedChampionIds=G([...e,...n].map(l=>l.championId)),this.bannedChampionIds=G([...((a=this.session.bans)==null?void 0:a.myTeamBans)||[],...((r=this.session.bans)==null?void 0:r.theirTeamBans)||[],...Je(this.actions)]),this.alliedIntentChampionIds=G(e.map(l=>l.championPickIntent)),this.teammateIntentChampionIds=G(s.map(l=>l.championPickIntent))}async runAutoSelectCycle(){const t=Lt();if(!t.pickConfig.enabled&&!t.banConfig.enabled)return;const e=this.getLocalPlayerActions();if(e.length===0){console.debug("auto-champion-select: No local player sub actions found, skipping..."),this.unmount();return}for(const n of e)if(await this.runAutoSelectForAction(n,t)===N.STOP)return}async runAutoSelectForAction(t,e){const n=await this.prepareActionForAutoSelect(t,e);switch(n.status){case h.READY:return this.tryAutoSelectPlan(n.plan);case h.SKIP_ACTION:return N.CONTINUE;case h.STOP_CYCLE:return N.STOP;default:throw new Error(`Unexpected auto-select plan status: ${n.status}`)}}async prepareActionForAutoSelect(t,e){const n=this.getConfigForActionType(t.type,e);if(!(n!=null&&n.enabled))return{status:h.SKIP_ACTION};if(!this.isActionAvailable(t,n))return{status:h.SKIP_ACTION};if(this.shouldSkipPickForManualSelection(t,n))return{status:h.SKIP_ACTION};const i=this.createAutoSelectPlan(t,n);if(!i)return{status:h.SKIP_ACTION};const s=this.createPlanLimitedToAlreadySatisfiedPriorityOption(i);if(s)return{status:h.READY,plan:s};const a=await this.delayAndRefreshAutoSelectPlan(t,n,e.actionDelayConfig);return a.status!==h.READY?a:{status:h.READY,plan:this.createPlanLimitedToAlreadySatisfiedPriorityOption(a.plan)||a.plan}}async tryAutoSelectPlan(t){for(const e of t.priorityOptions){const n=await this.tryPriorityOptionForAction(t.action,e,t.config);if(n===S.SATISFIED)return N.CONTINUE;if(n===S.STOP_CYCLE)return N.STOP}return N.CONTINUE}async tryPriorityOptionForAction(t,e,n){if(this.isPriorityOptionAlreadySatisfied(t,e))return S.SATISFIED;if(k(e))return this.tryBraveryForAction(t,n);const i=await this.resolveChampionIdsForPriorityOption(t,e,n),s=P(e)&&!this.isLockingExistingPickIntent(t,i);for(const a of i){const r={tryNextRandomCandidateOnFailure:s},l=await this.attemptChampionForAction(t,a,n,r);if(l===b.SATISFIED)return S.SATISFIED;if(l===b.STOP_CYCLE)return S.STOP_CYCLE}return S.TRY_NEXT_PRIORITY_OPTION}async tryBraveryForAction(t,e){if(t.type!=="pick")return S.TRY_NEXT_PRIORITY_OPTION;if(this.isBraveryPickIntentSet(t))return S.SATISFIED;console.debug("auto-champion-select: Trying to pick Bravery...");const n=await this.selectChampion(t,B);console.debug(n.ok?"auto-champion-select: Bravery request accepted, refreshing champ select state...":"auto-champion-select: Failed to pick Bravery, refreshing champ select state..."),n.ok&&(this.pluginPickSelectionId=B,await this.completePickIfNowInProgress(t,B));const i=await this.refreshPendingAction(t);return!i||!this.isActionAvailable(i,e)?n.ok?S.SATISFIED:S.STOP_CYCLE:this.isBraveryPickIntentSet(i)?S.SATISFIED:(this.pluginPickSelectionId=null,this.rememberRejectedBraveryAction(t),console.debug("auto-champion-select: Bravery was not applied after refresh, trying next pick..."),S.TRY_NEXT_PRIORITY_OPTION)}getLocalPlayerActions(){return dt(this.actions).filter(t=>this.isPendingLocalPlayerAction(t)).sort((t,e)=>It(t)-It(e))}isPendingLocalPlayerAction(t){return t.actorCellId===this.localPlayerCellId&&t.completed===!1}isActionAvailable(t,e){return t.type==="pick"?t.isInProgress===!0||e.pickIntent!==!1:t.isInProgress===!0}getConfigForActionType(t,e){return t==="pick"?e.pickConfig:t==="ban"?e.banConfig:null}createAutoSelectPlan(t,e){const n=this.getAvailablePriorityOptionsForAction(t,e);return n.length===0?null:{action:t,config:e,priorityOptions:n}}getAvailablePriorityOptionsForAction(t,e){return ft(e.priorityOptions||e.champions).filter(n=>!this.isPriorityOptionUnavailableForAction(t,n,e))}isPriorityOptionUnavailableForAction(t,e,n){return P(e)?this.isRandomPriorityOptionUnavailableForAction(t,n):k(e)?this.isBraveryPriorityOptionUnavailableForAction(t):this.isChampionUnavailableForAction(t,e,n)}isBraveryPriorityOptionUnavailableForAction(t){if(t.type!=="pick")return!0;const e=this.rejectedBraveryActionPhases.get(t.id);return e===void 0?!1:t.isInProgress===!0&&e===Z.INTENT?(this.rejectedBraveryActionPhases.delete(t.id),!1):!0}rememberRejectedBraveryAction(t){const e=t.isInProgress===!0?Z.COMPLETION:Z.INTENT;this.rejectedBraveryActionPhases.set(t.id,e)}isRandomPriorityOptionUnavailableForAction(t,e){if(t.type!=="pick")return!1;const n=T(e.randomAssignedPositions);return n.length===0?!1:this.localPlayerAssignedPosition?n.includes(this.localPlayerAssignedPosition)?!1:(console.debug(`auto-champion-select: Skipping random pick because assigned position ${this.localPlayerAssignedPosition} is not in ${n.join(", ")}.`),!0):(console.debug(`auto-champion-select: Skipping random pick because no assigned position is available for ${n.join(", ")} restriction.`),!0)}createPlanLimitedToAlreadySatisfiedPriorityOption(t){const e=t.priorityOptions.find(n=>this.isPriorityOptionAlreadySatisfied(t.action,n));return e===void 0?null:{...t,priorityOptions:[e]}}isPriorityOptionAlreadySatisfied(t,e){return P(e)?this.hasAnyPickIntentSet(t):k(e)?this.isBraveryPickIntentSet(t):this.isPickIntentSetToChampion(t,e)}hasAnyPickIntentSet(t){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentChampionId!==null||this.localPlayerIntentIsBravery||m(t.championId)!==null||Y(t.championId))}isBraveryPickIntentSet(t){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentIsBravery||Y(t.championId))}isLockingExistingPickIntent(t,e){return t.type==="pick"&&t.isInProgress===!0&&e.length===1&&e[0]===this.getPickIntentChampionId(t)}getPickIntentChampionId(t){return t.type!=="pick"?null:m(t.championId)??this.localPlayerIntentChampionId}getCurrentLocalPickOrIntentSelectionId(t){if(t.type!=="pick")return null;const e=m(t.championId);return e!==null?e:Y(t.championId)?B:this.localPlayerIntentChampionId!==null?this.localPlayerIntentChampionId:this.localPlayerIntentIsBravery?B:null}shouldSkipPickForManualSelection(t,e){if(t.type!=="pick"||e.respectManualPick!==!0)return!1;if(this.manualPickBlocked)return!0;const n=this.getCurrentLocalPickOrIntentSelectionId(t);return n===null||this.pluginPickSelectionId===n?!1:(this.manualPickBlocked=!0,console.debug(`auto-champion-select: Skipping pick action ${t.id} because manual pick ${n} was detected.`),!0)}resetPickTracking(){this.pluginPickSelectionId=null,this.manualPickBlocked=!1}async delayAndRefreshAutoSelectPlan(t,e,n){const i=ve(n);if(i<=0){console.debug(`auto-champion-select: Action delay is instant for ${t.type}.`);const u=this.createAutoSelectPlan(t,e);return u?{status:h.READY,plan:u}:{status:h.STOP_CYCLE}}console.debug(`auto-champion-select: Waiting ${i}ms before ${t.type}...`);const s=this.watchVersion;if(await v(i),!this.mounted||s!==this.watchVersion)return{status:h.STOP_CYCLE};let a=null;try{await this.refreshSessionState(),a=this.findPendingAction(t)}catch(u){return console.debug("auto-champion-select: Failed to refresh champion select after action delay",u),{status:h.STOP_CYCLE}}const r=this.getConfigForActionType(t.type,Lt());if(!(r!=null&&r.enabled))return{status:h.STOP_CYCLE};if(!a||!this.isActionAvailable(a,r))return{status:h.STOP_CYCLE};if(this.shouldSkipPickForManualSelection(a,r))return{status:h.SKIP_ACTION};const l=this.createAutoSelectPlan(a,r);return l?{status:h.READY,plan:l}:{status:h.STOP_CYCLE}}async resolveChampionIdsForPriorityOption(t,e,n){return k(e)?[]:P(e)?this.resolveRandomChampionIdsForAction(t,n):[e]}async resolveRandomChampionIdsForAction(t,e){if(t.type==="pick"&&t.isInProgress===!0){const a=this.getPickIntentChampionId(t);if(a!==null&&!this.isChampionUnavailableForAction(t,a,e))return[a]}const n=await this.fetchRandomCandidateChampionIds(t);if(n.length===0)return[];const i=n.filter(a=>!this.isChampionUnavailableForAction(t,a,e)),s=t.type==="pick"&&!this.hasConfiguredRandomPoolPositions(e)?await this.preferAssignedPositionRandomPickCandidates(i):await this.filterRandomChampionIdsByConfiguredPoolPositions(i,e);return Qe(s)}async fetchRandomCandidateChampionIds(t){const e=t.type==="pick"?f.pickableChampionIds:f.bannableChampionIds;try{const n=await O("GET",e);if(!n.ok)return console.debug(`auto-champion-select: Failed to load random ${t.type} candidates`,n),[];const i=await n.json();return t.type==="ban"&&Ze(i)?(console.debug("auto-champion-select: Random ban endpoint returned unrestricted sentinel, falling back to all champions..."),await this.fetchAllChampionIdsForRandomBan()):Re(i)}catch(n){return console.debug(`auto-champion-select: Failed to load random ${t.type} candidates`,n),[]}}async fetchAllChampionIdsForRandomBan(){return(await de()).map(e=>e.id)}hasConfiguredRandomPoolPositions(t){return T(t.randomPoolPositions).length>0}async filterRandomChampionIdsByConfiguredPoolPositions(t,e){const n=T(e.randomPoolPositions);if(n.length===0)return t;const i=new Set(n),s=await X(),a=t.filter(r=>{var l;return(l=s[String(r)])==null?void 0:l.some(u=>i.has(u))});return a.length===0&&console.debug(`auto-champion-select: No random candidates matched ${n.join(", ")} restriction.`),a}async preferAssignedPositionRandomPickCandidates(t){if(!this.localPlayerAssignedPosition)return t;const e=await X(),n=t.filter(i=>{var s;return(s=e[String(i)])==null?void 0:s.includes(this.localPlayerAssignedPosition)});return n.length>0?n:t}async attemptChampionForAction(t,e,n,i={}){const s=m(e);if(s===null||this.isChampionUnavailableForAction(t,s,n))return b.TRY_NEXT_CHAMPION;if(this.isPickIntentSetToChampion(t,s))return b.SATISFIED;if(console.debug(`auto-champion-select: Trying to ${t.type} ${s}...`),(await this.selectChampion(t,s)).ok)return t.type==="pick"&&(this.pluginPickSelectionId=s,await this.completePickIfNowInProgress(t,s)),b.SATISFIED;console.debug(`auto-champion-select: Failed to ${t.type} ${s}, refreshing champ select state...`);const r=await this.refreshPendingAction(t);return!r||!this.isActionAvailable(r,n)?b.STOP_CYCLE:i.tryNextRandomCandidateOnFailure===!0?this.hasAnyPickIntentSet(r)?b.SATISFIED:(console.debug(`auto-champion-select: Failed random ${t.type} candidate ${s}, trying next ${t.type}...`),b.TRY_NEXT_CHAMPION):this.isChampionUnavailableForAction(r,s,n)?(console.debug(`auto-champion-select: ${s} is unavailable after refresh, trying next ${t.type}...`),b.TRY_NEXT_CHAMPION):b.STOP_CYCLE}isPickIntentSetToChampion(t,e){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentChampionId===e||m(t.championId)===e)}async completePickIfNowInProgress(t,e){if(t.type!=="pick"||t.isInProgress===!0)return;const n=await this.refreshPendingAction(t);(n==null?void 0:n.isInProgress)!==!0||this.getCurrentLocalPickOrIntentSelectionId(n)!==e||(console.debug(`auto-champion-select: Completing pick ${e} after accepted pick intent...`),await this.selectChampion(n,e))}async refreshPendingAction(t){try{await this.refreshSessionState()}catch(e){return console.debug("auto-champion-select: Failed to refresh champion select action",e),null}return this.findPendingAction(t)}findPendingAction(t){return dt(this.actions).find(e=>e.id===t.id&&e.actorCellId===t.actorCellId&&e.type===t.type&&e.completed===!1)||null}isChampionUnavailableForAction(t,e,n){if(t.type==="pick"&&!De(n,e,this.localPlayerAssignedPosition)){const i=oe(n,e);return this.localPlayerAssignedPosition?console.debug(`auto-champion-select: Picking ${e} but assigned position ${this.localPlayerAssignedPosition} is not in ${i.join(", ")}, skipping...`):console.debug(`auto-champion-select: Picking ${e} but no assigned position is available for ${i.join(", ")} restriction, skipping...`),!0}if(this.bannedChampionIds.has(e))return console.debug(`auto-champion-select: Banning ${e} but it's already banned, skipping...`),!0;if(t.type==="ban"&&this.alliedIntentChampionIds.has(e))if(n.force===!0)console.debug(`auto-champion-select: Banning ${e} but it has an allied pick intent, forcing...`);else return console.debug(`auto-champion-select: Banning ${e} but it has an allied pick intent, skipping...`),!0;if(t.type==="pick"&&this.teammateIntentChampionIds.has(e))if(n.force===!0)console.debug(`auto-champion-select: Picking ${e} but it has a teammate pick intent, forcing...`);else return console.debug(`auto-champion-select: Picking ${e} but it has a teammate pick intent, skipping...`),!0;return t.type==="pick"&&this.pickedChampionIds.has(e)?(console.debug(`auto-champion-select: Picking ${e} but it's already picked, skipping...`),!0):!1}selectChampion(t,e){const n=f.champSelectAction(t.id),i={championId:e,completed:tn(t)};return O("PATCH",n,{body:i})}}const nn={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},on={autoAccept:"Accept",pick:"Pick",ban:"Ban"},sn={on:"ON",off:"OFF"},an={pick:"Pick",ban:"Ban"},rn={TOP:"Top",JUNGLE:"Jungle",MIDDLE:"Mid",BOTTOM:"ADC",UTILITY:"Support"},cn={two:"{first} or {second}",many:"{items}, or {last}"},ln={pickPlaceholder:"Add pick",banPlaceholder:"Add ban",search:"Search",emptyTitle:"No champions",pickEmptyHint:"Use the menu to add a pick",banEmptyHint:"Use the menu to add a ban",remove:"Remove {name}",positionFilterLabel:"Filter champions by position",random:{label:"Random",assignedTitlePart:"runs only when assigned role matches {positions}",poolTitlePart:"limits Random pool to {positions}"},bravery:{label:"Bravery",description:"For Arena mode"},positionBadge:{randomAssignedAny:"The plugin can use Random in any role. Click to run it only in selected draft roles.",randomAssignedSome:"The plugin will use Random only when your assigned role matches {positions}. Draft modes only. Click to edit.",randomPoolAny:"The plugin can choose any available champion at random. Click to filter the pool first.",randomPoolSome:"The plugin filters Random to champions for {positions}, then picks one. Click to edit.",championSome:"The plugin will pick this champion only when your assigned role matches {positions}. Draft modes only. Click to edit.",championAny:"The plugin can pick this champion in any role. Click to limit it to selected draft roles."}},dn={triggerLabel:"Auto champion select settings",empty:"No settings available",actionDelay:"Action delay",pickIntent:"Set pick intent",respectManualPick:"Respect manual pick",forcePick:"Ignore ally pick intent",forceBan:"Ignore ally pick intent when banning",hideAutoAcceptPrompt:"Hide auto-accept prompt",handleLabel:"{label} {handle}",handles:{min:"min",max:"max"},actionDelayValue:{instant:"Instant",exact:"Delays actions for {delay}",upTo:"Delays actions up to {delay}",range:"Delays actions {min}-{max}"}},un={readyCheckAccepted:"Match accepted!",readyCheckAcceptFailed:"Failed to accept match. Check console."},hn={group:"Balaclava: Auto Champion Select",autoSwitchName:"Auto {name} [{state}]",turnOn:"Turn ON",turnOff:"Turn OFF",autoSwitchOn:"Auto {name} is ON!",autoSwitchOff:"Auto {name} is OFF!",autoSwitchError:"Failed to toggle Auto {name}. Check console.",forcePickName:"Ignore Team Intent Pick",forceBanName:"Ignore Team Intent Ban",forceSwitchName:"{name} [{state}]",forcePickLegend:"Pick even if a teammate intends that champion",forceBanLegend:"Ban even if a teammate intends that champion",forceSwitchOn:"{name} is ON!",forceSwitchOff:"{name} is OFF!",forceSwitchError:"Failed to toggle {name}. Check console.",refreshChampionsName:"Refresh Champions",refreshChampionsLegend:"Normally champion selectors refresh automatically...",refreshChampionsSuccess:"Refreshed Champions!",refreshChampionsError:"Failed to refresh Champions. Check console."},pn={plugin:nn,toggles:on,states:sn,actions:an,positions:rn,list:cn,selectors:ln,settings:dn,toasts:un,commandBar:hn},mn={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},gn={autoAccept:"Aceptar",pick:"Pick",ban:"Ban"},fn={on:"ON",off:"OFF"},yn={pick:"Pick",ban:"Ban"},Pn={TOP:"Top",JUNGLE:"Jungla",MIDDLE:"Mid",BOTTOM:"ADC",UTILITY:"Soporte"},Sn={two:"{first} o {second}",many:"{items} o {last}"},An={pickPlaceholder:"Agregar pick",banPlaceholder:"Agregar ban",search:"Buscar",emptyTitle:"Sin campeones",pickEmptyHint:"Usa el menú para agregar",banEmptyHint:"Usa el menú para agregar",remove:"Quitar {name}",positionFilterLabel:"Filtrar campeones por posición",random:{label:"Aleatorio",assignedTitlePart:"solo si la posición asignada es {positions}",poolTitlePart:"filtra el pool a {positions}"},bravery:{label:"Valentía",description:"Para Arena"},positionBadge:{randomAssignedAny:"Aleatorio sirve en cualquier posición. Haz clic para limitar posiciones de draft.",randomAssignedSome:"Aleatorio solo si tu posición es {positions}. Solo draft; haz clic para editar.",randomPoolAny:"Aleatorio puede elegir cualquier campeón disponible. Haz clic para filtrar.",randomPoolSome:"Aleatorio elige campeones de {positions}. Haz clic para editar.",championSome:"Este campeón solo se elige si tu posición es {positions}. Solo draft; haz clic para editar.",championAny:"Este campeón sirve en cualquier posición. Haz clic para limitar posiciones."}},Cn={triggerLabel:"Ajustes de Auto Champion Select",empty:"Sin ajustes",actionDelay:"Retraso de acción",pickIntent:"Marcar intención de selección",respectManualPick:"Respetar selección manual",forcePick:"Ignorar intención aliada al pickear",forceBan:"Ignorar intención aliada al banear",hideAutoAcceptPrompt:"Ocultar confirmación de partida",handleLabel:"{label} {handle}",handles:{min:"mín",max:"máx"},actionDelayValue:{instant:"Sin retraso",exact:"Retraso de {delay}",upTo:"Hasta {delay}",range:"Retraso de {min}-{max}"}},bn={readyCheckAccepted:"¡Partida aceptada!",readyCheckAcceptFailed:"No se pudo aceptar la partida. Revisa la consola."},En={group:"Balaclava: Auto Champion Select",autoSwitchName:"Auto {name} [{state}]",turnOn:"Activar",turnOff:"Desactivar",autoSwitchOn:"Auto {name} está ON!",autoSwitchOff:"Auto {name} está OFF!",autoSwitchError:"No se pudo cambiar Auto {name}. Revisa la consola.",forcePickName:"Ignorar intención aliada al pickear",forceBanName:"Ignorar intención aliada al banear",forceSwitchName:"{name} [{state}]",forcePickLegend:"Pickea aunque un aliado quiera el mismo campeón",forceBanLegend:"Banea aunque un aliado quiera ese campeón",forceSwitchOn:"{name} está ON!",forceSwitchOff:"{name} está OFF!",forceSwitchError:"No se pudo cambiar {name}. Revisa la consola.",refreshChampionsName:"Actualizar campeones",refreshChampionsLegend:"Normalmente los selectores se actualizan solos...",refreshChampionsSuccess:"¡Campeones actualizados!",refreshChampionsError:"No se actualizaron campeones. Revisa la consola."},On={plugin:mn,toggles:gn,states:fn,actions:yn,positions:Pn,list:Sn,selectors:An,settings:Cn,toasts:bn,commandBar:En},wn={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},Tn={autoAccept:"수락",pick:"선택",ban:"밴"},kn={on:"ON",off:"OFF"},In={pick:"선택",ban:"밴"},Ln={TOP:"탑",JUNGLE:"정글",MIDDLE:"미드",BOTTOM:"원딜",UTILITY:"서폿"},_n={two:"{first} 또는 {second}",many:"{items} 또는 {last}"},vn={pickPlaceholder:"픽 추가",banPlaceholder:"밴 추가",search:"검색",emptyTitle:"챔피언 없음",pickEmptyHint:"메뉴에서 추가",banEmptyHint:"메뉴에서 추가",remove:"{name} 제거",positionFilterLabel:"포지션별 챔피언 필터",random:{label:"랜덤",assignedTitlePart:"배정 포지션이 {positions}일 때만 실행",poolTitlePart:"랜덤 풀을 {positions}로 제한"},bravery:{label:"용기",description:"아레나용"},positionBadge:{randomAssignedAny:"랜덤은 모든 포지션에서 사용 가능. 클릭해 드래프트 포지션 제한.",randomAssignedSome:"랜덤은 배정 포지션이 {positions}일 때만 사용. 드래프트 전용; 클릭해 편집.",randomPoolAny:"랜덤은 가능한 모든 챔피언 중 선택 가능. 클릭해 풀 필터.",randomPoolSome:"랜덤은 {positions} 챔피언 중 선택. 클릭해 편집.",championSome:"이 챔피언은 배정 포지션이 {positions}일 때만 선택. 드래프트 전용; 클릭해 편집.",championAny:"이 챔피언은 모든 포지션에서 선택 가능. 클릭해 포지션 제한."}},Rn={triggerLabel:"Auto Champion Select 설정",empty:"설정 없음",actionDelay:"동작 지연",pickIntent:"선택 의도 설정",respectManualPick:"수동 선택 존중",forcePick:"아군 희망 챔피언 무시하고 선택",forceBan:"아군 희망 챔피언 무시하고 밴",hideAutoAcceptPrompt:"자동 수락 알림 숨기기",handleLabel:"{label} {handle}",handles:{min:"최소",max:"최대"},actionDelayValue:{instant:"즉시",exact:"{delay} 지연",upTo:"{delay}까지 지연",range:"{min}-{max} 지연"}},Mn={readyCheckAccepted:"게임 수락됨!",readyCheckAcceptFailed:"게임 수락 실패. 콘솔 확인."},Nn={group:"Balaclava: Auto Champion Select",autoSwitchName:"자동 {name} [{state}]",turnOn:"켜기",turnOff:"끄기",autoSwitchOn:"자동 {name} 켜짐!",autoSwitchOff:"자동 {name} 꺼짐!",autoSwitchError:"자동 {name} 전환 실패. 콘솔 확인.",forcePickName:"희망 챔피언 무시 선택",forceBanName:"희망 챔피언 무시 밴",forceSwitchName:"{name} [{state}]",forcePickLegend:"팀원이 같은 챔피언을 희망해도 선택",forceBanLegend:"팀원이 같은 챔피언을 희망해도 밴",forceSwitchOn:"{name} 켜짐!",forceSwitchOff:"{name} 꺼짐!",forceSwitchError:"{name} 전환 실패. 콘솔 확인.",refreshChampionsName:"챔피언 새로고침",refreshChampionsLegend:"챔피언 목록은 보통 자동으로 새로고침됩니다...",refreshChampionsSuccess:"챔피언 새로고침 완료!",refreshChampionsError:"챔피언 새로고침 실패. 콘솔 확인."},Bn={plugin:wn,toggles:Tn,states:kn,actions:In,positions:Ln,list:_n,selectors:vn,settings:Rn,toasts:Mn,commandBar:Nn},Dn={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},xn={autoAccept:"Aceitar",pick:"Pick",ban:"Ban"},Fn={on:"ON",off:"OFF"},$n={pick:"Pick",ban:"Ban"},Hn={TOP:"Top",JUNGLE:"Jungle",MIDDLE:"Mid",BOTTOM:"ADC",UTILITY:"Suporte"},zn={two:"{first} ou {second}",many:"{items} ou {last}"},Vn={pickPlaceholder:"Adicionar pick",banPlaceholder:"Adicionar ban",search:"Buscar",emptyTitle:"Nenhum campeão",pickEmptyHint:"Use o menu para adicionar um pick",banEmptyHint:"Use o menu para adicionar um ban",remove:"Remover {name}",positionFilterLabel:"Filtrar campeões por posição",random:{label:"Aleatório",assignedTitlePart:"só roda quando sua rota for {positions}",poolTitlePart:"limita o pool a {positions}"},bravery:{label:"Bravura",description:"Para o modo Arena"},positionBadge:{randomAssignedAny:"Aleatório pode rodar em qualquer rota. Clique para limitar às rotas do draft.",randomAssignedSome:"Aleatório só roda se sua rota for {positions}. Draft apenas. Clique para editar.",randomPoolAny:"Aleatório pode escolher qualquer campeão disponível. Clique para filtrar o pool.",randomPoolSome:"Aleatório escolhe campeões de {positions}. Clique para editar.",championSome:"Este campeão só será escolhido se sua rota for {positions}. Draft apenas. Clique para editar.",championAny:"Este campeão pode ser escolhido em qualquer rota. Clique para limitar às rotas do draft."}},Un={triggerLabel:"Configurações do Auto Champion Select",empty:"Nenhuma configuração disponível",actionDelay:"Delay de ação",pickIntent:"Marcar intenção de pick",respectManualPick:"Respeitar pick manual",forcePick:"Ignorar intenção aliada no pick",forceBan:"Ignorar intenção aliada no ban",hideAutoAcceptPrompt:"Ocultar confirmação da fila",handleLabel:"{label} {handle}",handles:{min:"mínimo",max:"máximo"},actionDelayValue:{instant:"Sem delay",exact:"Delay de {delay}",upTo:"Delay de até {delay}",range:"Delay de {min}-{max}"}},Gn={readyCheckAccepted:"Fila aceita!",readyCheckAcceptFailed:"Falha ao aceitar a fila. Verifique o console."},Yn={group:"Balaclava: Auto Champion Select",autoSwitchName:"Auto {name} [{state}]",turnOn:"Ativar",turnOff:"Desativar",autoSwitchOn:"Auto {name} está ON!",autoSwitchOff:"Auto {name} está OFF!",autoSwitchError:"Falha ao alternar Auto {name}. Verifique o console.",forcePickName:"Ignorar intenção aliada no pick",forceBanName:"Ignorar intenção aliada no ban",forceSwitchName:"{name} [{state}]",forcePickLegend:"Escolhe mesmo se um aliado indicar o mesmo campeão",forceBanLegend:"Bane mesmo se um aliado indicar o campeão",forceSwitchOn:"{name} está ON!",forceSwitchOff:"{name} está OFF!",forceSwitchError:"Falha ao alternar {name}. Verifique o console.",refreshChampionsName:"Atualizar campeões",refreshChampionsLegend:"Normalmente as listas de campeões atualizam automaticamente...",refreshChampionsSuccess:"Campeões atualizados!",refreshChampionsError:"Falha ao atualizar campeões. Verifique o console."},qn={plugin:Dn,toggles:xn,states:Fn,actions:$n,positions:Hn,list:zn,selectors:Vn,settings:Un,toasts:Gn,commandBar:Yn},jn={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},Kn={autoAccept:"Принять",pick:"Пик",ban:"Бан"},Wn={on:"ON",off:"OFF"},Xn={pick:"Пик",ban:"Бан"},Jn={TOP:"Топ",JUNGLE:"Лес",MIDDLE:"Мид",BOTTOM:"Бот",UTILITY:"Саппорт"},Qn={two:"{first} или {second}",many:"{items} или {last}"},Zn={pickPlaceholder:"Добавить пик",banPlaceholder:"Добавить бан",search:"Поиск",emptyTitle:"Нет чемпионов",pickEmptyHint:"Добавьте пик через меню",banEmptyHint:"Добавьте бан через меню",remove:"Удалить {name}",positionFilterLabel:"Фильтр чемпионов по позиции",random:{label:"Случайный",assignedTitlePart:"только если позиция — {positions}",poolTitlePart:"пул: {positions}"},bravery:{label:"Храбрость",description:"Для Арены"},positionBadge:{randomAssignedAny:"Случайный выбор работает на любой позиции. Нажмите, чтобы ограничить позиции.",randomAssignedSome:"Случайный выбор только если позиция — {positions}. Только в драфте; нажмите для изменения.",randomPoolAny:"Пул: все доступные чемпионы. Нажмите, чтобы отфильтровать.",randomPoolSome:"Пул: {positions}. Нажмите для изменения.",championSome:"Чемпион выбирается только если позиция — {positions}. Только в драфте; нажмите для изменения.",championAny:"Чемпион доступен на любой позиции. Нажмите, чтобы ограничить позиции."}},to={triggerLabel:"Настройки Auto Champion Select",empty:"Настроек нет",actionDelay:"Задержка действий",pickIntent:"Показывать препик",respectManualPick:"Уважать ручной пик",forcePick:"Игнорировать препик при пике",forceBan:"Игнорировать препик при бане",hideAutoAcceptPrompt:"Скрывать окно принятия матча",handleLabel:"{label} {handle}",handles:{min:"мин",max:"макс"},actionDelayValue:{instant:"Без задержки",exact:"Задержка {delay}",upTo:"Задержка до {delay}",range:"Задержка {min}-{max}"}},eo={readyCheckAccepted:"Матч принят!",readyCheckAcceptFailed:"Не удалось принять матч. Проверьте консоль."},no={group:"Balaclava: Auto Champion Select",autoSwitchName:"Авто {name} [{state}]",turnOn:"Включить",turnOff:"Выключить",autoSwitchOn:"Авто {name} включен!",autoSwitchOff:"Авто {name} выключен!",autoSwitchError:"Не удалось переключить Авто {name}. Проверьте консоль.",forcePickName:"Игнор препика при пике",forceBanName:"Игнор препика при бане",forceSwitchName:"{name} [{state}]",forcePickLegend:"Пикать, даже если союзник препикнул чемпиона",forceBanLegend:"Банить, даже если союзник препикнул чемпиона",forceSwitchOn:"Включено: {name}!",forceSwitchOff:"Выключено: {name}!",forceSwitchError:"Не удалось переключить {name}. Проверьте консоль.",refreshChampionsName:"Обновить список чемпионов",refreshChampionsLegend:"Обычно список чемпионов обновляется автоматически...",refreshChampionsSuccess:"Список чемпионов обновлен!",refreshChampionsError:"Не удалось обновить список чемпионов. Проверьте консоль."},oo={plugin:jn,toggles:Kn,states:Wn,actions:Xn,positions:Jn,list:Qn,selectors:Zn,settings:to,toasts:eo,commandBar:no},io={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},so={autoAccept:"Kabul Et",pick:"Seç",ban:"Yasakla"},ao={on:"ON",off:"OFF"},ro={pick:"Seç",ban:"Yasakla"},co={TOP:"Üst",JUNGLE:"Orman",MIDDLE:"Orta",BOTTOM:"Alt",UTILITY:"Destek"},lo={two:"{first} veya {second}",many:"{items} veya {last}"},uo={pickPlaceholder:"Seçim ekle",banPlaceholder:"Yasaklama ekle",search:"Ara",emptyTitle:"Şampiyon yok",pickEmptyHint:"Menüden seçenek ekle",banEmptyHint:"Menüden seçenek ekle",remove:"{name} kaldır",positionFilterLabel:"Şampiyonları konuma göre filtrele",random:{label:"Rastgele",assignedTitlePart:"atanan konum {positions} ise çalışır",poolTitlePart:"rastgele havuzu {positions} ile sınırlar"},bravery:{label:"Cesaret",description:"Arena modu için"},positionBadge:{randomAssignedAny:"Rastgele her konumda kullanılabilir. Draft konumlarıyla sınırla.",randomAssignedSome:"Rastgele yalnız atanan konum {positions} ise kullanılır. Sadece draft; düzenle.",randomPoolAny:"Rastgele tüm uygun şampiyonlardan seçebilir. Havuzu filtrele.",randomPoolSome:"Rastgele, {positions} şampiyonlarından seçer. Düzenle.",championSome:"Bu şampiyon yalnız atanan konum {positions} ise seçilir. Sadece draft; düzenle.",championAny:"Bu şampiyon her konumda seçilebilir. Konumları sınırla."}},ho={triggerLabel:"Auto Champion Select ayarları",empty:"Ayar yok",actionDelay:"İşlem gecikmesi",pickIntent:"Seçim niyeti ayarla",respectManualPick:"Manuel seçimi koru",forcePick:"Seçim niyetini yok sayarak seç",forceBan:"Seçim niyetini yok sayarak yasakla",hideAutoAcceptPrompt:"Karşılaşma kabul penceresini gizle",handleLabel:"{label} {handle}",handles:{min:"min",max:"maks"},actionDelayValue:{instant:"Anında",exact:"{delay} gecikme",upTo:"{delay} kadar gecikme",range:"{min}-{max} gecikme"}},po={readyCheckAccepted:"Karşılaşma kabul edildi!",readyCheckAcceptFailed:"Karşılaşma kabul edilemedi. Konsola bakın."},mo={group:"Balaclava: Auto Champion Select",autoSwitchName:"Oto {name} [{state}]",turnOn:"Aç",turnOff:"Kapat",autoSwitchOn:"Oto {name} açık!",autoSwitchOff:"Oto {name} kapalı!",autoSwitchError:"Oto {name} değiştirilemedi. Konsola bakın.",forcePickName:"Seçim niyetini yok sayarak seç",forceBanName:"Seçim niyetini yok sayarak yasakla",forceSwitchName:"{name} [{state}]",forcePickLegend:"Takım arkadaşı aynı şampiyonu istese de seçer",forceBanLegend:"Takım arkadaşı aynı şampiyonu istese de yasaklar",forceSwitchOn:"{name} açık!",forceSwitchOff:"{name} kapalı!",forceSwitchError:"{name} değiştirilemedi. Konsola bakın.",refreshChampionsName:"Şampiyonları yenile",refreshChampionsLegend:"Seçiciler normalde otomatik yenilenir...",refreshChampionsSuccess:"Şampiyonlar yenilendi!",refreshChampionsError:"Şampiyonlar yenilenemedi. Konsola bakın."},go={plugin:io,toggles:so,states:ao,actions:ro,positions:co,list:lo,selectors:uo,settings:ho,toasts:po,commandBar:mo},fo={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},yo={autoAccept:"Chấp nhận",pick:"Chọn",ban:"Cấm"},Po={on:"ON",off:"OFF"},So={pick:"Chọn",ban:"Cấm"},Ao={TOP:"Đường trên",JUNGLE:"Rừng",MIDDLE:"Đường giữa",BOTTOM:"Đường dưới",UTILITY:"Hỗ trợ"},Co={two:"{first} hoặc {second}",many:"{items} hoặc {last}"},bo={pickPlaceholder:"Thêm tướng chọn",banPlaceholder:"Thêm tướng cấm",search:"Tìm",emptyTitle:"Không có tướng",pickEmptyHint:"Dùng menu để thêm",banEmptyHint:"Dùng menu để thêm",remove:"Xóa {name}",positionFilterLabel:"Lọc tướng theo vị trí",random:{label:"Ngẫu nhiên",assignedTitlePart:"chỉ chạy khi vị trí là {positions}",poolTitlePart:"lọc bể tướng theo {positions}"},bravery:{label:"Quả Cảm",description:"Cho chế độ Võ Đài"},positionBadge:{randomAssignedAny:"Ngẫu nhiên dùng được mọi vị trí. Bấm để giới hạn vị trí Cấm Chọn.",randomAssignedSome:"Ngẫu nhiên chỉ dùng khi vị trí là {positions}. Chỉ Cấm Chọn; bấm để sửa.",randomPoolAny:"Ngẫu nhiên có thể chọn mọi tướng hợp lệ. Bấm để lọc nhóm.",randomPoolSome:"Ngẫu nhiên chọn tướng thuộc {positions}. Bấm để sửa.",championSome:"Tướng này chỉ được chọn khi vị trí là {positions}. Chỉ Cấm Chọn; bấm để sửa.",championAny:"Tướng này dùng được mọi vị trí. Bấm để giới hạn."}},Eo={triggerLabel:"Cài đặt Auto Champion Select",empty:"Không có cài đặt",actionDelay:"Độ trễ thao tác",pickIntent:"Đặt ý định chọn tướng",respectManualPick:"Tôn trọng chọn thủ công",forcePick:"Bỏ qua ý định chọn tướng",forceBan:"Bỏ qua ý định chọn khi cấm",hideAutoAcceptPrompt:"Ẩn lời nhắc chấp nhận trận",handleLabel:"{label} {handle}",handles:{min:"tối thiểu",max:"tối đa"},actionDelayValue:{instant:"Ngay",exact:"Trễ {delay}",upTo:"Tới {delay}",range:"Trễ {min}-{max}"}},Oo={readyCheckAccepted:"Đã chấp nhận trận!",readyCheckAcceptFailed:"Không thể chấp nhận trận. Xem console."},wo={group:"Balaclava: Auto Champion Select",autoSwitchName:"Tự động {name} [{state}]",turnOn:"Bật",turnOff:"Tắt",autoSwitchOn:"Tự động {name} đã bật!",autoSwitchOff:"Tự động {name} đã tắt!",autoSwitchError:"Không đổi được tự động {name}. Xem console.",forcePickName:"Bỏ qua ý định chọn tướng",forceBanName:"Bỏ qua ý định chọn khi cấm",forceSwitchName:"{name} [{state}]",forcePickLegend:"Vẫn chọn dù đồng đội cũng định chọn",forceBanLegend:"Vẫn cấm dù đồng đội định chọn",forceSwitchOn:"{name} đã bật!",forceSwitchOff:"{name} đã tắt!",forceSwitchError:"Không đổi được {name}. Xem console.",refreshChampionsName:"Làm mới tướng",refreshChampionsLegend:"Danh sách tướng thường tự làm mới...",refreshChampionsSuccess:"Đã làm mới tướng!",refreshChampionsError:"Không thể làm mới tướng. Xem console."},_t={plugin:fo,toggles:yo,states:Po,actions:So,positions:Ao,list:Co,selectors:bo,settings:Eo,toasts:Oo,commandBar:wo},To={socialRosterTitle:"AUTO CHAMPION SELECT",champSelectMenuTitle:"Auto Champion Select"},ko={autoAccept:"接受",pick:"选择",ban:"禁用"},Io={on:"ON",off:"OFF"},Lo={pick:"选择",ban:"禁用"},_o={TOP:"上路",JUNGLE:"打野",MIDDLE:"中路",BOTTOM:"下路",UTILITY:"辅助"},vo={two:"{first}或{second}",many:"{items}或{last}"},Ro={pickPlaceholder:"添加选用英雄",banPlaceholder:"添加禁用英雄",search:"搜索",emptyTitle:"无英雄",pickEmptyHint:"用菜单添加",banEmptyHint:"用菜单添加",remove:"移除{name}",positionFilterLabel:"按分路筛选英雄",random:{label:"随机",assignedTitlePart:"仅在分配位置为{positions}时执行",poolTitlePart:"将随机英雄池限制为{positions}"},bravery:{label:"勇敢举动",description:"用于斗魂竞技场"},positionBadge:{randomAssignedAny:"随机可用于任意位置。点击限制为选定征召位置。",randomAssignedSome:"随机仅在分配位置为{positions}时使用。仅征召;点击编辑。",randomPoolAny:"随机可从所有可用英雄中选择。点击筛选英雄池。",randomPoolSome:"随机从{positions}英雄中选择。点击编辑。",championSome:"仅当分配位置为{positions}时选择此英雄。仅征召;点击编辑。",championAny:"此英雄可用于任意位置。点击限制位置。"}},Mo={triggerLabel:"Auto Champion Select 设置",empty:"无设置",actionDelay:"操作延迟",pickIntent:"设置选用意向",respectManualPick:"尊重手动选择",forcePick:"无视队友意向并选用",forceBan:"无视队友意向并禁用",hideAutoAcceptPrompt:"隐藏对局接受提示",handleLabel:"{label} {handle}",handles:{min:"最小",max:"最大"},actionDelayValue:{instant:"立即",exact:"延迟{delay}",upTo:"最多{delay}",range:"延迟{min}-{max}"}},No={readyCheckAccepted:"对局已接受!",readyCheckAcceptFailed:"接受对局失败。查看控制台。"},Bo={group:"Balaclava: Auto Champion Select",autoSwitchName:"自动{name} [{state}]",turnOn:"开启",turnOff:"关闭",autoSwitchOn:"自动{name}已开启!",autoSwitchOff:"自动{name}已关闭!",autoSwitchError:"切换自动{name}失败。查看控制台。",forcePickName:"无视队友意向选用",forceBanName:"无视队友意向禁用",forceSwitchName:"{name} [{state}]",forcePickLegend:"即使队友也想用该英雄也会选用",forceBanLegend:"即使队友想用该英雄也会禁用",forceSwitchOn:"{name}已开启!",forceSwitchOff:"{name}已关闭!",forceSwitchError:"切换{name}失败。查看控制台。",refreshChampionsName:"刷新英雄列表",refreshChampionsLegend:"英雄列表通常会自动刷新...",refreshChampionsSuccess:"英雄列表已刷新!",refreshChampionsError:"刷新英雄列表失败。查看控制台。"},Do={plugin:To,toggles:ko,states:Io,actions:Lo,positions:_o,list:vo,selectors:Ro,settings:Mo,toasts:No,commandBar:Bo},At="en-US",J=Object.freeze({"en-US":pn,"es-MX":On,"ko-KR":Bn,"pt-BR":qn,"ru-RU":oo,"tr-TR":go,"vi-VN":_t,"vn-VN":_t,"zh-CN":Do});let ut=At,ue=!1;function xo(){var o,t,e;return typeof document<"u"?((t=(o=document.body)==null?void 0:o.dataset)==null?void 0:t.locale)||((e=document.documentElement)==null?void 0:e.lang)||"":typeof navigator<"u"&&navigator.language||""}async function Fo(){try{const o=await O("GET",f.regionLocale);if(!o.ok)return"";const t=await o.json();return typeof(t==null?void 0:t.locale)=="string"?t.locale:""}catch{return""}}function $o(o){var s;const t=String(o||"").replace("_","-"),e=Object.keys(J).find(a=>a.toLowerCase()===t.toLowerCase());if(e)return e;const n=(s=t.split("-")[0])==null?void 0:s.toLowerCase();return Object.keys(J).find(a=>a.toLowerCase().startsWith(`${n}-`))||At}function he(o){return ut=$o(o),ut}function vt(o,t){return t.split(".").reduce((e,n)=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e[n]},o)}function Ho(o,t){return o.replace(/\{(\w+)\}/g,(e,n)=>Object.prototype.hasOwnProperty.call(t,n)?String(t[n]):e)}function pe(){return ue||he(xo()),ut}async function zo(){const o=await Fo();return o?(ue=!0,he(o)):pe()}function c(o,t={}){const e=pe(),n=vt(J[e],o),i=vt(J[At],o);return Ho(typeof n=="string"?n:typeof i=="string"?i:o,t)}function Vo(o){const t=o.map(e=>String(e));return t.length===0?"":t.length===1?t[0]:t.length===2?c("list.two",{first:t[0],second:t[1]}):c("list.many",{items:t.slice(0,-1).join(", "),last:t[t.length-1]})}function Q(o){const t=`positions.${o.value}`,e=c(t);return e===t?o.label:e}function Uo(o){const t=ne(o);return t?Q(t):""}const w=Object.freeze({dropdown:"lol-uikit-framed-dropdown",dropdownOption:"lol-uikit-dropdown-option",radioInputOption:"lol-uikit-radio-input-option",scrollable:"lol-uikit-scrollable",socialRosterGroup:"lol-social-roster-group"}),d=Object.freeze({socialRoster:".lol-social-roster",champSelectButtons:".bottom-right-buttons",firstChampSelectSquareButton:"lol-social-chat-toggle-button, .missions-tracker-button-component, .champ-select-voice-button-wrapper",dropdownRoot:".ui-dropdown",dropdownCurrent:".ui-dropdown-current",dropdownCurrentContent:".ui-dropdown-current-content",dropdownOption:w.dropdownOption,dropdownOptionSelected:`${w.dropdownOption}[selected]`,dropdownOptionsContainer:".ui-dropdown-options-container",dropdownOptions:".ui-dropdown-options",dropdownScrollable:w.scrollable,socialRosterGroupArrow:".arrow",socialRosterGroupHeader:".group-header",socialRosterGroupLabel:"span"});function Rt(){return document.querySelector(d.socialRoster)}function ht(){return document.querySelector(d.champSelectButtons)}const Go=50,Yo=100,tt=210,et=40,K="controlado-position-filter",pt="controlado-position-filter-visible",_="controlado-position-filter__badge",mt="controlado-position-filter__badge--active",Mt="controlado-placeholder",Nt="controlado-search",me="controlado-filter-input",ge="controlado-tag--search",fe="controlado-tag",ye="controlado-filter-icon",D="controlado-filter-icon--trash",Bt="controlado-champion-option__content",Dt="controlado-champion-option__icon",qo="controlado-champion-option__text",xt="controlado-champion-option__name",jo="controlado-champion-option__description",Ko="controlado-champion-option__static-icon",Ft=`
|
|
11
11
|
${d.dropdownRoot} {
|
|
12
12
|
position: relative;
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
:host {
|
|
16
|
-
--framed-dropdown-scrollable-max-height: ${
|
|
16
|
+
--framed-dropdown-scrollable-max-height: ${tt}px;
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
:host ${d.dropdownRoot} dt${d.dropdownCurrent} {
|
|
@@ -38,7 +38,7 @@ import{request as O,sleep as v,linkEndpoint as Et}from"https://cdn.jsdelivr.net/
|
|
|
38
38
|
position: absolute;
|
|
39
39
|
top: auto;
|
|
40
40
|
bottom: 100%;
|
|
41
|
-
height: ${
|
|
41
|
+
height: ${tt}px;
|
|
42
42
|
overflow: hidden;
|
|
43
43
|
transform-origin: bottom;
|
|
44
44
|
transform: translateY(0);
|
|
@@ -46,7 +46,7 @@ import{request as O,sleep as v,linkEndpoint as Et}from"https://cdn.jsdelivr.net/
|
|
|
46
46
|
|
|
47
47
|
${d.dropdownOptions},
|
|
48
48
|
${d.dropdownScrollable} {
|
|
49
|
-
height: ${
|
|
49
|
+
height: ${tt}px;
|
|
50
50
|
}
|
|
51
51
|
|
|
52
52
|
${d.dropdownOptions} {
|
|
@@ -58,8 +58,8 @@ import{request as O,sleep as v,linkEndpoint as Et}from"https://cdn.jsdelivr.net/
|
|
|
58
58
|
box-sizing: border-box;
|
|
59
59
|
}
|
|
60
60
|
|
|
61
|
-
${d.dropdownOptionsContainer}.${
|
|
62
|
-
padding-top: ${
|
|
61
|
+
${d.dropdownOptionsContainer}.${pt} ${d.dropdownOptions} ${d.dropdownScrollable} {
|
|
62
|
+
padding-top: ${et}px;
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
.${K} {
|
|
@@ -71,8 +71,8 @@ import{request as O,sleep as v,linkEndpoint as Et}from"https://cdn.jsdelivr.net/
|
|
|
71
71
|
display: flex;
|
|
72
72
|
align-items: center;
|
|
73
73
|
justify-content: space-between;
|
|
74
|
-
height: ${
|
|
75
|
-
min-height: ${
|
|
74
|
+
height: ${et}px;
|
|
75
|
+
min-height: ${et}px;
|
|
76
76
|
padding: 0 17px;
|
|
77
77
|
border-bottom: 1px solid #1e282d;
|
|
78
78
|
background: #010a13;
|
|
@@ -103,7 +103,7 @@ import{request as O,sleep as v,linkEndpoint as Et}from"https://cdn.jsdelivr.net/
|
|
|
103
103
|
background: #0f1b2d;
|
|
104
104
|
}
|
|
105
105
|
|
|
106
|
-
.${
|
|
106
|
+
.${mt} {
|
|
107
107
|
border-color: #f0e6d2;
|
|
108
108
|
background: #09202c;
|
|
109
109
|
box-shadow: 0 0 0 1px #c89b3c, 0 0 10px rgba(200, 155, 60, 0.45);
|
|
@@ -120,11 +120,11 @@ import{request as O,sleep as v,linkEndpoint as Et}from"https://cdn.jsdelivr.net/
|
|
|
120
120
|
|
|
121
121
|
.${_}:hover img,
|
|
122
122
|
.${_}:focus img,
|
|
123
|
-
.${
|
|
123
|
+
.${mt} img {
|
|
124
124
|
opacity: 1;
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
-
.${
|
|
127
|
+
.${ye} {
|
|
128
128
|
cursor: default;
|
|
129
129
|
display: inline-block;
|
|
130
130
|
flex: 0 0 auto;
|
|
@@ -137,14 +137,14 @@ import{request as O,sleep as v,linkEndpoint as Et}from"https://cdn.jsdelivr.net/
|
|
|
137
137
|
-webkit-mask-size: 18px 18px;
|
|
138
138
|
}
|
|
139
139
|
|
|
140
|
-
.${
|
|
140
|
+
.${D} {
|
|
141
141
|
cursor: pointer;
|
|
142
142
|
background-color: #c86e6e;
|
|
143
143
|
-webkit-mask-image: url('/fe/lol-uikit/images/icon_delete.png');
|
|
144
144
|
-webkit-mask-size: 12px 12px;
|
|
145
145
|
}
|
|
146
146
|
|
|
147
|
-
.${
|
|
147
|
+
.${me} {
|
|
148
148
|
flex: 0 0 auto;
|
|
149
149
|
min-width: 0;
|
|
150
150
|
width: auto;
|
|
@@ -158,7 +158,7 @@ import{request as O,sleep as v,linkEndpoint as Et}from"https://cdn.jsdelivr.net/
|
|
|
158
158
|
font-weight: inherit;
|
|
159
159
|
}
|
|
160
160
|
|
|
161
|
-
.${
|
|
161
|
+
.${fe} {
|
|
162
162
|
cursor: default;
|
|
163
163
|
display: inline-flex;
|
|
164
164
|
align-items: center;
|
|
@@ -176,7 +176,7 @@ import{request as O,sleep as v,linkEndpoint as Et}from"https://cdn.jsdelivr.net/
|
|
|
176
176
|
box-shadow: inset 0 0 8px rgba(15, 30, 45, 0.6);
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
-
.${
|
|
179
|
+
.${ge} {
|
|
180
180
|
border-color: #d7b46a;
|
|
181
181
|
color: #f6e1b2;
|
|
182
182
|
background: #1a232f;
|
|
@@ -189,4 +189,4 @@ import{request as O,sleep as v,linkEndpoint as Et}from"https://cdn.jsdelivr.net/
|
|
|
189
189
|
text-transform: none;
|
|
190
190
|
font-weight: 500;
|
|
191
191
|
}
|
|
192
|
-
`;function et(o){const t=document.createElement(w.dropdownOption);return t.setAttribute("slot",w.dropdownOption),t.innerText=o,t}class jo{constructor(t,e,n,i={}){this.dropdownElement=t,this.placeholderText=e,this.searchPlaceholderText=i.searchPlaceholderText||c("selectors.search"),this.staticOptions=Array.isArray(i.staticOptions)?i.staticOptions:[],this.onPriorityOptionSelected=n,this.placeholderOption=null,this.searchQuery="",this.activePositionFilter=null,this.hasRecommendedPositionData=!1,this.recommendedPositionsByOption=new WeakMap,this.staticOptionElements=new WeakSet}renderOptions(t){this.dropdownElement.replaceChildren(),this.hasRecommendedPositionData=!1,this.staticOptionElements=new WeakSet,this.placeholderOption=et(this.placeholderText),this.placeholderOption.setAttribute("selected","true"),this.hidePlaceholderOption(),this.dropdownElement.appendChild(this.placeholderOption);for(const e of this.staticOptions)this.dropdownElement.appendChild(this.createStaticOption(e));for(const e of t){const n=this.getChampionRecommendedPositions(e),i=this.createChampionOption(e,n);n.length>0&&(this.hasRecommendedPositionData=!0),this.dropdownElement.appendChild(i)}this.hasRecommendedPositionData||(this.activePositionFilter=null),this.applyOptionFilters()}createChampionOption(t,e){const n=et("");return this.recommendedPositionsByOption.set(n,new Set(e)),n.title=t.name,n.appendChild(this.createChampionOptionContent(t)),n.addEventListener("click",()=>{this.onPriorityOptionSelected(t.id),requestAnimationFrame(()=>this.reset())}),n}createStaticOption(t){const e=et(""),n=typeof t.description=="string"?t.description:"";return this.staticOptionElements.add(e),e.title=n?`${t.label}. ${n}`:t.label,e.appendChild(this.createStaticOptionContent(t,n)),e.addEventListener("click",()=>{this.onPriorityOptionSelected(t.value),requestAnimationFrame(()=>this.reset())}),e}createChampionOptionContent(t){const e=document.createElement("span");e.classList.add(Nt);const n=document.createElement("img");n.classList.add(Bt),n.src=t.squarePortraitPath,n.alt="",n.draggable=!1,n.loading="lazy";const i=document.createElement("span");return i.classList.add(Dt),i.innerText=t.name,e.append(n,i),e}createStaticOptionContent(t,e=""){const n=document.createElement("span");n.classList.add(Nt);const i=t.iconPath?document.createElement("img"):document.createElement("span");i.classList.add(Bt),t.iconClass&&i.classList.add(t.iconClass),t.iconPath?(i.src=t.iconPath,i.alt="",i.draggable=!1,i.loading="lazy"):(i.classList.add(qo),i.innerText=t.iconText||"?");const s=document.createElement("span");s.classList.add(Dt),s.innerText=t.label;const a=document.createElement("span");if(a.classList.add(Go),a.appendChild(s),e){const r=document.createElement("span");r.classList.add(Yo),r.innerText=e,a.appendChild(r)}return n.append(i,a),n}getChampionRecommendedPositions(t){return Array.isArray(t.recommendedPositions)?t.recommendedPositions:[]}async waitForRender(){for(let t=0;t<Vo;t++){const e=this.dropdownElement.shadowRoot;if(this.dropdownElement.isConnected&&(e!=null&&e.querySelector(d.dropdownCurrent)))return e;await v(Uo)}return null}ensureSearchPlaceholder(t){if(t.querySelector(`#${Rt}`))return;const e=t.querySelector(d.dropdownCurrent);e&&e.appendChild(this.createSearchPlaceholder())}ensurePositionFilter(t){var n;const e=t.querySelector(d.dropdownOptionsContainer);if(e){if(!this.hasRecommendedPositionData){(n=t.querySelector(`.${K}`))==null||n.remove(),e.classList.remove(ht),this.activePositionFilter=null;return}e.classList.add(ht),t.querySelector(`.${K}`)||e.insertBefore(this.createPositionFilter(),e.firstChild),this.syncPositionFilter(t)}}createPositionFilter(){const t=document.createElement("div");t.classList.add(K),t.setAttribute("role","toolbar"),t.setAttribute("aria-label",c("selectors.positionFilterLabel"));for(const e of D)t.appendChild(this.createPositionFilterBadge(e));return t}createPositionFilterBadge(t){const e=Q(t),n=document.createElement("button");n.classList.add(_),n.type="button",n.dataset.position=t.value,n.title=e,n.setAttribute("aria-label",e),n.setAttribute("aria-pressed","false");const i=document.createElement("img");return i.src=t.iconPath,i.alt="",i.draggable=!1,n.appendChild(i),n.addEventListener("pointerdown",s=>{s.preventDefault(),s.stopPropagation()}),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.togglePositionFilter(t.value)}),n}createSearchPlaceholder(){const t=document.createElement("div");t.classList.add(ge,me),t.id=Rt;const e=document.createElement("input");e.classList.add(pe),e.id=Mt,e.type="text",e.placeholder=this.searchPlaceholderText,e.setAttribute("aria-label",this.searchPlaceholderText),e.size=Math.max(this.searchPlaceholderText.length,1);const n=document.createElement("span");return n.classList.add(fe),n.addEventListener("click",()=>{n.classList.contains(B)&&this.clearSearch(e,n)}),e.addEventListener("input",i=>{this.ensureOpen(),this.setSearchQuery(i.target.value),n.classList.toggle(B,!!i.target.value)}),["pointerdown","click"].forEach(i=>{t.addEventListener(i,s=>s.stopPropagation()),n.addEventListener(i,s=>s.stopPropagation())}),["pointerdown","focusin"].forEach(i=>{e.addEventListener(i,s=>s.stopPropagation(),!0)}),t.appendChild(n),t.appendChild(e),t}togglePositionFilter(t){const e=x(t);e&&(this.activePositionFilter=this.activePositionFilter===e?null:e,this.withShadowRoot(n=>this.syncPositionFilter(n)),this.applyOptionFilters())}syncPositionFilter(t){t.querySelectorAll(`.${_}`).forEach(e=>{const n=e.dataset.position===this.activePositionFilter;e.classList.toggle(pt,n),e.setAttribute("aria-pressed",String(n))})}clearSearch(t,e){t.value="",this.setSearchQuery(""),e.classList.toggle(B,!1)}setSearchQuery(t){this.searchQuery=t,this.applyOptionFilters()}applyOptionFilters(){const t=this.searchQuery.toLowerCase();this.dropdownElement.querySelectorAll(d.dropdownOption).forEach(n=>{if(n===this.placeholderOption){this.hidePlaceholderOption();return}this.matchesSearchQuery(n,t)&&this.matchesPositionFilter(n)?n.style.display="":n.style.display="none"})}matchesSearchQuery(t,e){return(t.textContent??"").toLowerCase().includes(e)}matchesPositionFilter(t){var e;return this.staticOptionElements.has(t)||!this.activePositionFilter?!0:((e=this.recommendedPositionsByOption.get(t))==null?void 0:e.has(this.activePositionFilter))===!0}hidePlaceholderOption(){this.placeholderOption&&(this.placeholderOption.style.display="none")}reset(){var t;this.dropdownElement.querySelectorAll(d.dropdownOptionSelected).forEach(e=>{e.removeAttribute("selected")}),(t=this.placeholderOption)==null||t.setAttribute("selected","true"),this.withShadowRoot(e=>{var s;const n=e.querySelector(`#${Mt}`),i=e.querySelector(`.${B}`);n&&i?this.clearSearch(n,i):(n&&(n.value="",this.setSearchQuery("")),i&&i.classList.remove(B)),this.isOpen()&&((s=e.querySelector(d.dropdownCurrent))==null||s.click())})}isOpen(){return this.dropdownElement.classList.contains("active")}ensureOpen(){this.isOpen()||this.withShadowRoot(t=>{const e=t.querySelector(d.dropdownCurrent);e&&e.click()})}patchDropdownShadowDom(){this.withShadowRoot(t=>{this.ensureDropdownOpensUpward(t),this.injectDropdownSearchStyles(t),this.ensurePositionFilter(t)})}ensureDropdownOpensUpward(t){var e;(e=t.querySelector(d.dropdownRoot))==null||e.classList.add("opens-upward")}injectDropdownSearchStyles(t){const e=t.querySelector("style[data-controlado='dropdown-tags']");if(e){e.textContent=xt;return}const n=document.createElement("style");n.dataset.controlado="dropdown-tags",n.textContent=xt,t.appendChild(n)}withShadowRoot(t){const e=this.dropdownElement.shadowRoot;e&&t(e)}}const Ko=".champion-priority-selector__position-badge",Wo=".champion-priority-selector__position-option",nt=".champion-priority-selector__remove",ot="✕",Ft="?",$t="/fe/lol-champ-select/images/champion-grid/bravery-champion.png",Xo="controlado-champion-option__icon--bravery",Jo="champion-priority-selector__icon--bravery",Qo=0,Ht=1,q=8,p=Object.freeze({CHAMPION_ASSIGNED:"champion-assigned",RANDOM_ASSIGNED:"random-assigned",RANDOM_POOL:"random-pool"}),Zo=5,ti=150,ei="cubic-bezier(0.2, 0, 0, 1)";function zt(){return c("selectors.random.label")}function Vt(){return c("selectors.bravery.label")}class Ut{constructor(t,e,n,i={}){this.element=this.createRootElement(),this.dropdownElement=this.createDropdownElement();const s=[];i.enableBraveryOption===!0&&s.push({value:L,label:Vt(),description:c("selectors.bravery.description"),iconPath:$t,iconClass:Xo}),s.push({value:E,label:zt(),iconText:Ft}),this.championDropdown=new jo(this.dropdownElement,t,l=>this.addPriorityOption(l),{searchPlaceholderText:i.searchPlaceholderText,staticOptions:s});const{scrollElement:a,trackElement:r}=this.createSelectedChampionsScroll();this.scrollElement=a,this.trackElement=r,this.enablePositionRestrictions=i.enablePositionRestrictions===!0,this.enableRandomPoolPositionFilters=i.enableRandomPoolPositionFilters===!0,this.enableRandomAssignedPositionRestrictions=i.enableRandomAssignedPositionRestrictions===!0,this.enableBraveryOption=i.enableBraveryOption===!0,this.enablePositionMenu=this.enablePositionRestrictions||this.enableRandomAssignedPositionRestrictions||this.enableRandomPoolPositionFilters,this.positionMenuElement=this.enablePositionMenu?this.createPositionMenu():null,this.positionMenuTarget=null,this.positionsByChampionId={},this.randomAssignedPositions=[],this.randomPoolPositions=[],this.emptyElement=this.createEmptyState(e),this.element.append(this.dropdownElement,this.scrollElement),this.positionMenuElement&&this.element.appendChild(this.positionMenuElement),this.config=null,this.configKey=e,this.loadChampions=n,this.champions=[],this.championById=new Map,this.selectedPriorityOptions=[],this.optionButtons=new Map,this.dragState=null,this.handleWindowPointerMove=l=>this.moveDrag(l),this.handleWindowPointerUp=l=>this.finishDrag(l),this.handleWindowPointerCancel=l=>this.cancelDrag(l),this.handlePositionMenuOutsidePointerDown=l=>this.closePositionMenuOnOutsidePointerDown(l),this.handlePositionMenuKeyDown=l=>this.closePositionMenuOnKeyDown(l),this.setupInFlight=null,this.setupPending=!1}createRootElement(){const t=document.createElement("div");return t.classList.add("champion-priority-selector"),t}createDropdownElement(){const t=document.createElement(w.dropdown);return t.classList.add("dropdown-champions-default","dropdown-drop-up"),t}createSelectedChampionsScroll(){const t=document.createElement(w.scrollable);t.classList.add("champion-priority-selector__scroll"),t.setAttribute("direction","horizontal"),t.setAttribute("overflow-masks","disabled"),t.setAttribute("side-scroll-wheel","true");const e=document.createElement("div");return e.classList.add("champion-priority-selector__track"),t.appendChild(e),{scrollElement:t,trackElement:e}}createEmptyState(t){const e=document.createElement("div");e.classList.add("champion-priority-selector__empty");const n=document.createElement("span");n.innerText=c("selectors.emptyTitle");const i=document.createElement("span");return i.innerText=c(t==="controladoPick"?"selectors.pickEmptyHint":"selectors.banEmptyHint"),e.append(n,i),e}createPositionMenu(){const t=document.createElement("div");t.classList.add("champion-priority-selector__position-menu"),t.hidden=!0;for(const e of D)t.appendChild(this.createPositionOption(e));return t}createPositionOption(t){const e=Q(t),n=document.createElement("button");n.classList.add("champion-priority-selector__position-option"),n.type="button",n.dataset.position=t.value,n.title=e,n.setAttribute("aria-label",e),n.setAttribute("aria-pressed","false"),n.addEventListener("pointerdown",s=>s.stopPropagation()),n.addEventListener("click",s=>{s.stopPropagation(),this.togglePositionMenuPosition(t.value)});const i=document.createElement("img");return i.src=t.iconPath,i.alt=e,i.draggable=!1,n.appendChild(i),n}async setup(){return this.setupPending=!0,this.setupInFlight||(this.setupInFlight=this.runSetupLoop()),this.setupInFlight}refresh(){return this.setup()}async runSetupLoop(){try{for(;this.setupPending;)this.setupPending=!1,await this.performSetup()}finally{this.setupInFlight=null}}async performSetup(){this.champions=await this.loadChampions(),this.championById=new Map(this.champions.map(n=>[n.id,n]));const t=this.getAllowedChampionIds();this.config=re(this.configKey,{allowedChampionIds:t}),this.selectedPriorityOptions=gt(this.config.priorityOptions||this.config.champions,t).filter(n=>this.isPriorityOptionEnabled(n)),this.enablePositionRestrictions&&(this.positionsByChampionId=W(this.config.positionsByChampionId,$(this.selectedPriorityOptions))),this.enableRandomAssignedPositionRestrictions&&(this.randomAssignedPositions=T(this.config.randomAssignedPositions)),this.enableRandomPoolPositionFilters&&(this.randomPoolPositions=T(this.config.randomPoolPositions)),this.championDropdown.renderOptions(this.champions),this.renderSelectedPriorityOptions();const e=await this.championDropdown.waitForRender();e&&(this.championDropdown.ensureSearchPlaceholder(e),this.championDropdown.patchDropdownShadowDom())}getAllowedChampionIds(){return new Set(this.championById.keys())}isPriorityOptionEnabled(t){return!k(t)||this.enableBraveryOption}addPriorityOption(t){const e=M(t);e===null||this.selectedPriorityOptions.includes(e)||!this.isPriorityOptionEnabled(e)||!P(e)&&!k(e)&&!this.championById.has(e)||(this.selectedPriorityOptions.push(e),this.renderSelectedPriorityOptions(),this.saveConfig())}removePriorityOption(t){var s;const e=M(t),n=this.selectedPriorityOptions.indexOf(e);if(e===null||n===-1)return;this.selectedPriorityOptions.splice(n,1);const i=typeof e=="number"?e:null;((s=this.positionMenuTarget)==null?void 0:s.option)===e&&this.closePositionMenu(),this.enablePositionRestrictions&&i!==null&&delete this.positionsByChampionId[String(i)],this.enableRandomAssignedPositionRestrictions&&P(e)&&(this.randomAssignedPositions=[]),this.enableRandomPoolPositionFilters&&P(e)&&(this.randomPoolPositions=[]),this.renderSelectedPriorityOptions(),this.saveConfig()}movePriorityOptionToIndex(t,e){const n=M(t),i=this.selectedPriorityOptions.indexOf(n);if(n===null||i===-1)return!1;const[s]=this.selectedPriorityOptions.splice(i,1),a=Math.max(0,Math.min(e,this.selectedPriorityOptions.length));return this.selectedPriorityOptions.splice(a,0,s),i!==a}syncPositionsByChampionId(){this.enablePositionRestrictions&&(this.positionsByChampionId=W(this.positionsByChampionId,$(this.selectedPriorityOptions)))}syncRandomPoolPositions(){this.enableRandomPoolPositionFilters&&(this.randomPoolPositions=T(this.randomPoolPositions))}syncRandomAssignedPositions(){this.enableRandomAssignedPositionRestrictions&&(this.randomAssignedPositions=T(this.randomAssignedPositions))}saveConfig(){this.syncPositionsByChampionId(),this.syncRandomAssignedPositions(),this.syncRandomPoolPositions();const t=this.getAllowedChampionIds();this.config=R(this.configKey,e=>(e.priorityOptions=[...this.selectedPriorityOptions],e.champions=$(this.selectedPriorityOptions),this.enableRandomAssignedPositionRestrictions&&(e.randomAssignedPositions=[...this.randomAssignedPositions]),this.enableRandomPoolPositionFilters&&(e.randomPoolPositions=[...this.randomPoolPositions]),this.enablePositionRestrictions&&(e.positionsByChampionId={...this.positionsByChampionId}),e),{allowedChampionIds:t,selectedChampionIds:$(this.selectedPriorityOptions)}),this.enablePositionRestrictions&&(this.positionsByChampionId=this.config.positionsByChampionId||{}),this.enableRandomAssignedPositionRestrictions&&(this.randomAssignedPositions=this.config.randomAssignedPositions||[]),this.enableRandomPoolPositionFilters&&(this.randomPoolPositions=this.config.randomPoolPositions||[]),console.debug(this.configKey,this.config)}renderSelectedPriorityOptions(t=null,e=null){this.positionMenuTarget!==null&&this.closePositionMenu();const n=new Set(this.selectedPriorityOptions.map(s=>I(s)));for(const[s,a]of this.optionButtons)n.has(s)||(a.remove(),this.optionButtons.delete(s));if(this.selectedPriorityOptions.length===0){this.trackElement.replaceChildren(this.emptyElement);return}this.emptyElement.remove();const i=this.selectedPriorityOptions.map((s,a)=>this.getPriorityOptionButton(s,a)).filter(Boolean);this.trackElement.append(...i),t&&this.animateReorder(t,e)}getPriorityOptionButton(t,e){return P(t)?this.getRandomOptionButton(e):k(t)?this.enableBraveryOption?this.getBraveryOptionButton(e):null:this.getChampionOptionButton(t,e)}getChampionOptionButton(t,e){const n=this.championById.get(t);if(!n)return null;const i=String(t);let s=this.optionButtons.get(i);s||(s=this.createIconButton(n),this.optionButtons.set(i,s)),s.dataset.rank=String(e+1),s.classList.toggle("champion-priority-selector__icon--random",!1);const a=this.getChampionPositionTitleSuffix(t);s.title=`${e+1}. ${n.name}${a}`,s.setAttribute("aria-label",`${e+1}. ${n.name}${a}`);const r=s.querySelector("img");r.src=n.squarePortraitPath,r.alt=n.name;const l=s.querySelector(nt);return l.setAttribute("aria-label",c("selectors.remove",{name:n.name})),l.title=c("selectors.remove",{name:n.name}),this.renderPositionBadge(s,t),s}getRandomOptionButton(t){let e=this.optionButtons.get(E);e||(e=this.createRandomOptionButton(),this.optionButtons.set(E,e)),e.dataset.rank=String(t+1);const n=zt(),i=this.getRandomPositionTitleSuffix();e.title=`${t+1}. ${n}${i}`,e.setAttribute("aria-label",`${t+1}. ${n}${i}`);const s=e.querySelector(nt);return s.setAttribute("aria-label",c("selectors.remove",{name:n})),s.title=c("selectors.remove",{name:n}),this.renderPositionBadge(e,E),e}getBraveryOptionButton(t){let e=this.optionButtons.get(L);e||(e=this.createBraveryOptionButton(),this.optionButtons.set(L,e)),e.dataset.rank=String(t+1);const n=Vt();e.title=`${t+1}. ${n}`,e.setAttribute("aria-label",`${t+1}. ${n}`);const i=e.querySelector("img");i.src=$t,i.alt=n;const s=e.querySelector(nt);return s.setAttribute("aria-label",c("selectors.remove",{name:n})),s.title=c("selectors.remove",{name:n}),e}createIconButton(t){const e=document.createElement("div");e.classList.add("champion-priority-selector__icon"),e.setAttribute("role","button"),e.tabIndex=0;const n=document.createElement("img");n.draggable=!1;const i=document.createElement("button");if(i.classList.add("champion-priority-selector__remove"),i.type="button",i.dataset.icon=ot,i.addEventListener("pointerdown",s=>s.stopPropagation()),i.addEventListener("click",s=>{s.stopPropagation(),this.removePriorityOption(t.id)}),e.addEventListener("pointerdown",s=>this.startDrag(s,t.id)),e.addEventListener("auxclick",s=>this.removePriorityOptionOnMiddleClick(s,t.id)),this.enablePositionRestrictions){const s={option:t.id,kind:p.CHAMPION_ASSIGNED};e.addEventListener("contextmenu",a=>this.openPositionMenu(a,s))}return e.append(n,i),e}createRandomOptionButton(){const t=document.createElement("div");t.classList.add("champion-priority-selector__icon","champion-priority-selector__icon--random"),t.setAttribute("role","button"),t.tabIndex=0;const e=document.createElement("span");e.classList.add("champion-priority-selector__random-icon"),e.innerText=Ft;const n=document.createElement("button");if(n.classList.add("champion-priority-selector__remove"),n.type="button",n.dataset.icon=ot,n.addEventListener("pointerdown",i=>i.stopPropagation()),n.addEventListener("click",i=>{i.stopPropagation(),this.removePriorityOption(E)}),t.addEventListener("pointerdown",i=>this.startDrag(i,E)),t.addEventListener("auxclick",i=>this.removePriorityOptionOnMiddleClick(i,E)),this.enableRandomPoolPositionFilters){const i={option:E,kind:p.RANDOM_POOL};t.addEventListener("contextmenu",s=>this.openPositionMenu(s,i))}return t.append(e,n),t}createBraveryOptionButton(){const t=document.createElement("div");t.classList.add("champion-priority-selector__icon",Jo),t.setAttribute("role","button"),t.tabIndex=0;const e=document.createElement("img");e.draggable=!1;const n=document.createElement("button");return n.classList.add("champion-priority-selector__remove"),n.type="button",n.dataset.icon=ot,n.addEventListener("pointerdown",i=>i.stopPropagation()),n.addEventListener("click",i=>{i.stopPropagation(),this.removePriorityOption(L)}),t.addEventListener("pointerdown",i=>this.startDrag(i,L)),t.addEventListener("auxclick",i=>this.removePriorityOptionOnMiddleClick(i,L)),t.append(e,n),t}getChampionAllowedPositions(t){const e=m(t);return e===null?[]:this.positionsByChampionId[String(e)]||[]}getRandomPoolPositions(){return this.randomPoolPositions}getRandomAssignedPositions(){return this.randomAssignedPositions}getPositionLabels(t){return t.map(e=>zo(e)).filter(Boolean)}getChampionAllowedPositionLabels(t){return this.getPositionLabels(this.getChampionAllowedPositions(t))}getRandomPoolPositionLabels(){return this.getPositionLabels(this.getRandomPoolPositions())}getRandomAssignedPositionLabels(){return this.getPositionLabels(this.getRandomAssignedPositions())}getChampionPositionTitleSuffix(t){const e=this.getChampionAllowedPositionLabels(t);return e.length>0?` (${e.join(", ")})`:""}getRandomPositionTitleSuffix(){const t=[],e=this.getRandomAssignedPositionLabels(),n=this.getRandomPoolPositionLabels();return e.length>0&&t.push(c("selectors.random.assignedTitlePart",{positions:this.formatPositionLabelsForSentence(e)})),n.length>0&&t.push(c("selectors.random.poolTitlePart",{positions:this.formatPositionLabelsForSentence(n)})),t.length>0?` (${t.join("; ")})`:""}formatPositionLabelsForSentence(t){return Ho(t)}renderPositionBadge(t,e){t.querySelectorAll(Ko).forEach(i=>i.remove());const n=M(e);if(n!==null)for(const i of this.getPositionBadgeTargetsForOption(n)){const s=this.createPositionBadge(i);s&&t.appendChild(s)}}getPositionBadgeTargetsForOption(t){return this.selectedPriorityOptions.includes(t)?P(t)?[{option:t,kind:p.RANDOM_ASSIGNED},{option:t,kind:p.RANDOM_POOL}].filter(e=>this.canOpenPositionMenuForTarget(e)):k(t)?[]:[{option:t,kind:p.CHAMPION_ASSIGNED}].filter(e=>this.canOpenPositionMenuForTarget(e)):[]}createPositionBadge(t){const e=this.getAllowedPositionsForPositionMenuTarget(t),n=this.getAllowedPositionLabelsForPositionMenuTarget(t),i=t.kind===p.RANDOM_POOL,s=document.createElement("button");if(s.classList.add("champion-priority-selector__position-badge"),s.classList.toggle("champion-priority-selector__position-badge--random",i),s.type="button",s.dataset.positionTarget=t.kind,s.title=this.getPositionBadgeTitle(n,t),s.setAttribute("aria-label",s.title),s.addEventListener("pointerdown",l=>l.stopPropagation()),s.addEventListener("click",l=>this.openPositionMenu(l,t,s)),i)return e.length>0?(s.classList.add("champion-priority-selector__position-badge--active"),s.dataset.count=String(e.length)):s.classList.add("champion-priority-selector__position-badge--empty"),s;if(e.length===0)return s.classList.add("champion-priority-selector__position-badge--empty"),s.innerText="+",s;const a=ee(e[0]);if(!a)return null;e.length>1&&(s.dataset.count=String(e.length));const r=document.createElement("img");return r.src=a.iconPath,r.alt=Q(a),r.draggable=!1,s.appendChild(r),s}getPositionBadgeTitle(t,e){return e.kind===p.RANDOM_ASSIGNED?t.length===0?c("selectors.positionBadge.randomAssignedAny"):c("selectors.positionBadge.randomAssignedSome",{positions:this.formatPositionLabelsForSentence(t)}):e.kind===p.RANDOM_POOL?t.length===0?c("selectors.positionBadge.randomPoolAny"):c("selectors.positionBadge.randomPoolSome",{positions:this.formatPositionLabelsForSentence(t)}):t.length>0?c("selectors.positionBadge.championSome",{positions:this.formatPositionLabelsForSentence(t)}):c("selectors.positionBadge.championAny")}canOpenPositionMenuForTarget(t){if(!this.selectedPriorityOptions.includes(t.option))return!1;switch(t.kind){case p.CHAMPION_ASSIGNED:return typeof t.option=="number"&&this.enablePositionRestrictions;case p.RANDOM_ASSIGNED:return P(t.option)&&this.enableRandomAssignedPositionRestrictions;case p.RANDOM_POOL:return P(t.option)&&this.enableRandomPoolPositionFilters;default:return!1}}normalizePositionMenuTarget(t){if(!t||typeof t!="object"||Array.isArray(t)||!("option"in t)||!("kind"in t))return null;const e=M(t.option),n=e===null?null:{option:e,kind:String(t.kind)};return n&&this.canOpenPositionMenuForTarget(n)?n:null}getAllowedPositionsForPositionMenuTarget(t){switch(t.kind){case p.CHAMPION_ASSIGNED:return this.getChampionAllowedPositions(t.option);case p.RANDOM_ASSIGNED:return this.getRandomAssignedPositions();case p.RANDOM_POOL:return this.getRandomPoolPositions();default:return[]}}getAllowedPositionLabelsForPositionMenuTarget(t){return this.getPositionLabels(this.getAllowedPositionsForPositionMenuTarget(t))}setAllowedPositionsForPositionMenuTarget(t,e){switch(t.kind){case p.CHAMPION_ASSIGNED:{const n=String(t.option);e.length>0?this.positionsByChampionId[n]=e:delete this.positionsByChampionId[n];break}case p.RANDOM_ASSIGNED:this.randomAssignedPositions=e;break;case p.RANDOM_POOL:this.randomPoolPositions=e;break}}openPositionMenu(t,e,n=null){if(!this.positionMenuElement)return;const i=this.normalizePositionMenuTarget(e);if(i===null)return;t.preventDefault(),t.stopPropagation(),this.positionMenuTarget=i,this.renderPositionMenu(),this.positionMenuElement.hidden=!1,this.positionMenuElement.style.left="0px",this.positionMenuElement.style.top="0px";const{left:s,top:a}=this.getPositionMenuCoordinates(t,n);this.positionMenuElement.style.left=`${s}px`,this.positionMenuElement.style.top=`${a}px`,document.addEventListener("pointerdown",this.handlePositionMenuOutsidePointerDown,!0),document.addEventListener("keydown",this.handlePositionMenuKeyDown,!0)}getPositionMenuCoordinates(t,e=null){const n=this.positionMenuElement.getBoundingClientRect();let i=t.clientX,s=t.clientY;if(e&&t.type==="click"&&t.detail===0){const l=e.getBoundingClientRect();i=l.left+l.width/2,s=l.bottom}const a=Math.min(Math.max(i,q),window.innerWidth-n.width-q),r=Math.min(Math.max(s,q),window.innerHeight-n.height-q);return{left:a,top:r}}renderPositionMenu(){if(!this.positionMenuElement||this.positionMenuTarget===null)return;const t=new Set(this.getAllowedPositionsForPositionMenuTarget(this.positionMenuTarget));this.positionMenuElement.querySelectorAll(Wo).forEach(e=>{const n=t.has(e.dataset.position);e.classList.toggle("champion-priority-selector__position-option--selected",n),e.setAttribute("aria-pressed",String(n))})}togglePositionMenuPosition(t){if(!this.positionMenuElement||this.positionMenuTarget===null)return;const e=x(t);if(!e)return;const n=this.positionMenuTarget,i=n.option,s=new Set(this.getAllowedPositionsForPositionMenuTarget(n));s.has(e)?s.delete(e):s.add(e);const a=D.map(A=>A.value).filter(A=>s.has(A));this.setAllowedPositionsForPositionMenuTarget(n,a),this.renderPositionMenu();const r=I(i),l=r?this.optionButtons.get(r):null,u=this.selectedPriorityOptions.indexOf(i);l&&u!==-1&&(P(i)?this.getRandomOptionButton(u):this.getChampionOptionButton(i,u)),this.saveConfig()}closePositionMenuOnOutsidePointerDown(t){var e;(e=this.positionMenuElement)!=null&&e.contains(t.target)||this.closePositionMenu()}closePositionMenuOnKeyDown(t){t.key==="Escape"&&this.closePositionMenu()}closePositionMenu(){this.positionMenuElement&&(this.positionMenuElement.hidden=!0,this.positionMenuTarget=null,document.removeEventListener("pointerdown",this.handlePositionMenuOutsidePointerDown,!0),document.removeEventListener("keydown",this.handlePositionMenuKeyDown,!0))}startDrag(t,e){var s;if(t.button===Ht){t.preventDefault();return}if(t.button!==Qo)return;this.dragState&&this.clearDragState();const n=I(e),i=n?this.optionButtons.get(n):null;if(i){this.dragState={option:e,pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,active:!1,moved:!1};try{(s=i.setPointerCapture)==null||s.call(i,t.pointerId)}catch{}window.addEventListener("pointermove",this.handleWindowPointerMove),window.addEventListener("pointerup",this.handleWindowPointerUp),window.addEventListener("pointercancel",this.handleWindowPointerCancel)}}removePriorityOptionOnMiddleClick(t,e){t.button===Ht&&(t.preventDefault(),t.stopPropagation(),this.removePriorityOption(e))}moveDrag(t){var A;if(!this.dragState||this.dragState.pointerId!==t.pointerId)return;const e=this.dragState.option,n=I(e),i=t.clientX-this.dragState.startX,s=t.clientY-this.dragState.startY,a=Math.hypot(i,s);if(!this.dragState.active){if(a<Zo)return;this.dragState.active=!0,n&&((A=this.optionButtons.get(n))==null||A.classList.add("champion-priority-selector__icon--dragging"))}t.preventDefault();const r=this.getDropIndex(t.clientX,e),l=this.selectedPriorityOptions.indexOf(e);if(r===l||r===-1)return;const u=this.getIconPositions();this.movePriorityOptionToIndex(e,r)&&(this.dragState.moved=!0,this.renderSelectedPriorityOptions(u,e))}finishDrag(t){if(!this.dragState||this.dragState.pointerId!==t.pointerId)return;const e=this.dragState.active,n=this.dragState.moved;this.clearDragState(),e&&n&&this.saveConfig()}cancelDrag(t){!this.dragState||this.dragState.pointerId!==t.pointerId||this.clearDragState()}clearDragState(){var s;if(!this.dragState)return;const{option:t,pointerId:e}=this.dragState,n=I(t),i=n?this.optionButtons.get(n):null;i==null||i.classList.remove("champion-priority-selector__icon--dragging");try{(s=i==null?void 0:i.releasePointerCapture)==null||s.call(i,e)}catch{}window.removeEventListener("pointermove",this.handleWindowPointerMove),window.removeEventListener("pointerup",this.handleWindowPointerUp),window.removeEventListener("pointercancel",this.handleWindowPointerCancel),this.dragState=null}getDropIndex(t,e){const n=this.selectedPriorityOptions.filter(i=>i!==e);for(let i=0;i<n.length;i++){const s=I(n[i]),a=s?this.optionButtons.get(s):null;if(!a)continue;const r=a.getBoundingClientRect();if(t<r.left+r.width/2)return i}return n.length}getIconPositions(){const t=new Map;for(const e of this.selectedPriorityOptions){const n=I(e),i=n?this.optionButtons.get(n):null;i&&t.set(n,i.getBoundingClientRect())}return t}animateReorder(t,e){for(const n of this.selectedPriorityOptions){if(n===e)continue;const i=I(n),s=i?this.optionButtons.get(i):null,a=i?t.get(i):null;if(!s||!a||typeof s.animate!="function")continue;const r=s.getBoundingClientRect(),l=a.left-r.left,u=a.top-r.top;l===0&&u===0||s.animate([{transform:`translate(${l}px, ${u}px)`},{transform:"translate(0, 0)"}],{duration:ti,easing:ei})}}}const ni=200,it="auto-select-champ-select-menu--collapsed",oi="auto-select-champ-select-menu-button-wrapper--open";class ii{constructor(t,e,n){this.element=document.createElement("div"),this.element.classList.add("auto-select-champ-select-menu",it),this.buttonWrapper=document.createElement("div"),this.buttonWrapper.classList.add("auto-select-champ-select-menu-button-wrapper"),this.headerElement=document.createElement("button"),this.headerElement.classList.add("auto-select-champ-select-menu__header"),this.headerElement.type="button",this.headerElement.setAttribute("aria-label",t),this.headerElement.setAttribute("aria-expanded","false"),this.headerElement.addEventListener("click",()=>this.toggle()),this.contentElement=document.createElement("div"),this.contentElement.classList.add("auto-select-champ-select-menu__content"),this.titleElement=document.createElement("div"),this.titleElement.classList.add("auto-select-champ-select-menu__title"),this.titleElement.textContent=t,this.titleAccessoryElement=null,this.buttonWrapper.append(this.headerElement,this.element),this.contentElement.appendChild(this.titleElement),this.element.appendChild(this.contentElement),this.returnControlsToSocialRoster=e,this.controlElements=n,this.boundCloseOnOutsideInteraction=i=>this.closeOnOutsideInteraction(i),this.buttonObserver=null,this.buttonMountFrame=null,this.buttonMountTask=null,this.hiddenStates=new WeakMap,this.mounted=!1}async mount(){return this.mounted?this.mountButton():(this.mounted=!0,this.controlElements.forEach(t=>{this.hiddenStates.set(t,t.classList.contains("hidden")),t.classList.remove("hidden"),this.contentElement.appendChild(t)}),this.observeButtonContainer(),document.addEventListener("pointerdown",this.boundCloseOnOutsideInteraction,!0),this.mountButton())}unmount(){return this.mounted?(this.mounted=!1,this.stopButtonMounting(),document.removeEventListener("pointerdown",this.boundCloseOnOutsideInteraction,!0),this.setOpen(!1),this.buttonWrapper.remove(),this.restoreHiddenStates(),this.returnControlsToSocialRoster()):this.returnControlsToSocialRoster()}stopButtonMounting(){var t;(t=this.buttonObserver)==null||t.disconnect(),this.buttonObserver=null,this.buttonMountFrame!==null&&(cancelAnimationFrame(this.buttonMountFrame),this.buttonMountFrame=null),this.buttonMountTask=null}restoreHiddenStates(){this.controlElements.forEach(t=>{t.classList.toggle("hidden",this.hiddenStates.get(t)===!0),this.hiddenStates.delete(t)})}isOpen(){return!this.element.classList.contains(it)}setOpen(t){this.element.classList.toggle(it,!t),this.buttonWrapper.classList.toggle(oi,t),this.headerElement.setAttribute("aria-expanded",String(t))}toggle(){this.setOpen(!this.isOpen())}closeOnOutsideInteraction(t){if(!this.isOpen())return;(typeof t.composedPath=="function"?t.composedPath():[]).includes(this.buttonWrapper)||this.buttonWrapper.contains(t.target)||this.setOpen(!1)}observeButtonContainer(){this.buttonObserver=new MutationObserver(()=>this.scheduleMountButton()),this.buttonObserver.observe(document.body,{childList:!0,subtree:!0})}scheduleMountButton(){this.buttonMountFrame===null&&(this.buttonMountFrame=requestAnimationFrame(()=>{this.buttonMountFrame=null,this.mountButton()}))}mountButton(){return this.buttonMountTask||(this.buttonMountTask=this.appendButtonToContainer().finally(()=>{this.buttonMountTask=null})),this.buttonMountTask}async appendButtonToContainer(){let t=ut();for(;this.mounted&&!t;)await v(ni),t=ut();if(!this.mounted||!t)return;const e=t.querySelector(d.firstChampSelectSquareButton);this.buttonWrapper.parentNode===t&&this.buttonWrapper.nextSibling===e||t.insertBefore(this.buttonWrapper,e)}setTitleAccessory(t){this.titleAccessoryElement=t,(!t.isConnected||t.parentNode!==this.titleElement)&&this.titleElement.appendChild(t)}}class st{constructor(t,e){this.element=document.createElement(w.radioInputOption),this.element.classList.add("lol-settings-voice-input-mode-option","auto-select-checkbox"),this.element.innerText=t,this.config=null,this.configKey=e,this.setupComplete=!1}setup(){this.syncFromConfig(),this.setupComplete||(this.element.addEventListener("click",()=>this.toggle()),this.setupComplete=!0)}syncFromConfig(){this.config=re(this.configKey),this.element.toggleAttribute("selected",this.config.enabled===!0)}toggle(){return console.debug("auto-champion-select: Toggling",this.configKey),this.config=R(this.configKey,t=>(t.enabled=!t.enabled,t)),this.element.toggleAttribute("selected",this.config.enabled===!0),this.config.enabled}}const si=224,ai="auto-select-settings-trigger",Gt="auto-select-settings-flyout",Yt="auto-select-settings-menu",ri="auto-select-settings-menu__empty",ci="auto-select-settings-checkbox",li="auto-select-settings-range",di="auto-select-settings-range__header",ui="auto-select-settings-range__label",hi="auto-select-settings-range__value",pi="auto-select-settings-range__track",mi="auto-select-settings-range__fill",gi="auto-select-settings-range__handle",fi="auto-select-settings-range__handle--min",yi="auto-select-settings-range__handle--max",j="auto-select-settings-range__handle--dragging";class Pi{constructor(t=[]){this.controls=t,this.triggerElements=new Set,this.flyoutElement=this.createFlyoutElement(),this.open=!1,this.activeTriggerElement=null,this.setupComplete=!1,this.boundCloseOnOutsideInteraction=e=>this.closeOnOutsideInteraction(e),this.boundCloseOnEscape=e=>this.closeOnEscape(e),this.boundPositionFlyout=()=>this.positionFlyout(),this.renderControls()}setup(){this.ensureFlyoutConnected(),this.controls.forEach(t=>{var e;return(e=t.setup)==null?void 0:e.call(t)}),this.sync(),!this.setupComplete&&(document.addEventListener("pointerdown",this.boundCloseOnOutsideInteraction,!0),document.addEventListener("keydown",this.boundCloseOnEscape,!0),window.addEventListener("resize",this.boundPositionFlyout),this.setupComplete=!0)}setControls(t){this.controls=t,this.renderControls(),this.setupComplete&&this.controls.forEach(e=>{var n;return(n=e.setup)==null?void 0:n.call(e)}),this.sync()}createTriggerElement(t=c("settings.triggerLabel")){const e=document.createElement("button");return e.type="button",e.classList.add(ai),e.dataset.autoSelectSettings="trigger",e.setAttribute("aria-label",t),e.setAttribute("aria-expanded","false"),e.title=t,e.addEventListener("click",n=>{n.preventDefault(),n.stopImmediatePropagation(),n.stopPropagation(),this.toggleFlyout(e)},!0),this.triggerElements.add(e),e}createFlyoutElement(){const t=document.createElement("lol-uikit-flyout-frame");t.classList.add("flyout",Gt),t.dataset.autoSelectSettings="flyout",t.setAttribute("orientation","bottom"),t.setAttribute("animated","true"),t.setAttribute("caretless","true"),t.style.position="fixed",t.style.overflow="visible",t.style.display="none";const e=document.createElement("lc-flyout-content"),n=document.createElement("div");return n.classList.add("social-options-menu","active",Yt),e.appendChild(n),t.appendChild(e),t}renderControls(){const t=this.flyoutElement.querySelector(`.${Yt}`);if(t){if(t.replaceChildren(),this.controls.length===0){const e=document.createElement("div");e.classList.add(ri),e.textContent=c("settings.empty"),t.appendChild(e);return}t.append(...this.controls.map(e=>e.element))}}sync(){this.controls.forEach(t=>{var e;return(e=t.sync)==null?void 0:e.call(t)})}ensureFlyoutConnected(){document.querySelectorAll(`.${Gt}`).forEach(t=>{t!==this.flyoutElement&&t.remove()}),this.flyoutElement.isConnected||document.body.appendChild(this.flyoutElement)}isOpen(){return this.open&&this.flyoutElement.isConnected&&getComputedStyle(this.flyoutElement).display!=="none"}setOpen(t,e=this.activeTriggerElement){this.open=t,this.activeTriggerElement=t?e:null,this.ensureFlyoutConnected(),this.flyoutElement.style.display=t?"block":"none",this.flyoutElement.toggleAttribute("show",t),this.triggerElements.forEach(n=>{n.setAttribute("aria-expanded",String(t&&n===this.activeTriggerElement))}),t&&(this.sync(),this.positionFlyout())}toggleFlyout(t){const e=!this.isOpen()||this.activeTriggerElement!==t;this.setOpen(e,t)}positionFlyout(){if(!this.isOpen()||!this.activeTriggerElement)return;const t=this.activeTriggerElement.getBoundingClientRect(),e=Math.min(si,window.innerWidth-16);this.flyoutElement.style.width=`${e}px`;const n=this.flyoutElement.getBoundingClientRect(),i=t.right-e+4,s=Math.max(8,Math.min(window.innerWidth-e-8,i)),a=t.bottom+4,r=a+n.height<=window.innerHeight-8?a:Math.max(8,t.top-n.height-4);this.flyoutElement.style.left=`${Math.round(s)}px`,this.flyoutElement.style.top=`${Math.round(r)}px`}closeOnOutsideInteraction(t){if(!this.isOpen())return;const e=typeof t.composedPath=="function"?t.composedPath():[],n=[...this.triggerElements].some(s=>e.includes(s)),i=e.includes(this.flyoutElement);!n&&!i&&this.setOpen(!1)}closeOnEscape(t){t.key==="Escape"&&this.isOpen()&&this.setOpen(!1)}}class F{constructor(t,e){this.label=t,this.options=e,this.element=document.createElement(w.radioInputOption),this.element.classList.add("lol-settings-voice-input-mode-option",ci),this.element.textContent=t,this.element.title=t,this.setupComplete=!1}setup(){this.sync(),!this.setupComplete&&(this.element.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.options.toggle(),this.sync()}),this.setupComplete=!0)}sync(){this.element.toggleAttribute("selected",this.options.isSelected()===!0)}}class Si{constructor(t,e){this.label=t,this.options=e,this.dragHandle=null,this.dragStartedCollapsed=!1,this.setupComplete=!1,this.boundPointerMove=i=>this.onPointerMove(i),this.boundPointerUp=()=>this.stopDragging(),this.element=document.createElement("div"),this.element.classList.add(li);const n=document.createElement("div");n.classList.add(di),this.labelElement=document.createElement("span"),this.labelElement.classList.add(ui),this.labelElement.textContent=t,this.valueElement=document.createElement("span"),this.valueElement.classList.add(hi),this.trackElement=document.createElement("div"),this.trackElement.classList.add(pi),this.fillElement=document.createElement("div"),this.fillElement.classList.add(mi),this.minHandleElement=this.createHandle("min"),this.maxHandleElement=this.createHandle("max"),n.append(this.labelElement,this.valueElement),this.trackElement.append(this.fillElement,this.minHandleElement,this.maxHandleElement),this.element.append(n,this.trackElement)}setup(){this.sync(),!this.setupComplete&&(this.trackElement.addEventListener("pointerdown",t=>this.onTrackPointerDown(t)),this.minHandleElement.addEventListener("pointerdown",t=>this.startDragging(t,"min")),this.maxHandleElement.addEventListener("pointerdown",t=>this.startDragging(t,"max")),this.minHandleElement.addEventListener("keydown",t=>this.onHandleKeyDown(t,"min")),this.maxHandleElement.addEventListener("keydown",t=>this.onHandleKeyDown(t,"max")),this.setupComplete=!0)}createHandle(t){const e=document.createElement("button");return e.type="button",e.classList.add(gi,t==="min"?fi:yi),e.setAttribute("aria-label",c("settings.handleLabel",{label:this.label,handle:c(`settings.handles.${t}`)})),e.setAttribute("aria-valuemin",String(this.options.min)),e.setAttribute("aria-valuemax",String(this.options.max)),e.setAttribute("role","slider"),e}getNormalizedValue(){const t=this.options.getValue(),e=this.snapValue(t.min),n=this.snapValue(t.max);return{min:Math.min(e,n),max:Math.max(e,n)}}snapValue(t){const e=this.options.min,n=this.options.max,i=this.options.step,s=Number(t),a=Number.isFinite(s)?s:e,r=Math.round((a-e)/i)*i+e;return Math.max(e,Math.min(n,r))}sync(){const t=this.getNormalizedValue(),e=this.valueToPercent(t.min),n=this.valueToPercent(t.max);this.valueElement.textContent=this.options.formatValue(t),this.fillElement.style.left=`${e}%`,this.fillElement.style.width=`${n-e}%`,this.minHandleElement.style.left=`${e}%`,this.maxHandleElement.style.left=`${n}%`,this.syncHandle(this.minHandleElement,t.min),this.syncHandle(this.maxHandleElement,t.max)}syncHandle(t,e){t.setAttribute("aria-valuenow",String(e)),t.setAttribute("aria-valuetext",this.options.formatValue({min:e,max:e}))}valueToPercent(t){const e=this.options.max-this.options.min;return e<=0?0:(t-this.options.min)/e*100}clientXToValue(t){const e=this.trackElement.getBoundingClientRect(),n=e.width<=0?0:(t-e.left)/e.width;return this.snapValue(this.options.min+(this.options.max-this.options.min)*n)}onTrackPointerDown(t){if(t.target===this.minHandleElement||t.target===this.maxHandleElement)return;const e=this.clientXToValue(t.clientX),n=this.getNormalizedValue(),i=Math.abs(e-n.min)<=Math.abs(e-n.max)?"min":"max";this.startDragging(t,i),this.setHandleValue(i,e)}startDragging(t,e){t.preventDefault(),t.stopPropagation(),this.dragHandle=e;const n=this.getNormalizedValue();this.dragStartedCollapsed=n.min===n.max,this.syncDraggingHandle(),document.addEventListener("pointermove",this.boundPointerMove,!0),document.addEventListener("pointerup",this.boundPointerUp,!0)}onPointerMove(t){if(!this.dragHandle)return;t.preventDefault();const e=this.clientXToValue(t.clientX),n=this.resolveDragHandleForValue(e);this.dragHandle=n,this.syncDraggingHandle(),this.setHandleValue(n,e)}stopDragging(){this.clearDraggingHandle(),this.dragHandle=null,this.dragStartedCollapsed=!1,document.removeEventListener("pointermove",this.boundPointerMove,!0),document.removeEventListener("pointerup",this.boundPointerUp,!0)}syncDraggingHandle(){this.minHandleElement.classList.toggle(j,this.dragHandle==="min"),this.maxHandleElement.classList.toggle(j,this.dragHandle==="max")}clearDraggingHandle(){this.minHandleElement.classList.remove(j),this.maxHandleElement.classList.remove(j)}onHandleKeyDown(t,e){const n=this.getNormalizedValue();let s=e==="min"?n.min:n.max;if(t.key==="ArrowLeft"||t.key==="ArrowDown")s-=this.options.step;else if(t.key==="ArrowRight"||t.key==="ArrowUp")s+=this.options.step;else if(t.key==="Home")s=this.options.min;else if(t.key==="End")s=this.options.max;else return;t.preventDefault(),this.setHandleValue(e,s)}resolveDragHandleForValue(t){if(!this.dragHandle)return"min";if(!this.dragStartedCollapsed)return this.dragHandle;const e=this.getNormalizedValue();return t<e.min?"min":t>e.max?"max":this.dragHandle}setHandleValue(t,e){const n=this.getNormalizedValue(),i=this.snapValue(e),s=t==="min"?{min:Math.min(i,n.max),max:n.max}:{min:n.min,max:Math.max(i,n.min)};this.options.setValue(s),this.sync()}}const Ai="auto-select-social-roster-section",qt="auto-select-social-roster-section__header";class Ci{constructor(t,...e){this.element=document.createElement(w.socialRosterGroup),this.element.classList.add(Ai),this.element.addEventListener("post-render",()=>this.onPostRender()),this.element.addEventListener("click",()=>this.onClick()),this.label=t,this.collapsibleElements=e,this.headerAccessoryElement=null,this.waitRender()}waitRender(){new MutationObserver((t,e)=>{if(this.element.querySelector(d.socialRosterGroupLabel)){const n=new Event("post-render");this.element.dispatchEvent(n),e.disconnect()}}).observe(this.element,{childList:!0})}onPostRender(){this.element.querySelector(d.socialRosterGroupLabel).innerText=this.label;const t=this.element.querySelector(d.socialRosterGroupHeader);t==null||t.removeAttribute("draggable"),t&&this.headerAccessoryElement&&(t.classList.add(qt),t.appendChild(this.headerAccessoryElement))}setHeaderAccessory(t){this.headerAccessoryElement=t;const e=this.element.querySelector(d.socialRosterGroupHeader);e&&(e.classList.add(qt),e.appendChild(t))}onClick(){var t;this.collapsibleElements.forEach(e=>{e.closest(".auto-select-champ-select-menu")||e.classList.toggle("hidden")}),(t=this.element.querySelector(d.socialRosterGroupArrow))==null||t.toggleAttribute("open")}}function ye(o){o&&Toast.success(o)}function mt(o){o&&Toast.error(o)}function bi(o,t){return typeof Toast.promise=="function"?Toast.promise(o,t):o}const At="Balaclava: Auto Champion Select";function Ct(){return c("commandBar.group")}function Ei(o){return typeof(o==null?void 0:o.then)=="function"}class bt{constructor({id:t,name:e,legend:n,tags:i,group:s,callback:a,toasts:r}){this.id=t,this.name=e,this.legend=n,this.tags=i,this.group=s,this.perform=this.perform.bind(this),this.callback=a,this.toasts=r}perform(){try{const t=this.callback();if(Ei(t))return bi(t,{loading:this.toasts.loading,success:this.toasts.success,error:this.toasts.error});const e=this.toasts.success||(t?this.toasts.on:this.toasts.off);ye(e)}catch(t){mt(this.toasts.error),console.error(t)}}}class Pe extends bt{constructor(t,e,n){super({id:`${e}Switch`,name:()=>c("commandBar.autoSwitchName",{name:t,state:y(e).enabled?c("states.on"):c("states.off")}),legend:()=>y(e).enabled?c("commandBar.turnOff"):c("commandBar.turnOn"),tags:[At,e,"switch"],group:Ct(),callback:n,toasts:{on:c("commandBar.autoSwitchOn",{name:t}),off:c("commandBar.autoSwitchOff",{name:t}),error:c("commandBar.autoSwitchError",{name:t})}})}}function Oi(o){return R(o,e=>(e.force=!e.force,e)).force}class Se extends bt{constructor(t){const e=t==="controladoPick",n=c(e?"commandBar.forcePickName":"commandBar.forceBanName");super({id:`${t}ForceSwitch`,name:()=>c("commandBar.forceSwitchName",{name:n,state:y(t).force?c("states.on"):c("states.off")}),legend:()=>c(e?"commandBar.forcePickLegend":"commandBar.forceBanLegend"),tags:[At,t,"force","intent","switch"],group:Ct(),callback:()=>Oi(t),toasts:{on:c("commandBar.forceSwitchOn",{name:n}),off:c("commandBar.forceSwitchOff",{name:n}),error:c("commandBar.forceSwitchError",{name:n})}})}}class wi extends bt{constructor(t){super({id:"RefreshDropdowns",name:()=>c("commandBar.refreshChampionsName"),legend:()=>c("commandBar.refreshChampionsLegend"),tags:[At,"refresh"],group:Ct(),callback:t,toasts:{success:c("commandBar.refreshChampionsSuccess"),error:c("commandBar.refreshChampionsError")}})}}class Ti extends Pe{constructor(t){super(c("actions.pick"),"controladoPick",t)}}class ki extends Pe{constructor(t){super(c("actions.ban"),"controladoBan",t)}}class Ii extends Se{constructor(){super("controladoPick")}}class Li extends Se{constructor(){super("controladoBan")}}function _i(o){for(const t of o)CommandBar.addAction(t)}const vi=200,Ri=6e4,jt=2e3,Mi=".ready-check-root-element",Ni="#lol-uikit-layer-manager-wrapper > .modal",Bi=".auto-select-champ-select-menu__header",g=Object.freeze({autoAccept:"controladoAutoAccept",actionDelay:"controladoActionDelay",pick:"controladoPick",ban:"controladoBan"});function Di(){return y(g.autoAccept).enabled===!0}function Ae(){return y(g.autoAccept).hideAutoAcceptPrompt===!0}function xi(){const o=y(g.autoAccept);return o.enabled===!0&&o.hideAutoAcceptPrompt===!0}function Fi(){const o=Ae();R(g.autoAccept,t=>(t.hideAutoAcceptPrompt=!o,t))}function Ce(o){return o==="pick"?g.pick:g.ban}function be(){return y(g.pick).pickIntent!==!1}function $i(){const o=be();R(g.pick,t=>(t.pickIntent=!o,t))}function Hi(){return y(g.pick).respectManualPick===!0}function zi(){R(g.pick,o=>(o.respectManualPick=o.respectManualPick!==!0,o))}function Kt(o){return y(Ce(o)).force===!0}function Wt(o){R(Ce(o),t=>(t.force=t.force!==!0,t))}function Vi(){const o=y(g.actionDelay),{minMs:t,maxMs:e}=z(o.minMs,o.maxMs);return{min:t,max:e}}function Ui(o){const{minMs:t,maxMs:e}=z(o.min,o.max);R(g.actionDelay,n=>(n.minMs=t,n.maxMs=e,n))}function Gi(o){const{minMs:t,maxMs:e}=z(o.min,o.max);return t===0&&e===0?c("settings.actionDelayValue.instant"):t===e?c("settings.actionDelayValue.exact",{delay:U(e)}):t===0?c("settings.actionDelayValue.upTo",{delay:U(e)}):c("settings.actionDelayValue.range",{min:U(t),max:U(e)})}class Yi{constructor(t){this.isEnabled=t,this.observer=null,this.hiddenModal=null,this.hiddenModalStyles=new WeakMap,this.sync=this.sync.bind(this)}start(){this.observer||(this.observer=new MutationObserver(()=>this.sync()),this.observer.observe(document.body,{childList:!0,subtree:!0}),this.sync())}sync(){const t=qi();if(!t){this.restore();return}if(!this.isEnabled()){this.restore();return}this.hide(t)}hide(t){this.hiddenModal!==t&&(this.restore(),this.hiddenModal=t,this.hiddenModalStyles.set(t,{display:t.style.getPropertyValue("display"),displayPriority:t.style.getPropertyPriority("display"),pointerEvents:t.style.getPropertyValue("pointer-events"),pointerEventsPriority:t.style.getPropertyPriority("pointer-events")}),t.style.setProperty("display","none","important"),t.style.setProperty("pointer-events","none","important"))}restore(){if(!this.hiddenModal)return;const t=this.hiddenModal,e=this.hiddenModalStyles.get(t);Xt(t,"display",e==null?void 0:e.display,e==null?void 0:e.displayPriority),Xt(t,"pointer-events",e==null?void 0:e.pointerEvents,e==null?void 0:e.pointerEventsPriority),this.hiddenModalStyles.delete(t),this.hiddenModal=null}}function qi(){const o=document.querySelector(Mi);return(o==null?void 0:o.closest(Ni))||null}function Xt(o,t,e,n){e?o.style.setProperty(t,e,n||""):o.style.removeProperty(t)}async function ji(o){function t(){return Di()?!1:(o.restore(),!0)}if(t()||(console.debug(`auto-champion-select(auto-accept): Ready check detected, accepting in ${jt}ms...`),await v(jt),t()))return;let e=!1;try{e=await Ki()}catch(n){throw o.restore(),mt(c("toasts.readyCheckAcceptFailed")),n}e?ye(c("toasts.readyCheckAccepted")):(o.restore(),mt(c("toasts.readyCheckAcceptFailed")))}async function Ki(){const o=await O("POST",f.readyCheckAccept);return o.ok?(console.debug("auto-champion-select(auto-accept): Accepted ready check"),!0):(console.error("auto-champion-select(auto-accept): Failed to accept ready check",o),!1)}async function Wi(o){const t=await O("GET",f.gameflowPhase),e=t.ok?await t.json():null;o.handleGameflowPhase(e)}function Xi({championSelect:o,champSelectControlsMenu:t,readyCheckModalSuppressor:e,setupChampionSelectors:n}){let i=0;return async function(l){const u=++i;try{await s(l,u)}catch(A){console.error("auto-champion-select: Failed to handle gameflow phase",A)}};async function s(r,l){r==="ReadyCheck"?ji(e).catch(u=>{console.error("auto-champion-select(auto-accept): Failed to handle ready check",u)}):e.restore(),await a(r),l===i&&await n()}async function a(r){r==="ChampSelect"?(o.mount(),await t.mount()):(o.unmount(),await t.unmount())}}function Ji(){const o=new Ze,t=new st(c("toggles.autoAccept"),g.autoAccept),e=new st(c("toggles.pick"),g.pick),n=new Ut(c("selectors.pickPlaceholder"),g.pick,Ke,{enablePositionRestrictions:!0,enableRandomAssignedPositionRestrictions:!0,enableBraveryOption:!0,enableRandomPoolPositionFilters:!0}),i=new st(c("toggles.ban"),g.ban),s=new Ut(c("selectors.banPlaceholder"),g.ban,le,{enableRandomPoolPositionFilters:!0}),a=Zi(n,s),r=ts(t,e,i),l=new Pi,u=new Ci(c("plugin.socialRosterTitle"),a,r);return u.setHeaderAccessory(l.createTriggerElement()),{championSelect:o,autoAcceptToggle:t,pickToggle:e,banToggle:i,pickChampionSelector:n,banChampionSelector:s,selectorsContainer:a,checkboxesContainer:r,pluginSection:u,settingsMenu:l,championSelectors:[n,s]}}function Qi(o){return[new Si(c("settings.actionDelay"),{min:Zt,max:te,step:at,getValue:Vi,setValue:Ui,formatValue:Gi}),new F(c("settings.pickIntent"),{isSelected:()=>be(),toggle:()=>$i()}),new F(c("settings.respectManualPick"),{isSelected:()=>Hi(),toggle:()=>zi()}),new F(c("settings.forcePick"),{isSelected:()=>Kt("pick"),toggle:()=>Wt("pick")}),new F(c("settings.forceBan"),{isSelected:()=>Kt("ban"),toggle:()=>Wt("ban")}),new F(c("settings.hideAutoAcceptPrompt"),{isSelected:()=>Ae(),toggle:()=>{Fi(),o.sync()}})]}function Zi(...o){const t=document.createElement("div");return t.append(...o.map(e=>e.element)),t}function ts(...o){const t=document.createElement("div");return t.classList.add("auto-select-checkboxes-div"),t.append(...o.map(e=>e.element)),t}function es({pluginSection:o,checkboxesContainer:t,selectorsContainer:e}){let n=null,i=0,s=()=>!1;async function a(r){let l=vt();for(;!l;){if(s()||r!==i)return;await v(vi),l=vt()}s()||r!==i||l.append(o.element,t,e)}return{setIsChampSelectControlsMounted(r){s=r},returnControlsToSocialRoster(){if(n)return n;const r=++i;return n=a(r).catch(l=>console.error("auto-champion-select: Failed to return controls to social roster",l)).finally(()=>{n=null}),n}}}function ns({autoAcceptToggle:o,pickToggle:t,banToggle:e,readyCheckModalSuppressor:n}){o.setup(),o.element.addEventListener("click",()=>n.sync()),t.setup(),e.setup()}async function os(o){await Promise.all(o.map(t=>t.setup()))}async function is(o){await Promise.all(o.map(t=>t.refresh()))}function ss(){const o=Ji(),t=new Yi(xi);o.settingsMenu.setControls(Qi(t));const e=es(o),n=new ii(c("plugin.champSelectMenuTitle"),e.returnControlsToSocialRoster,[o.checkboxesContainer,o.selectorsContainer]);n.setTitleAccessory(o.settingsMenu.createTriggerElement()),e.setIsChampSelectControlsMounted(()=>n.mounted);const i={...o,champSelectControlsMenu:n,readyCheckModalSuppressor:t,setupToggles:()=>ns({...o,readyCheckModalSuppressor:t}),setupSettingsMenu:()=>o.settingsMenu.setup(),setupChampionSelectors:()=>os(o.championSelectors),refreshChampionSelectors:()=>is(o.championSelectors),refreshPickChampionSelector:async()=>{await o.pickChampionSelector.refresh()}};return i.handleGameflowPhase=Xi(i),i}function as(o){Et(f.gameflowPhase,t=>{o.handleGameflowPhase(t.data)}),Et(f.wallet,async t=>{if(t.eventType==="Update"){console.debug("auto-champion-select(wallet): Refreshing champion selectors...");try{await o.refreshPickChampionSelector()}catch(e){console.error("auto-champion-select(wallet): Failed to refresh champion selectors",e)}}})}function rs({pickToggle:o,banToggle:t,refreshChampionSelectors:e}){_i([new Ti(()=>o.toggle()),new ki(()=>t.toggle()),new Ii,new Li,new wi(e)])}function cs(o){let t=null,e=null;function n(){e==null||e.disconnect(),e=null,t!==null&&(cancelAnimationFrame(t),t=null)}const i=setTimeout(()=>{n()},Ri);function s(){if(!(ut()!==null))return;clearTimeout(i),n(),document.querySelector(Bi)!==null||o.handleGameflowPhase("ChampSelect")}e=new MutationObserver(()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,s()}))}),e.observe(document.body,{childList:!0,subtree:!0}),s()}async function ls(){await $o();const o=ss();o.setupToggles(),o.setupSettingsMenu(),o.readyCheckModalSuppressor.start(),rs(o),as(o),await Wi(o),cs(o),console.debug(`auto-champion-select(${Ee}): Report bugs to Balaclava#1912`)}let Jt=!1;function Qt(){Jt||(Jt=!0,ls().catch(o=>console.error("auto-champion-select: Failed to initialize",o)))}document.readyState==="loading"?window.addEventListener("load",Qt,{once:!0}):Qt();export{Qt as load};
|
|
192
|
+
`;function nt(o){const t=document.createElement(w.dropdownOption);return t.setAttribute("slot",w.dropdownOption),t.innerText=o,t}class Wo{constructor(t,e,n,i={}){this.dropdownElement=t,this.placeholderText=e,this.searchPlaceholderText=i.searchPlaceholderText||c("selectors.search"),this.staticOptions=Array.isArray(i.staticOptions)?i.staticOptions:[],this.onPriorityOptionSelected=n,this.placeholderOption=null,this.searchQuery="",this.activePositionFilter=null,this.hasRecommendedPositionData=!1,this.recommendedPositionsByOption=new WeakMap,this.staticOptionElements=new WeakSet}renderOptions(t){this.dropdownElement.replaceChildren(),this.hasRecommendedPositionData=!1,this.staticOptionElements=new WeakSet,this.placeholderOption=nt(this.placeholderText),this.placeholderOption.setAttribute("selected","true"),this.hidePlaceholderOption(),this.dropdownElement.appendChild(this.placeholderOption);for(const e of this.staticOptions)this.dropdownElement.appendChild(this.createStaticOption(e));for(const e of t){const n=this.getChampionRecommendedPositions(e),i=this.createChampionOption(e,n);n.length>0&&(this.hasRecommendedPositionData=!0),this.dropdownElement.appendChild(i)}this.hasRecommendedPositionData||(this.activePositionFilter=null),this.applyOptionFilters()}createChampionOption(t,e){const n=nt("");return this.recommendedPositionsByOption.set(n,new Set(e)),n.title=t.name,n.appendChild(this.createChampionOptionContent(t)),n.addEventListener("click",()=>{this.onPriorityOptionSelected(t.id),requestAnimationFrame(()=>this.reset())}),n}createStaticOption(t){const e=nt(""),n=typeof t.description=="string"?t.description:"";return this.staticOptionElements.add(e),e.title=n?`${t.label}. ${n}`:t.label,e.appendChild(this.createStaticOptionContent(t,n)),e.addEventListener("click",()=>{this.onPriorityOptionSelected(t.value),requestAnimationFrame(()=>this.reset())}),e}createChampionOptionContent(t){const e=document.createElement("span");e.classList.add(Bt);const n=document.createElement("img");n.classList.add(Dt),n.src=t.squarePortraitPath,n.alt="",n.draggable=!1,n.loading="lazy";const i=document.createElement("span");return i.classList.add(xt),i.innerText=t.name,e.append(n,i),e}createStaticOptionContent(t,e=""){const n=document.createElement("span");n.classList.add(Bt);const i=t.iconPath?document.createElement("img"):document.createElement("span");i.classList.add(Dt),t.iconClass&&i.classList.add(t.iconClass),t.iconPath?(i.src=t.iconPath,i.alt="",i.draggable=!1,i.loading="lazy"):(i.classList.add(Ko),i.innerText=t.iconText||"?");const s=document.createElement("span");s.classList.add(xt),s.innerText=t.label;const a=document.createElement("span");if(a.classList.add(qo),a.appendChild(s),e){const r=document.createElement("span");r.classList.add(jo),r.innerText=e,a.appendChild(r)}return n.append(i,a),n}getChampionRecommendedPositions(t){return Array.isArray(t.recommendedPositions)?t.recommendedPositions:[]}async waitForRender(){for(let t=0;t<Go;t++){const e=this.dropdownElement.shadowRoot;if(this.dropdownElement.isConnected&&(e!=null&&e.querySelector(d.dropdownCurrent)))return e;await v(Yo)}return null}ensureSearchPlaceholder(t){if(t.querySelector(`#${Mt}`))return;const e=t.querySelector(d.dropdownCurrent);e&&e.appendChild(this.createSearchPlaceholder())}ensurePositionFilter(t){var n;const e=t.querySelector(d.dropdownOptionsContainer);if(e){if(!this.hasRecommendedPositionData){(n=t.querySelector(`.${K}`))==null||n.remove(),e.classList.remove(pt),this.activePositionFilter=null;return}e.classList.add(pt),t.querySelector(`.${K}`)||e.insertBefore(this.createPositionFilter(),e.firstChild),this.syncPositionFilter(t)}}createPositionFilter(){const t=document.createElement("div");t.classList.add(K),t.setAttribute("role","toolbar"),t.setAttribute("aria-label",c("selectors.positionFilterLabel"));for(const e of x)t.appendChild(this.createPositionFilterBadge(e));return t}createPositionFilterBadge(t){const e=Q(t),n=document.createElement("button");n.classList.add(_),n.type="button",n.dataset.position=t.value,n.title=e,n.setAttribute("aria-label",e),n.setAttribute("aria-pressed","false");const i=document.createElement("img");return i.src=t.iconPath,i.alt="",i.draggable=!1,n.appendChild(i),n.addEventListener("pointerdown",s=>{s.preventDefault(),s.stopPropagation()}),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.togglePositionFilter(t.value)}),n}createSearchPlaceholder(){const t=document.createElement("div");t.classList.add(fe,ge),t.id=Mt;const e=document.createElement("input");e.classList.add(me),e.id=Nt,e.type="text",e.placeholder=this.searchPlaceholderText,e.setAttribute("aria-label",this.searchPlaceholderText),e.size=Math.max(this.searchPlaceholderText.length,1);const n=document.createElement("span");return n.classList.add(ye),n.addEventListener("click",()=>{n.classList.contains(D)&&this.clearSearch(e,n)}),e.addEventListener("input",i=>{this.ensureOpen(),this.setSearchQuery(i.target.value),n.classList.toggle(D,!!i.target.value)}),["pointerdown","click"].forEach(i=>{t.addEventListener(i,s=>s.stopPropagation()),n.addEventListener(i,s=>s.stopPropagation())}),["pointerdown","focusin"].forEach(i=>{e.addEventListener(i,s=>s.stopPropagation(),!0)}),t.appendChild(n),t.appendChild(e),t}togglePositionFilter(t){const e=F(t);e&&(this.activePositionFilter=this.activePositionFilter===e?null:e,this.withShadowRoot(n=>this.syncPositionFilter(n)),this.applyOptionFilters())}syncPositionFilter(t){t.querySelectorAll(`.${_}`).forEach(e=>{const n=e.dataset.position===this.activePositionFilter;e.classList.toggle(mt,n),e.setAttribute("aria-pressed",String(n))})}clearSearch(t,e){t.value="",this.setSearchQuery(""),e.classList.toggle(D,!1)}setSearchQuery(t){this.searchQuery=t,this.applyOptionFilters()}applyOptionFilters(){const t=this.searchQuery.toLowerCase();this.dropdownElement.querySelectorAll(d.dropdownOption).forEach(n=>{if(n===this.placeholderOption){this.hidePlaceholderOption();return}this.matchesSearchQuery(n,t)&&this.matchesPositionFilter(n)?n.style.display="":n.style.display="none"})}matchesSearchQuery(t,e){return(t.textContent??"").toLowerCase().includes(e)}matchesPositionFilter(t){var e;return this.staticOptionElements.has(t)||!this.activePositionFilter?!0:((e=this.recommendedPositionsByOption.get(t))==null?void 0:e.has(this.activePositionFilter))===!0}hidePlaceholderOption(){this.placeholderOption&&(this.placeholderOption.style.display="none")}reset(){var t;this.dropdownElement.querySelectorAll(d.dropdownOptionSelected).forEach(e=>{e.removeAttribute("selected")}),(t=this.placeholderOption)==null||t.setAttribute("selected","true"),this.withShadowRoot(e=>{var s;const n=e.querySelector(`#${Nt}`),i=e.querySelector(`.${D}`);n&&i?this.clearSearch(n,i):(n&&(n.value="",this.setSearchQuery("")),i&&i.classList.remove(D)),this.isOpen()&&((s=e.querySelector(d.dropdownCurrent))==null||s.click())})}isOpen(){return this.dropdownElement.classList.contains("active")}ensureOpen(){this.isOpen()||this.withShadowRoot(t=>{const e=t.querySelector(d.dropdownCurrent);e&&e.click()})}patchDropdownShadowDom(){this.withShadowRoot(t=>{this.ensureDropdownOpensUpward(t),this.injectDropdownSearchStyles(t),this.ensurePositionFilter(t)})}ensureDropdownOpensUpward(t){var e;(e=t.querySelector(d.dropdownRoot))==null||e.classList.add("opens-upward")}injectDropdownSearchStyles(t){const e=t.querySelector("style[data-controlado='dropdown-tags']");if(e){e.textContent=Ft;return}const n=document.createElement("style");n.dataset.controlado="dropdown-tags",n.textContent=Ft,t.appendChild(n)}withShadowRoot(t){const e=this.dropdownElement.shadowRoot;e&&t(e)}}const Xo=".champion-priority-selector__position-badge",Jo=".champion-priority-selector__position-option",ot=".champion-priority-selector__remove",it="✕",$t="?",Ht="/fe/lol-champ-select/images/champion-grid/bravery-champion.png",Qo="controlado-champion-option__icon--bravery",Zo="champion-priority-selector__icon--bravery",ti=0,zt=1,q=8,p=Object.freeze({CHAMPION_ASSIGNED:"champion-assigned",RANDOM_ASSIGNED:"random-assigned",RANDOM_POOL:"random-pool"}),ei=5,ni=150,oi="cubic-bezier(0.2, 0, 0, 1)";function Vt(){return c("selectors.random.label")}function Ut(){return c("selectors.bravery.label")}class Gt{constructor(t,e,n,i={}){this.element=this.createRootElement(),this.dropdownElement=this.createDropdownElement();const s=[];i.enableBraveryOption===!0&&s.push({value:L,label:Ut(),description:c("selectors.bravery.description"),iconPath:Ht,iconClass:Qo}),s.push({value:E,label:Vt(),iconText:$t}),this.championDropdown=new Wo(this.dropdownElement,t,l=>this.addPriorityOption(l),{searchPlaceholderText:i.searchPlaceholderText,staticOptions:s});const{scrollElement:a,trackElement:r}=this.createSelectedChampionsScroll();this.scrollElement=a,this.trackElement=r,this.enablePositionRestrictions=i.enablePositionRestrictions===!0,this.enableRandomPoolPositionFilters=i.enableRandomPoolPositionFilters===!0,this.enableRandomAssignedPositionRestrictions=i.enableRandomAssignedPositionRestrictions===!0,this.enableBraveryOption=i.enableBraveryOption===!0,this.enablePositionMenu=this.enablePositionRestrictions||this.enableRandomAssignedPositionRestrictions||this.enableRandomPoolPositionFilters,this.positionMenuElement=this.enablePositionMenu?this.createPositionMenu():null,this.positionMenuTarget=null,this.positionsByChampionId={},this.randomAssignedPositions=[],this.randomPoolPositions=[],this.emptyElement=this.createEmptyState(e),this.element.append(this.dropdownElement,this.scrollElement),this.positionMenuElement&&this.element.appendChild(this.positionMenuElement),this.config=null,this.configKey=e,this.loadChampions=n,this.champions=[],this.championById=new Map,this.selectedPriorityOptions=[],this.optionButtons=new Map,this.dragState=null,this.handleWindowPointerMove=l=>this.moveDrag(l),this.handleWindowPointerUp=l=>this.finishDrag(l),this.handleWindowPointerCancel=l=>this.cancelDrag(l),this.handlePositionMenuOutsidePointerDown=l=>this.closePositionMenuOnOutsidePointerDown(l),this.handlePositionMenuKeyDown=l=>this.closePositionMenuOnKeyDown(l),this.setupInFlight=null,this.setupPending=!1}createRootElement(){const t=document.createElement("div");return t.classList.add("champion-priority-selector"),t}createDropdownElement(){const t=document.createElement(w.dropdown);return t.classList.add("dropdown-champions-default","dropdown-drop-up"),t}createSelectedChampionsScroll(){const t=document.createElement(w.scrollable);t.classList.add("champion-priority-selector__scroll"),t.setAttribute("direction","horizontal"),t.setAttribute("overflow-masks","disabled"),t.setAttribute("side-scroll-wheel","true");const e=document.createElement("div");return e.classList.add("champion-priority-selector__track"),t.appendChild(e),{scrollElement:t,trackElement:e}}createEmptyState(t){const e=document.createElement("div");e.classList.add("champion-priority-selector__empty");const n=document.createElement("span");n.innerText=c("selectors.emptyTitle");const i=document.createElement("span");return i.innerText=c(t==="controladoPick"?"selectors.pickEmptyHint":"selectors.banEmptyHint"),e.append(n,i),e}createPositionMenu(){const t=document.createElement("div");t.classList.add("champion-priority-selector__position-menu"),t.hidden=!0;for(const e of x)t.appendChild(this.createPositionOption(e));return t}createPositionOption(t){const e=Q(t),n=document.createElement("button");n.classList.add("champion-priority-selector__position-option"),n.type="button",n.dataset.position=t.value,n.title=e,n.setAttribute("aria-label",e),n.setAttribute("aria-pressed","false"),n.addEventListener("pointerdown",s=>s.stopPropagation()),n.addEventListener("click",s=>{s.stopPropagation(),this.togglePositionMenuPosition(t.value)});const i=document.createElement("img");return i.src=t.iconPath,i.alt=e,i.draggable=!1,n.appendChild(i),n}async setup(){return this.setupPending=!0,this.setupInFlight||(this.setupInFlight=this.runSetupLoop()),this.setupInFlight}refresh(){return this.setup()}async runSetupLoop(){try{for(;this.setupPending;)this.setupPending=!1,await this.performSetup()}finally{this.setupInFlight=null}}async performSetup(){this.champions=await this.loadChampions(),this.championById=new Map(this.champions.map(n=>[n.id,n]));const t=this.getAllowedChampionIds();this.config=ce(this.configKey,{allowedChampionIds:t}),this.selectedPriorityOptions=ft(this.config.priorityOptions||this.config.champions,t).filter(n=>this.isPriorityOptionEnabled(n)),this.enablePositionRestrictions&&(this.positionsByChampionId=W(this.config.positionsByChampionId,H(this.selectedPriorityOptions))),this.enableRandomAssignedPositionRestrictions&&(this.randomAssignedPositions=T(this.config.randomAssignedPositions)),this.enableRandomPoolPositionFilters&&(this.randomPoolPositions=T(this.config.randomPoolPositions)),this.championDropdown.renderOptions(this.champions),this.renderSelectedPriorityOptions();const e=await this.championDropdown.waitForRender();e&&(this.championDropdown.ensureSearchPlaceholder(e),this.championDropdown.patchDropdownShadowDom())}getAllowedChampionIds(){return new Set(this.championById.keys())}isPriorityOptionEnabled(t){return!k(t)||this.enableBraveryOption}addPriorityOption(t){const e=M(t);e===null||this.selectedPriorityOptions.includes(e)||!this.isPriorityOptionEnabled(e)||!P(e)&&!k(e)&&!this.championById.has(e)||(this.selectedPriorityOptions.push(e),this.renderSelectedPriorityOptions(),this.saveConfig())}removePriorityOption(t){var s;const e=M(t),n=this.selectedPriorityOptions.indexOf(e);if(e===null||n===-1)return;this.selectedPriorityOptions.splice(n,1);const i=typeof e=="number"?e:null;((s=this.positionMenuTarget)==null?void 0:s.option)===e&&this.closePositionMenu(),this.enablePositionRestrictions&&i!==null&&delete this.positionsByChampionId[String(i)],this.enableRandomAssignedPositionRestrictions&&P(e)&&(this.randomAssignedPositions=[]),this.enableRandomPoolPositionFilters&&P(e)&&(this.randomPoolPositions=[]),this.renderSelectedPriorityOptions(),this.saveConfig()}movePriorityOptionToIndex(t,e){const n=M(t),i=this.selectedPriorityOptions.indexOf(n);if(n===null||i===-1)return!1;const[s]=this.selectedPriorityOptions.splice(i,1),a=Math.max(0,Math.min(e,this.selectedPriorityOptions.length));return this.selectedPriorityOptions.splice(a,0,s),i!==a}syncPositionsByChampionId(){this.enablePositionRestrictions&&(this.positionsByChampionId=W(this.positionsByChampionId,H(this.selectedPriorityOptions)))}syncRandomPoolPositions(){this.enableRandomPoolPositionFilters&&(this.randomPoolPositions=T(this.randomPoolPositions))}syncRandomAssignedPositions(){this.enableRandomAssignedPositionRestrictions&&(this.randomAssignedPositions=T(this.randomAssignedPositions))}saveConfig(){this.syncPositionsByChampionId(),this.syncRandomAssignedPositions(),this.syncRandomPoolPositions();const t=this.getAllowedChampionIds();this.config=R(this.configKey,e=>(e.priorityOptions=[...this.selectedPriorityOptions],e.champions=H(this.selectedPriorityOptions),this.enableRandomAssignedPositionRestrictions&&(e.randomAssignedPositions=[...this.randomAssignedPositions]),this.enableRandomPoolPositionFilters&&(e.randomPoolPositions=[...this.randomPoolPositions]),this.enablePositionRestrictions&&(e.positionsByChampionId={...this.positionsByChampionId}),e),{allowedChampionIds:t,selectedChampionIds:H(this.selectedPriorityOptions)}),this.enablePositionRestrictions&&(this.positionsByChampionId=this.config.positionsByChampionId||{}),this.enableRandomAssignedPositionRestrictions&&(this.randomAssignedPositions=this.config.randomAssignedPositions||[]),this.enableRandomPoolPositionFilters&&(this.randomPoolPositions=this.config.randomPoolPositions||[]),console.debug(this.configKey,this.config)}renderSelectedPriorityOptions(t=null,e=null){this.positionMenuTarget!==null&&this.closePositionMenu();const n=new Set(this.selectedPriorityOptions.map(s=>I(s)));for(const[s,a]of this.optionButtons)n.has(s)||(a.remove(),this.optionButtons.delete(s));if(this.selectedPriorityOptions.length===0){this.trackElement.replaceChildren(this.emptyElement);return}this.emptyElement.remove();const i=this.selectedPriorityOptions.map((s,a)=>this.getPriorityOptionButton(s,a)).filter(Boolean);this.trackElement.append(...i),t&&this.animateReorder(t,e)}getPriorityOptionButton(t,e){return P(t)?this.getRandomOptionButton(e):k(t)?this.enableBraveryOption?this.getBraveryOptionButton(e):null:this.getChampionOptionButton(t,e)}getChampionOptionButton(t,e){const n=this.championById.get(t);if(!n)return null;const i=String(t);let s=this.optionButtons.get(i);s||(s=this.createIconButton(n),this.optionButtons.set(i,s)),s.dataset.rank=String(e+1),s.classList.toggle("champion-priority-selector__icon--random",!1);const a=this.getChampionPositionTitleSuffix(t);s.title=`${e+1}. ${n.name}${a}`,s.setAttribute("aria-label",`${e+1}. ${n.name}${a}`);const r=s.querySelector("img");r.src=n.squarePortraitPath,r.alt=n.name;const l=s.querySelector(ot);return l.setAttribute("aria-label",c("selectors.remove",{name:n.name})),l.title=c("selectors.remove",{name:n.name}),this.renderPositionBadge(s,t),s}getRandomOptionButton(t){let e=this.optionButtons.get(E);e||(e=this.createRandomOptionButton(),this.optionButtons.set(E,e)),e.dataset.rank=String(t+1);const n=Vt(),i=this.getRandomPositionTitleSuffix();e.title=`${t+1}. ${n}${i}`,e.setAttribute("aria-label",`${t+1}. ${n}${i}`);const s=e.querySelector(ot);return s.setAttribute("aria-label",c("selectors.remove",{name:n})),s.title=c("selectors.remove",{name:n}),this.renderPositionBadge(e,E),e}getBraveryOptionButton(t){let e=this.optionButtons.get(L);e||(e=this.createBraveryOptionButton(),this.optionButtons.set(L,e)),e.dataset.rank=String(t+1);const n=Ut();e.title=`${t+1}. ${n}`,e.setAttribute("aria-label",`${t+1}. ${n}`);const i=e.querySelector("img");i.src=Ht,i.alt=n;const s=e.querySelector(ot);return s.setAttribute("aria-label",c("selectors.remove",{name:n})),s.title=c("selectors.remove",{name:n}),e}createIconButton(t){const e=document.createElement("div");e.classList.add("champion-priority-selector__icon"),e.setAttribute("role","button"),e.tabIndex=0;const n=document.createElement("img");n.draggable=!1;const i=document.createElement("button");if(i.classList.add("champion-priority-selector__remove"),i.type="button",i.dataset.icon=it,i.addEventListener("pointerdown",s=>s.stopPropagation()),i.addEventListener("click",s=>{s.stopPropagation(),this.removePriorityOption(t.id)}),e.addEventListener("pointerdown",s=>this.startDrag(s,t.id)),e.addEventListener("auxclick",s=>this.removePriorityOptionOnMiddleClick(s,t.id)),this.enablePositionRestrictions){const s={option:t.id,kind:p.CHAMPION_ASSIGNED};e.addEventListener("contextmenu",a=>this.openPositionMenu(a,s))}return e.append(n,i),e}createRandomOptionButton(){const t=document.createElement("div");t.classList.add("champion-priority-selector__icon","champion-priority-selector__icon--random"),t.setAttribute("role","button"),t.tabIndex=0;const e=document.createElement("span");e.classList.add("champion-priority-selector__random-icon"),e.innerText=$t;const n=document.createElement("button");if(n.classList.add("champion-priority-selector__remove"),n.type="button",n.dataset.icon=it,n.addEventListener("pointerdown",i=>i.stopPropagation()),n.addEventListener("click",i=>{i.stopPropagation(),this.removePriorityOption(E)}),t.addEventListener("pointerdown",i=>this.startDrag(i,E)),t.addEventListener("auxclick",i=>this.removePriorityOptionOnMiddleClick(i,E)),this.enableRandomPoolPositionFilters){const i={option:E,kind:p.RANDOM_POOL};t.addEventListener("contextmenu",s=>this.openPositionMenu(s,i))}return t.append(e,n),t}createBraveryOptionButton(){const t=document.createElement("div");t.classList.add("champion-priority-selector__icon",Zo),t.setAttribute("role","button"),t.tabIndex=0;const e=document.createElement("img");e.draggable=!1;const n=document.createElement("button");return n.classList.add("champion-priority-selector__remove"),n.type="button",n.dataset.icon=it,n.addEventListener("pointerdown",i=>i.stopPropagation()),n.addEventListener("click",i=>{i.stopPropagation(),this.removePriorityOption(L)}),t.addEventListener("pointerdown",i=>this.startDrag(i,L)),t.addEventListener("auxclick",i=>this.removePriorityOptionOnMiddleClick(i,L)),t.append(e,n),t}getChampionAllowedPositions(t){const e=m(t);return e===null?[]:this.positionsByChampionId[String(e)]||[]}getRandomPoolPositions(){return this.randomPoolPositions}getRandomAssignedPositions(){return this.randomAssignedPositions}getPositionLabels(t){return t.map(e=>Uo(e)).filter(Boolean)}getChampionAllowedPositionLabels(t){return this.getPositionLabels(this.getChampionAllowedPositions(t))}getRandomPoolPositionLabels(){return this.getPositionLabels(this.getRandomPoolPositions())}getRandomAssignedPositionLabels(){return this.getPositionLabels(this.getRandomAssignedPositions())}getChampionPositionTitleSuffix(t){const e=this.getChampionAllowedPositionLabels(t);return e.length>0?` (${e.join(", ")})`:""}getRandomPositionTitleSuffix(){const t=[],e=this.getRandomAssignedPositionLabels(),n=this.getRandomPoolPositionLabels();return e.length>0&&t.push(c("selectors.random.assignedTitlePart",{positions:this.formatPositionLabelsForSentence(e)})),n.length>0&&t.push(c("selectors.random.poolTitlePart",{positions:this.formatPositionLabelsForSentence(n)})),t.length>0?` (${t.join("; ")})`:""}formatPositionLabelsForSentence(t){return Vo(t)}renderPositionBadge(t,e){t.querySelectorAll(Xo).forEach(i=>i.remove());const n=M(e);if(n!==null)for(const i of this.getPositionBadgeTargetsForOption(n)){const s=this.createPositionBadge(i);s&&t.appendChild(s)}}getPositionBadgeTargetsForOption(t){return this.selectedPriorityOptions.includes(t)?P(t)?[{option:t,kind:p.RANDOM_ASSIGNED},{option:t,kind:p.RANDOM_POOL}].filter(e=>this.canOpenPositionMenuForTarget(e)):k(t)?[]:[{option:t,kind:p.CHAMPION_ASSIGNED}].filter(e=>this.canOpenPositionMenuForTarget(e)):[]}createPositionBadge(t){const e=this.getAllowedPositionsForPositionMenuTarget(t),n=this.getAllowedPositionLabelsForPositionMenuTarget(t),i=t.kind===p.RANDOM_POOL,s=document.createElement("button");if(s.classList.add("champion-priority-selector__position-badge"),s.classList.toggle("champion-priority-selector__position-badge--random",i),s.type="button",s.dataset.positionTarget=t.kind,s.title=this.getPositionBadgeTitle(n,t),s.setAttribute("aria-label",s.title),s.addEventListener("pointerdown",l=>l.stopPropagation()),s.addEventListener("click",l=>this.openPositionMenu(l,t,s)),i)return e.length>0?(s.classList.add("champion-priority-selector__position-badge--active"),s.dataset.count=String(e.length)):s.classList.add("champion-priority-selector__position-badge--empty"),s;if(e.length===0)return s.classList.add("champion-priority-selector__position-badge--empty"),s.innerText="+",s;const a=ne(e[0]);if(!a)return null;e.length>1&&(s.dataset.count=String(e.length));const r=document.createElement("img");return r.src=a.iconPath,r.alt=Q(a),r.draggable=!1,s.appendChild(r),s}getPositionBadgeTitle(t,e){return e.kind===p.RANDOM_ASSIGNED?t.length===0?c("selectors.positionBadge.randomAssignedAny"):c("selectors.positionBadge.randomAssignedSome",{positions:this.formatPositionLabelsForSentence(t)}):e.kind===p.RANDOM_POOL?t.length===0?c("selectors.positionBadge.randomPoolAny"):c("selectors.positionBadge.randomPoolSome",{positions:this.formatPositionLabelsForSentence(t)}):t.length>0?c("selectors.positionBadge.championSome",{positions:this.formatPositionLabelsForSentence(t)}):c("selectors.positionBadge.championAny")}canOpenPositionMenuForTarget(t){if(!this.selectedPriorityOptions.includes(t.option))return!1;switch(t.kind){case p.CHAMPION_ASSIGNED:return typeof t.option=="number"&&this.enablePositionRestrictions;case p.RANDOM_ASSIGNED:return P(t.option)&&this.enableRandomAssignedPositionRestrictions;case p.RANDOM_POOL:return P(t.option)&&this.enableRandomPoolPositionFilters;default:return!1}}normalizePositionMenuTarget(t){if(!t||typeof t!="object"||Array.isArray(t)||!("option"in t)||!("kind"in t))return null;const e=M(t.option),n=e===null?null:{option:e,kind:String(t.kind)};return n&&this.canOpenPositionMenuForTarget(n)?n:null}getAllowedPositionsForPositionMenuTarget(t){switch(t.kind){case p.CHAMPION_ASSIGNED:return this.getChampionAllowedPositions(t.option);case p.RANDOM_ASSIGNED:return this.getRandomAssignedPositions();case p.RANDOM_POOL:return this.getRandomPoolPositions();default:return[]}}getAllowedPositionLabelsForPositionMenuTarget(t){return this.getPositionLabels(this.getAllowedPositionsForPositionMenuTarget(t))}setAllowedPositionsForPositionMenuTarget(t,e){switch(t.kind){case p.CHAMPION_ASSIGNED:{const n=String(t.option);e.length>0?this.positionsByChampionId[n]=e:delete this.positionsByChampionId[n];break}case p.RANDOM_ASSIGNED:this.randomAssignedPositions=e;break;case p.RANDOM_POOL:this.randomPoolPositions=e;break}}openPositionMenu(t,e,n=null){if(!this.positionMenuElement)return;const i=this.normalizePositionMenuTarget(e);if(i===null)return;t.preventDefault(),t.stopPropagation(),this.positionMenuTarget=i,this.renderPositionMenu(),this.positionMenuElement.hidden=!1,this.positionMenuElement.style.left="0px",this.positionMenuElement.style.top="0px";const{left:s,top:a}=this.getPositionMenuCoordinates(t,n);this.positionMenuElement.style.left=`${s}px`,this.positionMenuElement.style.top=`${a}px`,document.addEventListener("pointerdown",this.handlePositionMenuOutsidePointerDown,!0),document.addEventListener("keydown",this.handlePositionMenuKeyDown,!0)}getPositionMenuCoordinates(t,e=null){const n=this.positionMenuElement.getBoundingClientRect();let i=t.clientX,s=t.clientY;if(e&&t.type==="click"&&t.detail===0){const l=e.getBoundingClientRect();i=l.left+l.width/2,s=l.bottom}const a=Math.min(Math.max(i,q),window.innerWidth-n.width-q),r=Math.min(Math.max(s,q),window.innerHeight-n.height-q);return{left:a,top:r}}renderPositionMenu(){if(!this.positionMenuElement||this.positionMenuTarget===null)return;const t=new Set(this.getAllowedPositionsForPositionMenuTarget(this.positionMenuTarget));this.positionMenuElement.querySelectorAll(Jo).forEach(e=>{const n=t.has(e.dataset.position);e.classList.toggle("champion-priority-selector__position-option--selected",n),e.setAttribute("aria-pressed",String(n))})}togglePositionMenuPosition(t){if(!this.positionMenuElement||this.positionMenuTarget===null)return;const e=F(t);if(!e)return;const n=this.positionMenuTarget,i=n.option,s=new Set(this.getAllowedPositionsForPositionMenuTarget(n));s.has(e)?s.delete(e):s.add(e);const a=x.map(A=>A.value).filter(A=>s.has(A));this.setAllowedPositionsForPositionMenuTarget(n,a),this.renderPositionMenu();const r=I(i),l=r?this.optionButtons.get(r):null,u=this.selectedPriorityOptions.indexOf(i);l&&u!==-1&&(P(i)?this.getRandomOptionButton(u):this.getChampionOptionButton(i,u)),this.saveConfig()}closePositionMenuOnOutsidePointerDown(t){var e;(e=this.positionMenuElement)!=null&&e.contains(t.target)||this.closePositionMenu()}closePositionMenuOnKeyDown(t){t.key==="Escape"&&this.closePositionMenu()}closePositionMenu(){this.positionMenuElement&&(this.positionMenuElement.hidden=!0,this.positionMenuTarget=null,document.removeEventListener("pointerdown",this.handlePositionMenuOutsidePointerDown,!0),document.removeEventListener("keydown",this.handlePositionMenuKeyDown,!0))}startDrag(t,e){var s;if(t.button===zt){t.preventDefault();return}if(t.button!==ti)return;this.dragState&&this.clearDragState();const n=I(e),i=n?this.optionButtons.get(n):null;if(i){this.dragState={option:e,pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,active:!1,moved:!1};try{(s=i.setPointerCapture)==null||s.call(i,t.pointerId)}catch{}window.addEventListener("pointermove",this.handleWindowPointerMove),window.addEventListener("pointerup",this.handleWindowPointerUp),window.addEventListener("pointercancel",this.handleWindowPointerCancel)}}removePriorityOptionOnMiddleClick(t,e){t.button===zt&&(t.preventDefault(),t.stopPropagation(),this.removePriorityOption(e))}moveDrag(t){var A;if(!this.dragState||this.dragState.pointerId!==t.pointerId)return;const e=this.dragState.option,n=I(e),i=t.clientX-this.dragState.startX,s=t.clientY-this.dragState.startY,a=Math.hypot(i,s);if(!this.dragState.active){if(a<ei)return;this.dragState.active=!0,n&&((A=this.optionButtons.get(n))==null||A.classList.add("champion-priority-selector__icon--dragging"))}t.preventDefault();const r=this.getDropIndex(t.clientX,e),l=this.selectedPriorityOptions.indexOf(e);if(r===l||r===-1)return;const u=this.getIconPositions();this.movePriorityOptionToIndex(e,r)&&(this.dragState.moved=!0,this.renderSelectedPriorityOptions(u,e))}finishDrag(t){if(!this.dragState||this.dragState.pointerId!==t.pointerId)return;const e=this.dragState.active,n=this.dragState.moved;this.clearDragState(),e&&n&&this.saveConfig()}cancelDrag(t){!this.dragState||this.dragState.pointerId!==t.pointerId||this.clearDragState()}clearDragState(){var s;if(!this.dragState)return;const{option:t,pointerId:e}=this.dragState,n=I(t),i=n?this.optionButtons.get(n):null;i==null||i.classList.remove("champion-priority-selector__icon--dragging");try{(s=i==null?void 0:i.releasePointerCapture)==null||s.call(i,e)}catch{}window.removeEventListener("pointermove",this.handleWindowPointerMove),window.removeEventListener("pointerup",this.handleWindowPointerUp),window.removeEventListener("pointercancel",this.handleWindowPointerCancel),this.dragState=null}getDropIndex(t,e){const n=this.selectedPriorityOptions.filter(i=>i!==e);for(let i=0;i<n.length;i++){const s=I(n[i]),a=s?this.optionButtons.get(s):null;if(!a)continue;const r=a.getBoundingClientRect();if(t<r.left+r.width/2)return i}return n.length}getIconPositions(){const t=new Map;for(const e of this.selectedPriorityOptions){const n=I(e),i=n?this.optionButtons.get(n):null;i&&t.set(n,i.getBoundingClientRect())}return t}animateReorder(t,e){for(const n of this.selectedPriorityOptions){if(n===e)continue;const i=I(n),s=i?this.optionButtons.get(i):null,a=i?t.get(i):null;if(!s||!a||typeof s.animate!="function")continue;const r=s.getBoundingClientRect(),l=a.left-r.left,u=a.top-r.top;l===0&&u===0||s.animate([{transform:`translate(${l}px, ${u}px)`},{transform:"translate(0, 0)"}],{duration:ni,easing:oi})}}}const ii=200,st="auto-select-champ-select-menu--collapsed",si="auto-select-champ-select-menu-button-wrapper--open";class ai{constructor(t,e,n){this.element=document.createElement("div"),this.element.classList.add("auto-select-champ-select-menu",st),this.buttonWrapper=document.createElement("div"),this.buttonWrapper.classList.add("auto-select-champ-select-menu-button-wrapper"),this.headerElement=document.createElement("button"),this.headerElement.classList.add("auto-select-champ-select-menu__header"),this.headerElement.type="button",this.headerElement.setAttribute("aria-label",t),this.headerElement.setAttribute("aria-expanded","false"),this.headerElement.addEventListener("click",()=>this.toggle()),this.contentElement=document.createElement("div"),this.contentElement.classList.add("auto-select-champ-select-menu__content"),this.titleElement=document.createElement("div"),this.titleElement.classList.add("auto-select-champ-select-menu__title"),this.titleElement.textContent=t,this.titleAccessoryElement=null,this.buttonWrapper.append(this.headerElement,this.element),this.contentElement.appendChild(this.titleElement),this.element.appendChild(this.contentElement),this.returnControlsToSocialRoster=e,this.controlElements=n,this.boundCloseOnOutsideInteraction=i=>this.closeOnOutsideInteraction(i),this.buttonObserver=null,this.buttonMountFrame=null,this.buttonMountTask=null,this.hiddenStates=new WeakMap,this.mounted=!1}async mount(){return this.mounted?this.mountButton():(this.mounted=!0,this.controlElements.forEach(t=>{this.hiddenStates.set(t,t.classList.contains("hidden")),t.classList.remove("hidden"),this.contentElement.appendChild(t)}),this.observeButtonContainer(),document.addEventListener("pointerdown",this.boundCloseOnOutsideInteraction,!0),this.mountButton())}unmount(){return this.mounted?(this.mounted=!1,this.stopButtonMounting(),document.removeEventListener("pointerdown",this.boundCloseOnOutsideInteraction,!0),this.setOpen(!1),this.buttonWrapper.remove(),this.restoreHiddenStates(),this.returnControlsToSocialRoster()):this.returnControlsToSocialRoster()}stopButtonMounting(){var t;(t=this.buttonObserver)==null||t.disconnect(),this.buttonObserver=null,this.buttonMountFrame!==null&&(cancelAnimationFrame(this.buttonMountFrame),this.buttonMountFrame=null),this.buttonMountTask=null}restoreHiddenStates(){this.controlElements.forEach(t=>{t.classList.toggle("hidden",this.hiddenStates.get(t)===!0),this.hiddenStates.delete(t)})}isOpen(){return!this.element.classList.contains(st)}setOpen(t){this.element.classList.toggle(st,!t),this.buttonWrapper.classList.toggle(si,t),this.headerElement.setAttribute("aria-expanded",String(t))}toggle(){this.setOpen(!this.isOpen())}closeOnOutsideInteraction(t){if(!this.isOpen())return;(typeof t.composedPath=="function"?t.composedPath():[]).includes(this.buttonWrapper)||this.buttonWrapper.contains(t.target)||this.setOpen(!1)}observeButtonContainer(){this.buttonObserver=new MutationObserver(()=>this.scheduleMountButton()),this.buttonObserver.observe(document.body,{childList:!0,subtree:!0})}scheduleMountButton(){this.buttonMountFrame===null&&(this.buttonMountFrame=requestAnimationFrame(()=>{this.buttonMountFrame=null,this.mountButton()}))}mountButton(){return this.buttonMountTask||(this.buttonMountTask=this.appendButtonToContainer().finally(()=>{this.buttonMountTask=null})),this.buttonMountTask}async appendButtonToContainer(){let t=ht();for(;this.mounted&&!t;)await v(ii),t=ht();if(!this.mounted||!t)return;const e=t.querySelector(d.firstChampSelectSquareButton);this.buttonWrapper.parentNode===t&&this.buttonWrapper.nextSibling===e||t.insertBefore(this.buttonWrapper,e)}setTitleAccessory(t){this.titleAccessoryElement=t,(!t.isConnected||t.parentNode!==this.titleElement)&&this.titleElement.appendChild(t)}}class at{constructor(t,e){this.element=document.createElement(w.radioInputOption),this.element.classList.add("lol-settings-voice-input-mode-option","auto-select-checkbox"),this.element.innerText=t,this.config=null,this.configKey=e,this.setupComplete=!1}setup(){this.syncFromConfig(),this.setupComplete||(this.element.addEventListener("click",()=>this.toggle()),this.setupComplete=!0)}syncFromConfig(){this.config=ce(this.configKey),this.element.toggleAttribute("selected",this.config.enabled===!0)}toggle(){return console.debug("auto-champion-select: Toggling",this.configKey),this.config=R(this.configKey,t=>(t.enabled=!t.enabled,t)),this.element.toggleAttribute("selected",this.config.enabled===!0),this.config.enabled}}const ri=224,ci="auto-select-settings-trigger",Yt="auto-select-settings-flyout",qt="auto-select-settings-menu",li="auto-select-settings-menu__empty",di="auto-select-settings-checkbox",ui="auto-select-settings-range",hi="auto-select-settings-range__header",pi="auto-select-settings-range__label",mi="auto-select-settings-range__value",gi="auto-select-settings-range__track",fi="auto-select-settings-range__fill",yi="auto-select-settings-range__handle",Pi="auto-select-settings-range__handle--min",Si="auto-select-settings-range__handle--max",j="auto-select-settings-range__handle--dragging";class Ai{constructor(t=[]){this.controls=t,this.triggerElements=new Set,this.flyoutElement=this.createFlyoutElement(),this.open=!1,this.activeTriggerElement=null,this.setupComplete=!1,this.boundCloseOnOutsideInteraction=e=>this.closeOnOutsideInteraction(e),this.boundCloseOnEscape=e=>this.closeOnEscape(e),this.boundPositionFlyout=()=>this.positionFlyout(),this.renderControls()}setup(){this.ensureFlyoutConnected(),this.controls.forEach(t=>{var e;return(e=t.setup)==null?void 0:e.call(t)}),this.sync(),!this.setupComplete&&(document.addEventListener("pointerdown",this.boundCloseOnOutsideInteraction,!0),document.addEventListener("keydown",this.boundCloseOnEscape,!0),window.addEventListener("resize",this.boundPositionFlyout),this.setupComplete=!0)}setControls(t){this.controls=t,this.renderControls(),this.setupComplete&&this.controls.forEach(e=>{var n;return(n=e.setup)==null?void 0:n.call(e)}),this.sync()}createTriggerElement(t=c("settings.triggerLabel")){const e=document.createElement("button");return e.type="button",e.classList.add(ci),e.dataset.autoSelectSettings="trigger",e.setAttribute("aria-label",t),e.setAttribute("aria-expanded","false"),e.title=t,e.addEventListener("click",n=>{n.preventDefault(),n.stopImmediatePropagation(),n.stopPropagation(),this.toggleFlyout(e)},!0),this.triggerElements.add(e),e}createFlyoutElement(){const t=document.createElement("lol-uikit-flyout-frame");t.classList.add("flyout",Yt),t.dataset.autoSelectSettings="flyout",t.setAttribute("orientation","bottom"),t.setAttribute("animated","true"),t.setAttribute("caretless","true"),t.style.position="fixed",t.style.overflow="visible",t.style.display="none";const e=document.createElement("lc-flyout-content"),n=document.createElement("div");return n.classList.add("social-options-menu","active",qt),e.appendChild(n),t.appendChild(e),t}renderControls(){const t=this.flyoutElement.querySelector(`.${qt}`);if(t){if(t.replaceChildren(),this.controls.length===0){const e=document.createElement("div");e.classList.add(li),e.textContent=c("settings.empty"),t.appendChild(e);return}t.append(...this.controls.map(e=>e.element))}}sync(){this.controls.forEach(t=>{var e;return(e=t.sync)==null?void 0:e.call(t)})}ensureFlyoutConnected(){document.querySelectorAll(`.${Yt}`).forEach(t=>{t!==this.flyoutElement&&t.remove()}),this.flyoutElement.isConnected||document.body.appendChild(this.flyoutElement)}isOpen(){return this.open&&this.flyoutElement.isConnected&&getComputedStyle(this.flyoutElement).display!=="none"}setOpen(t,e=this.activeTriggerElement){this.open=t,this.activeTriggerElement=t?e:null,this.ensureFlyoutConnected(),this.flyoutElement.style.display=t?"block":"none",this.flyoutElement.toggleAttribute("show",t),this.triggerElements.forEach(n=>{n.setAttribute("aria-expanded",String(t&&n===this.activeTriggerElement))}),t&&(this.sync(),this.positionFlyout())}toggleFlyout(t){const e=!this.isOpen()||this.activeTriggerElement!==t;this.setOpen(e,t)}positionFlyout(){if(!this.isOpen()||!this.activeTriggerElement)return;const t=this.activeTriggerElement.getBoundingClientRect(),e=Math.min(ri,window.innerWidth-16);this.flyoutElement.style.width=`${e}px`;const n=this.flyoutElement.getBoundingClientRect(),i=t.right-e+4,s=Math.max(8,Math.min(window.innerWidth-e-8,i)),a=t.bottom+4,r=a+n.height<=window.innerHeight-8?a:Math.max(8,t.top-n.height-4);this.flyoutElement.style.left=`${Math.round(s)}px`,this.flyoutElement.style.top=`${Math.round(r)}px`}closeOnOutsideInteraction(t){if(!this.isOpen())return;const e=typeof t.composedPath=="function"?t.composedPath():[],n=[...this.triggerElements].some(s=>e.includes(s)),i=e.includes(this.flyoutElement);!n&&!i&&this.setOpen(!1)}closeOnEscape(t){t.key==="Escape"&&this.isOpen()&&this.setOpen(!1)}}class ${constructor(t,e){this.label=t,this.options=e,this.element=document.createElement(w.radioInputOption),this.element.classList.add("lol-settings-voice-input-mode-option",di),this.element.textContent=t,this.element.title=t,this.setupComplete=!1}setup(){this.sync(),!this.setupComplete&&(this.element.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),this.options.toggle(),this.sync()}),this.setupComplete=!0)}sync(){this.element.toggleAttribute("selected",this.options.isSelected()===!0)}}class Ci{constructor(t,e){this.label=t,this.options=e,this.dragHandle=null,this.dragStartedCollapsed=!1,this.setupComplete=!1,this.boundPointerMove=i=>this.onPointerMove(i),this.boundPointerUp=()=>this.stopDragging(),this.element=document.createElement("div"),this.element.classList.add(ui);const n=document.createElement("div");n.classList.add(hi),this.labelElement=document.createElement("span"),this.labelElement.classList.add(pi),this.labelElement.textContent=t,this.valueElement=document.createElement("span"),this.valueElement.classList.add(mi),this.trackElement=document.createElement("div"),this.trackElement.classList.add(gi),this.fillElement=document.createElement("div"),this.fillElement.classList.add(fi),this.minHandleElement=this.createHandle("min"),this.maxHandleElement=this.createHandle("max"),n.append(this.labelElement,this.valueElement),this.trackElement.append(this.fillElement,this.minHandleElement,this.maxHandleElement),this.element.append(n,this.trackElement)}setup(){this.sync(),!this.setupComplete&&(this.trackElement.addEventListener("pointerdown",t=>this.onTrackPointerDown(t)),this.minHandleElement.addEventListener("pointerdown",t=>this.startDragging(t,"min")),this.maxHandleElement.addEventListener("pointerdown",t=>this.startDragging(t,"max")),this.minHandleElement.addEventListener("keydown",t=>this.onHandleKeyDown(t,"min")),this.maxHandleElement.addEventListener("keydown",t=>this.onHandleKeyDown(t,"max")),this.setupComplete=!0)}createHandle(t){const e=document.createElement("button");return e.type="button",e.classList.add(yi,t==="min"?Pi:Si),e.setAttribute("aria-label",c("settings.handleLabel",{label:this.label,handle:c(`settings.handles.${t}`)})),e.setAttribute("aria-valuemin",String(this.options.min)),e.setAttribute("aria-valuemax",String(this.options.max)),e.setAttribute("role","slider"),e}getNormalizedValue(){const t=this.options.getValue(),e=this.snapValue(t.min),n=this.snapValue(t.max);return{min:Math.min(e,n),max:Math.max(e,n)}}snapValue(t){const e=this.options.min,n=this.options.max,i=this.options.step,s=Number(t),a=Number.isFinite(s)?s:e,r=Math.round((a-e)/i)*i+e;return Math.max(e,Math.min(n,r))}sync(){const t=this.getNormalizedValue(),e=this.valueToPercent(t.min),n=this.valueToPercent(t.max);this.valueElement.textContent=this.options.formatValue(t),this.fillElement.style.left=`${e}%`,this.fillElement.style.width=`${n-e}%`,this.minHandleElement.style.left=`${e}%`,this.maxHandleElement.style.left=`${n}%`,this.syncHandle(this.minHandleElement,t.min),this.syncHandle(this.maxHandleElement,t.max)}syncHandle(t,e){t.setAttribute("aria-valuenow",String(e)),t.setAttribute("aria-valuetext",this.options.formatValue({min:e,max:e}))}valueToPercent(t){const e=this.options.max-this.options.min;return e<=0?0:(t-this.options.min)/e*100}clientXToValue(t){const e=this.trackElement.getBoundingClientRect(),n=e.width<=0?0:(t-e.left)/e.width;return this.snapValue(this.options.min+(this.options.max-this.options.min)*n)}onTrackPointerDown(t){if(t.target===this.minHandleElement||t.target===this.maxHandleElement)return;const e=this.clientXToValue(t.clientX),n=this.getNormalizedValue(),i=Math.abs(e-n.min)<=Math.abs(e-n.max)?"min":"max";this.startDragging(t,i),this.setHandleValue(i,e)}startDragging(t,e){t.preventDefault(),t.stopPropagation(),this.dragHandle=e;const n=this.getNormalizedValue();this.dragStartedCollapsed=n.min===n.max,this.syncDraggingHandle(),document.addEventListener("pointermove",this.boundPointerMove,!0),document.addEventListener("pointerup",this.boundPointerUp,!0)}onPointerMove(t){if(!this.dragHandle)return;t.preventDefault();const e=this.clientXToValue(t.clientX),n=this.resolveDragHandleForValue(e);this.dragHandle=n,this.syncDraggingHandle(),this.setHandleValue(n,e)}stopDragging(){this.clearDraggingHandle(),this.dragHandle=null,this.dragStartedCollapsed=!1,document.removeEventListener("pointermove",this.boundPointerMove,!0),document.removeEventListener("pointerup",this.boundPointerUp,!0)}syncDraggingHandle(){this.minHandleElement.classList.toggle(j,this.dragHandle==="min"),this.maxHandleElement.classList.toggle(j,this.dragHandle==="max")}clearDraggingHandle(){this.minHandleElement.classList.remove(j),this.maxHandleElement.classList.remove(j)}onHandleKeyDown(t,e){const n=this.getNormalizedValue();let s=e==="min"?n.min:n.max;if(t.key==="ArrowLeft"||t.key==="ArrowDown")s-=this.options.step;else if(t.key==="ArrowRight"||t.key==="ArrowUp")s+=this.options.step;else if(t.key==="Home")s=this.options.min;else if(t.key==="End")s=this.options.max;else return;t.preventDefault(),this.setHandleValue(e,s)}resolveDragHandleForValue(t){if(!this.dragHandle)return"min";if(!this.dragStartedCollapsed)return this.dragHandle;const e=this.getNormalizedValue();return t<e.min?"min":t>e.max?"max":this.dragHandle}setHandleValue(t,e){const n=this.getNormalizedValue(),i=this.snapValue(e),s=t==="min"?{min:Math.min(i,n.max),max:n.max}:{min:n.min,max:Math.max(i,n.min)};this.options.setValue(s),this.sync()}}const bi="auto-select-social-roster-section",jt="auto-select-social-roster-section__header";class Ei{constructor(t,...e){this.element=document.createElement(w.socialRosterGroup),this.element.classList.add(bi),this.element.addEventListener("post-render",()=>this.onPostRender()),this.element.addEventListener("click",()=>this.onClick()),this.label=t,this.collapsibleElements=e,this.headerAccessoryElement=null,this.waitRender()}waitRender(){new MutationObserver((t,e)=>{if(this.element.querySelector(d.socialRosterGroupLabel)){const n=new Event("post-render");this.element.dispatchEvent(n),e.disconnect()}}).observe(this.element,{childList:!0})}onPostRender(){this.element.querySelector(d.socialRosterGroupLabel).innerText=this.label;const t=this.element.querySelector(d.socialRosterGroupHeader);t==null||t.removeAttribute("draggable"),t&&this.headerAccessoryElement&&(t.classList.add(jt),t.appendChild(this.headerAccessoryElement))}setHeaderAccessory(t){this.headerAccessoryElement=t;const e=this.element.querySelector(d.socialRosterGroupHeader);e&&(e.classList.add(jt),e.appendChild(t))}onClick(){var t;this.collapsibleElements.forEach(e=>{e.closest(".auto-select-champ-select-menu")||e.classList.toggle("hidden")}),(t=this.element.querySelector(d.socialRosterGroupArrow))==null||t.toggleAttribute("open")}}function Pe(o){o&&Toast.success(o)}function gt(o){o&&Toast.error(o)}function Oi(o,t){return typeof Toast.promise=="function"?Toast.promise(o,t):o}const Ct="Balaclava: Auto Champion Select";function bt(){return c("commandBar.group")}function wi(o){return typeof(o==null?void 0:o.then)=="function"}class Et{constructor({id:t,name:e,legend:n,tags:i,group:s,callback:a,toasts:r}){this.id=t,this.name=e,this.legend=n,this.tags=i,this.group=s,this.perform=this.perform.bind(this),this.callback=a,this.toasts=r}perform(){try{const t=this.callback();if(wi(t))return Oi(t,{loading:this.toasts.loading,success:this.toasts.success,error:this.toasts.error});const e=this.toasts.success||(t?this.toasts.on:this.toasts.off);Pe(e)}catch(t){gt(this.toasts.error),console.error(t)}}}class Se extends Et{constructor(t,e,n){super({id:`${e}Switch`,name:()=>c("commandBar.autoSwitchName",{name:t,state:y(e).enabled?c("states.on"):c("states.off")}),legend:()=>y(e).enabled?c("commandBar.turnOff"):c("commandBar.turnOn"),tags:[Ct,e,"switch"],group:bt(),callback:n,toasts:{on:c("commandBar.autoSwitchOn",{name:t}),off:c("commandBar.autoSwitchOff",{name:t}),error:c("commandBar.autoSwitchError",{name:t})}})}}function Ti(o){return R(o,e=>(e.force=!e.force,e)).force}class Ae extends Et{constructor(t){const e=t==="controladoPick",n=c(e?"commandBar.forcePickName":"commandBar.forceBanName");super({id:`${t}ForceSwitch`,name:()=>c("commandBar.forceSwitchName",{name:n,state:y(t).force?c("states.on"):c("states.off")}),legend:()=>c(e?"commandBar.forcePickLegend":"commandBar.forceBanLegend"),tags:[Ct,t,"force","intent","switch"],group:bt(),callback:()=>Ti(t),toasts:{on:c("commandBar.forceSwitchOn",{name:n}),off:c("commandBar.forceSwitchOff",{name:n}),error:c("commandBar.forceSwitchError",{name:n})}})}}class ki extends Et{constructor(t){super({id:"RefreshDropdowns",name:()=>c("commandBar.refreshChampionsName"),legend:()=>c("commandBar.refreshChampionsLegend"),tags:[Ct,"refresh"],group:bt(),callback:t,toasts:{success:c("commandBar.refreshChampionsSuccess"),error:c("commandBar.refreshChampionsError")}})}}class Ii extends Se{constructor(t){super(c("actions.pick"),"controladoPick",t)}}class Li extends Se{constructor(t){super(c("actions.ban"),"controladoBan",t)}}class _i extends Ae{constructor(){super("controladoPick")}}class vi extends Ae{constructor(){super("controladoBan")}}function Ri(o){for(const t of o)CommandBar.addAction(t)}const Mi=200,Ni=6e4,Kt=2e3,Bi=".ready-check-root-element",Di="#lol-uikit-layer-manager-wrapper > .modal",xi=".auto-select-champ-select-menu__header",g=Object.freeze({autoAccept:"controladoAutoAccept",actionDelay:"controladoActionDelay",pick:"controladoPick",ban:"controladoBan"});function Fi(){return y(g.autoAccept).enabled===!0}function Ce(){return y(g.autoAccept).hideAutoAcceptPrompt===!0}function $i(){const o=y(g.autoAccept);return o.enabled===!0&&o.hideAutoAcceptPrompt===!0}function Hi(){const o=Ce();R(g.autoAccept,t=>(t.hideAutoAcceptPrompt=!o,t))}function be(o){return o==="pick"?g.pick:g.ban}function Ee(){return y(g.pick).pickIntent!==!1}function zi(){const o=Ee();R(g.pick,t=>(t.pickIntent=!o,t))}function Vi(){return y(g.pick).respectManualPick===!0}function Ui(){R(g.pick,o=>(o.respectManualPick=o.respectManualPick!==!0,o))}function Wt(o){return y(be(o)).force===!0}function Xt(o){R(be(o),t=>(t.force=t.force!==!0,t))}function Gi(){const o=y(g.actionDelay),{minMs:t,maxMs:e}=z(o.minMs,o.maxMs);return{min:t,max:e}}function Yi(o){const{minMs:t,maxMs:e}=z(o.min,o.max);R(g.actionDelay,n=>(n.minMs=t,n.maxMs=e,n))}function qi(o){const{minMs:t,maxMs:e}=z(o.min,o.max);return t===0&&e===0?c("settings.actionDelayValue.instant"):t===e?c("settings.actionDelayValue.exact",{delay:U(e)}):t===0?c("settings.actionDelayValue.upTo",{delay:U(e)}):c("settings.actionDelayValue.range",{min:U(t),max:U(e)})}class ji{constructor(t){this.isEnabled=t,this.observer=null,this.hiddenModal=null,this.hiddenModalStyles=new WeakMap,this.sync=this.sync.bind(this)}start(){this.observer||(this.observer=new MutationObserver(()=>this.sync()),this.observer.observe(document.body,{childList:!0,subtree:!0}),this.sync())}sync(){const t=Ki();if(!t){this.restore();return}if(!this.isEnabled()){this.restore();return}this.hide(t)}hide(t){this.hiddenModal!==t&&(this.restore(),this.hiddenModal=t,this.hiddenModalStyles.set(t,{display:t.style.getPropertyValue("display"),displayPriority:t.style.getPropertyPriority("display"),pointerEvents:t.style.getPropertyValue("pointer-events"),pointerEventsPriority:t.style.getPropertyPriority("pointer-events")}),t.style.setProperty("display","none","important"),t.style.setProperty("pointer-events","none","important"))}restore(){if(!this.hiddenModal)return;const t=this.hiddenModal,e=this.hiddenModalStyles.get(t);Jt(t,"display",e==null?void 0:e.display,e==null?void 0:e.displayPriority),Jt(t,"pointer-events",e==null?void 0:e.pointerEvents,e==null?void 0:e.pointerEventsPriority),this.hiddenModalStyles.delete(t),this.hiddenModal=null}}function Ki(){const o=document.querySelector(Bi);return(o==null?void 0:o.closest(Di))||null}function Jt(o,t,e,n){e?o.style.setProperty(t,e,n||""):o.style.removeProperty(t)}async function Wi(o){function t(){return Fi()?!1:(o.restore(),!0)}if(t()||(console.debug(`auto-champion-select(auto-accept): Ready check detected, accepting in ${Kt}ms...`),await v(Kt),t()))return;let e=!1;try{e=await Xi()}catch(n){throw o.restore(),gt(c("toasts.readyCheckAcceptFailed")),n}e?Pe(c("toasts.readyCheckAccepted")):(o.restore(),gt(c("toasts.readyCheckAcceptFailed")))}async function Xi(){const o=await O("POST",f.readyCheckAccept);return o.ok?(console.debug("auto-champion-select(auto-accept): Accepted ready check"),!0):(console.error("auto-champion-select(auto-accept): Failed to accept ready check",o),!1)}async function Ji(o){const t=await O("GET",f.gameflowPhase),e=t.ok?await t.json():null;o.handleGameflowPhase(e)}function Qi({championSelect:o,champSelectControlsMenu:t,readyCheckModalSuppressor:e,setupChampionSelectors:n}){let i=0;return async function(l){const u=++i;try{await s(l,u)}catch(A){console.error("auto-champion-select: Failed to handle gameflow phase",A)}};async function s(r,l){r==="ReadyCheck"?Wi(e).catch(u=>{console.error("auto-champion-select(auto-accept): Failed to handle ready check",u)}):e.restore(),await a(r),l===i&&await n()}async function a(r){r==="ChampSelect"?(o.mount(),await t.mount()):(o.unmount(),await t.unmount())}}function Zi(){const o=new en,t=new at(c("toggles.autoAccept"),g.autoAccept),e=new at(c("toggles.pick"),g.pick),n=new Gt(c("selectors.pickPlaceholder"),g.pick,We,{enablePositionRestrictions:!0,enableRandomAssignedPositionRestrictions:!0,enableBraveryOption:!0,enableRandomPoolPositionFilters:!0}),i=new at(c("toggles.ban"),g.ban),s=new Gt(c("selectors.banPlaceholder"),g.ban,de,{enableRandomPoolPositionFilters:!0}),a=es(n,s),r=ns(t,e,i),l=new Ai,u=new Ei(c("plugin.socialRosterTitle"),a,r);return u.setHeaderAccessory(l.createTriggerElement()),{championSelect:o,autoAcceptToggle:t,pickToggle:e,banToggle:i,pickChampionSelector:n,banChampionSelector:s,selectorsContainer:a,checkboxesContainer:r,pluginSection:u,settingsMenu:l,championSelectors:[n,s]}}function ts(o){return[new Ci(c("settings.actionDelay"),{min:te,max:ee,step:rt,getValue:Gi,setValue:Yi,formatValue:qi}),new $(c("settings.pickIntent"),{isSelected:()=>Ee(),toggle:()=>zi()}),new $(c("settings.respectManualPick"),{isSelected:()=>Vi(),toggle:()=>Ui()}),new $(c("settings.forcePick"),{isSelected:()=>Wt("pick"),toggle:()=>Xt("pick")}),new $(c("settings.forceBan"),{isSelected:()=>Wt("ban"),toggle:()=>Xt("ban")}),new $(c("settings.hideAutoAcceptPrompt"),{isSelected:()=>Ce(),toggle:()=>{Hi(),o.sync()}})]}function es(...o){const t=document.createElement("div");return t.append(...o.map(e=>e.element)),t}function ns(...o){const t=document.createElement("div");return t.classList.add("auto-select-checkboxes-div"),t.append(...o.map(e=>e.element)),t}function os({pluginSection:o,checkboxesContainer:t,selectorsContainer:e}){let n=null,i=0,s=()=>!1;async function a(r){let l=Rt();for(;!l;){if(s()||r!==i)return;await v(Mi),l=Rt()}s()||r!==i||l.append(o.element,t,e)}return{setIsChampSelectControlsMounted(r){s=r},returnControlsToSocialRoster(){if(n)return n;const r=++i;return n=a(r).catch(l=>console.error("auto-champion-select: Failed to return controls to social roster",l)).finally(()=>{n=null}),n}}}function is({autoAcceptToggle:o,pickToggle:t,banToggle:e,readyCheckModalSuppressor:n}){o.setup(),o.element.addEventListener("click",()=>n.sync()),t.setup(),e.setup()}async function ss(o){await Promise.all(o.map(t=>t.setup()))}async function as(o){await Promise.all(o.map(t=>t.refresh()))}function rs(){const o=Zi(),t=new ji($i);o.settingsMenu.setControls(ts(t));const e=os(o),n=new ai(c("plugin.champSelectMenuTitle"),e.returnControlsToSocialRoster,[o.checkboxesContainer,o.selectorsContainer]);n.setTitleAccessory(o.settingsMenu.createTriggerElement()),e.setIsChampSelectControlsMounted(()=>n.mounted);const i={...o,champSelectControlsMenu:n,readyCheckModalSuppressor:t,setupToggles:()=>is({...o,readyCheckModalSuppressor:t}),setupSettingsMenu:()=>o.settingsMenu.setup(),setupChampionSelectors:()=>ss(o.championSelectors),refreshChampionSelectors:()=>as(o.championSelectors),refreshPickChampionSelector:async()=>{await o.pickChampionSelector.refresh()}};return i.handleGameflowPhase=Qi(i),i}function cs(o){Ot(f.gameflowPhase,t=>{o.handleGameflowPhase(t.data)}),Ot(f.wallet,async t=>{if(t.eventType==="Update"){console.debug("auto-champion-select(wallet): Refreshing champion selectors...");try{await o.refreshPickChampionSelector()}catch(e){console.error("auto-champion-select(wallet): Failed to refresh champion selectors",e)}}})}function ls({pickToggle:o,banToggle:t,refreshChampionSelectors:e}){Ri([new Ii(()=>o.toggle()),new Li(()=>t.toggle()),new _i,new vi,new ki(e)])}function ds(o){let t=null,e=null;function n(){e==null||e.disconnect(),e=null,t!==null&&(cancelAnimationFrame(t),t=null)}const i=setTimeout(()=>{n()},Ni);function s(){if(!(ht()!==null))return;clearTimeout(i),n(),document.querySelector(xi)!==null||o.handleGameflowPhase("ChampSelect")}e=new MutationObserver(()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,s()}))}),e.observe(document.body,{childList:!0,subtree:!0}),s()}async function us(){await zo();const o=rs();o.setupToggles(),o.setupSettingsMenu(),o.readyCheckModalSuppressor.start(),ls(o),cs(o),await Ji(o),ds(o),console.debug(`auto-champion-select(${Oe}): Report bugs to Balaclava#1912`)}let Qt=!1;function Zt(){Qt||(Qt=!0,us().catch(o=>console.error("auto-champion-select: Failed to initialize",o)))}document.readyState==="loading"?window.addEventListener("load",Zt,{once:!0}):Zt();export{Zt as load};
|