auto-champion-select 1.9.5 → 1.9.6

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/README.br.md CHANGED
@@ -17,8 +17,8 @@ Aceite a fila, selecione e bana os campeões automaticamente. <br>
17
17
 
18
18
  ## 📍 Novidades
19
19
 
20
- - Opção pickar Bravura
21
- - Opção para pickar aleatoriamente
20
+ - Opção pickar Bravura no modo Arena
21
+ - Opção para pickar ou banir aleatoriamente
22
22
  - Menu na seleção de campeões
23
23
  - Filtrar campeões
24
24
 
package/README.md CHANGED
@@ -17,8 +17,8 @@ Accept queue, pick and ban champions automatically. <br>
17
17
 
18
18
  ## 📍 What's new
19
19
 
20
- - Bravery pick option
21
- - Random pick option
20
+ - Bravery pick option for Arena mode
21
+ - Random pick or ban option
22
22
  - Champion select menu
23
23
  - Filter champions
24
24
 
package/dist/index.js CHANGED
@@ -4,10 +4,10 @@
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.9.5
7
+ * @version 1.9.6
8
8
  * @license GPL-3.0-or-later
9
9
  */
10
- import{request as S,sleep as T,linkEndpoint as pt}from"https://cdn.jsdelivr.net/npm/balaclava-utils@latest";const ee="1.9.5",ne={enabled:!1},oe={enabled:!1,force:!1,quickAction:!1,champions:[432,235],randomAssignedPositions:[],randomPoolPositions:[],positionsByChampionId:{235:["BOTTOM","UTILITY"],432:["UTILITY"]}},ie={enabled:!1,force:!1,quickAction:!1,champions:[157,777,238,38],randomPoolPositions:[]},se={controladoAutoAccept:ne,controladoPick:oe,controladoBan:ie};function u(i){const t=Number(i);return Number.isSafeInteger(t)&&t>0?t:null}function re(i,t=null){const e=[],n=new Set,o=ae(t);if(!Array.isArray(i))return e;for(const s of i){const r=u(s);r===null||n.has(r)||o&&!o.has(r)||(e.push(r),n.add(r))}return e}function ae(i){return i?new Set(Array.from(i,u).filter(t=>t!==null)):null}const F=[{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"}],ce=new Set(F.map(i=>i.value));function x(i){const t=String(i??"").toUpperCase();return ce.has(t)?t:null}function A(i){if(!Array.isArray(i))return[];const t=new Set;for(const e of i){const n=x(e);n&&t.add(n)}return F.map(e=>e.value).filter(e=>t.has(e))}function G(i,t=null){const e={};if(!i||typeof i!="object"||Array.isArray(i))return e;const n=le(t);for(const[o,s]of Object.entries(i)){const r=u(o);if(r===null||!Array.isArray(s))continue;const a=String(r);if(n&&!n.has(a))continue;const c=[],d=new Set;for(const g of s){const z=x(g);!z||d.has(z)||(c.push(z),d.add(z))}c.length>0&&(e[a]=c)}return e}function le(i){if(!i)return null;const t=new Set;for(const e of i){const n=u(e);n!==null&&t.add(String(n))}return t}function mt(i){return F.find(t=>t.value===i)}function Dt(i,t){var n;const e=u(t);return e===null?[]:((n=i==null?void 0:i.positionsByChampionId)==null?void 0:n[String(e)])||[]}function de(i,t,e){const n=Dt(i,t);if(n.length===0)return!0;const o=x(e);return o!==null&&n.includes(o)}const b="random",E="bravery";function p(i){return i===b}function C(i){return i===E}function _(i){return p(i)?b:C(i)?E:u(i)}function w(i){const t=_(i);return t===null?null:String(t)}function ct(i,t=null){const e=[],n=new Set,o=he(t);if(!Array.isArray(i))return e;for(const s of i){const r=_(s);if(r===null)continue;const a=String(r);n.has(a)||typeof r=="number"&&o&&!o.has(r)||(e.push(r),n.add(a))}return e}function M(i){return i?Array.from(i,u).filter(t=>t!==null):[]}function he(i){return i?new Set(Array.from(i,u).filter(t=>t!==null)):null}const ft=new Set;function xt(i,t){return Object.prototype.hasOwnProperty.call(i,t)}function R(i,t){return xt(i,t)}function ue(i){return Array.isArray(i.priorityOptions)?i.priorityOptions:i.champions}function pe(i,t){return xt(i,"randomPoolPositions")?i.randomPoolPositions:t.randomPositions}function lt(){if(!globalThis.DataStore)throw new Error("DataStore is not available");return globalThis.DataStore}function me(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)}function dt(i){if(i!==void 0)return JSON.parse(JSON.stringify(i))}function $t(i){const t=se[i];if(!t)throw new Error(`Unknown auto-champion-select config key: ${i}`);return dt(t)}function qt(i,t,e={}){const n=$t(i),o=me(t)?dt(t):{},s={...n,...o},r={enabled:s.enabled===!0};return R(n,"force")&&(r.force=s.force===!0),R(n,"quickAction")&&(r.quickAction=s.quickAction===!0),R(n,"champions")&&(r.priorityOptions=ct(ue(s),e.allowedChampionIds),r.champions=M(r.priorityOptions)),R(n,"randomAssignedPositions")&&(r.randomAssignedPositions=A(s.randomAssignedPositions)),R(n,"randomPoolPositions")&&(r.randomPoolPositions=A(pe(o,s))),R(n,"positionsByChampionId")&&(r.positionsByChampionId=G(s.positionsByChampionId,e.selectedChampionIds||r.champions)),r}function zt(i,t,e={}){const n=t===void 0?$t(i):t;return qt(i,n,e)}function k(i,t={}){const n=lt().get(i);return zt(i,n,t)}function fe(i,t,e={}){const n=lt(),o=qt(i,t,e);return n.set(i,o),o}function ge(i,t){return JSON.stringify(i)===JSON.stringify(t)}function Pe(i,t,e){ft.has(i)||(ft.add(i),console.warn(`auto-champion-select: Repaired ${i} 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 Yt(i,t={}){const e=lt(),n=e.get(i),o=zt(i,n,t);return(n===void 0||!ge(n,o))&&(n!==void 0&&Pe(i,n,o),e.set(i,o)),o}function H(i,t,e={}){const n=k(i,e),o=dt(n),s=t(o)||o;return fe(i,s,e)}const m=Object.freeze({readyCheckAccept:"/lol-matchmaking/v1/ready-check/accept",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(i){return`/lol-game-data/assets/v1/champion-icons/${i}.png`},champSelectAction(i){return`/lol-champ-select/v1/session/actions/${i}`}}),ye=1e3;function ht(i){let t=null;return function(){return t||(t=Promise.resolve().then(i).finally(()=>{t=null})),t}}function Ut(i,t={}){const e=[],n=new Set;if(!Array.isArray(i))return e;for(const o of i){if(!o||typeof o!="object")continue;const s=u(o.id),r=typeof o.name=="string"?o.name:"";s===null||!r||n.has(r)||(e.push({...o,id:s,name:r,squarePortraitPath:o.squarePortraitPath||m.championIcon(s),recommendedPositions:t[String(s)]||[]}),n.add(r))}return e.sort((o,s)=>o.name.localeCompare(s.name)),e}function be(i){const t={};if(!i||typeof i!="object"||Array.isArray(i))return t;for(const[e,n]of Object.entries(i))!n||typeof n!="object"||Array.isArray(n)||(t[e]=n.recommendedPositions);return G(t)}async function Ae(){try{const i=await S("GET",m.recommendedChampionPositions);return i.ok?be(await i.json()):(console.warn("auto-champion-select(recommended-champion-positions): Request failed",i),{})}catch(i){return console.warn("auto-champion-select(recommended-champion-positions): Failed to load",i),{}}}const j=ht(Ae);async function Ce(){let i=await S("GET",m.ownedChampions);for(;!i.ok;)console.debug("auto-champion-select(owned-champions-minimal): Retrying..."),i=await S("GET",m.ownedChampions),await T(ye);return Ut(await i.json(),await j())}async function Se(){const[i,t]=await Promise.all([S("GET",m.championSummary),j()]);return Ut(await i.json(),t)}const Oe=ht(Ce),Gt=ht(Se),gt=300,Pt=2e3,we=4e3,Ee=-1,Ht=-3,P=Object.freeze({SATISFIED:"satisfied",TRY_NEXT_CHAMPION:"try-next-champion",STOP_CYCLE:"stop-cycle"}),v=Object.freeze({CONTINUE:"continue-cycle",STOP:"stop-cycle"}),y=Object.freeze({READY:"ready",SKIP_ACTION:"skip-action",STOP_CYCLE:"stop-cycle"}),f=Object.freeze({SATISFIED:"satisfied",TRY_NEXT_PRIORITY_OPTION:"try-next-priority-option",STOP_CYCLE:"stop-cycle"});function ot(i){return Array.isArray(i)?i.flat():[]}function Ie(i){return ot(i).filter(t=>t.type==="ban"&&t.completed===!0).map(t=>t.championId)}function yt(i){return Array.isArray(i)?i:[]}function Q(i){const t=new Set;for(const e of i){const n=u(e);n!==null&&t.add(n)}return t}function bt(i){return i.type==="pick"?0:1}function At(){return{pickConfig:k("controladoPick"),banConfig:k("controladoBan")}}function Te(i){return i.quickAction===!0}function _e(){const i=we-Pt;return Pt+Math.floor(Math.random()*(i+1))}function ke(i){const t=[...i];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 Re(i){return Array.isArray(i)&&i.length===1&&i[0]===Ee}function W(i){return Number(i)===Ht}class ve{constructor(){this.session=null,this.actions=null,this.localPlayerCellId=null,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.watchTask=null,this.watchVersion=0,this.mounted=!1}mount(){this.mounted||(this.mounted=!0,this.rejectedBraveryActionIds.clear(),this.watchVersion+=1,this.watchTask||(this.watchTask=this.watch()))}unmount(){this.mounted&&(this.mounted=!1,this.rejectedBraveryActionIds.clear(),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 T(gt);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 T(gt)}}finally{this.watchTask=null}}async refreshSessionState(){var s,r;const t=await S("GET",m.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=yt(this.session.myTeam),n=yt(this.session.theirTeam),o=e.find(a=>a.cellId===this.localPlayerCellId);this.localPlayerAssignedPosition=x(o==null?void 0:o.assignedPosition),this.localPlayerIntentChampionId=u(o==null?void 0:o.championPickIntent),this.localPlayerIntentIsBravery=W(o==null?void 0:o.championPickIntent),this.pickedChampionIds=Q([...e,...n].map(a=>a.championId)),this.bannedChampionIds=Q([...((s=this.session.bans)==null?void 0:s.myTeamBans)||[],...((r=this.session.bans)==null?void 0:r.theirTeamBans)||[],...Ie(this.actions)]),this.teammateIntentChampionIds=Q(e.map(a=>a.championPickIntent))}async runAutoSelectCycle(){const t=At();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)===v.STOP)return}async runAutoSelectForAction(t,e){const n=await this.prepareActionForAutoSelect(t,e);switch(n.status){case y.READY:return this.tryAutoSelectPlan(n.plan);case y.SKIP_ACTION:return v.CONTINUE;case y.STOP_CYCLE:return v.STOP;default:throw new Error(`Unexpected auto-select plan status: ${n.status}`)}}async prepareActionForAutoSelect(t,e){if(!this.isActionAvailable(t))return{status:y.SKIP_ACTION};const n=this.getConfigForActionType(t.type,e);if(!(n!=null&&n.enabled))return{status:y.SKIP_ACTION};const o=this.createAutoSelectPlan(t,n);if(!o)return{status:y.SKIP_ACTION};const s=this.createPlanLimitedToAlreadySatisfiedPriorityOption(o);if(s)return{status:y.READY,plan:s};if(Te(n))return{status:y.READY,plan:o};const r=await this.delayAndRefreshAutoSelectPlan(t);return r?{status:y.READY,plan:this.createPlanLimitedToAlreadySatisfiedPriorityOption(r)||r}:{status:y.STOP_CYCLE}}async tryAutoSelectPlan(t){for(const e of t.priorityOptions){const n=await this.tryPriorityOptionForAction(t.action,e,t.config);if(n===f.SATISFIED)return v.CONTINUE;if(n===f.STOP_CYCLE)return v.STOP}return v.CONTINUE}async tryPriorityOptionForAction(t,e,n){if(this.isPriorityOptionAlreadySatisfied(t,e))return f.SATISFIED;if(C(e))return this.tryBraveryForAction(t);const o=await this.resolveChampionIdsForPriorityOption(t,e,n),s=p(e)&&!this.isLockingExistingPickIntent(t,o);for(const r of o){const a={tryNextRandomCandidateOnFailure:s},c=await this.attemptChampionForAction(t,r,n,a);if(c===P.SATISFIED)return f.SATISFIED;if(c===P.STOP_CYCLE)return f.STOP_CYCLE}return f.TRY_NEXT_PRIORITY_OPTION}async tryBraveryForAction(t){if(t.type!=="pick")return f.TRY_NEXT_PRIORITY_OPTION;if(this.isBraveryPickIntentSet(t))return f.SATISFIED;console.debug("auto-champion-select: Trying to pick Bravery...");const e=await this.selectChampion(t.id,Ht);console.debug(e.ok?"auto-champion-select: Bravery request accepted, refreshing champ select state...":"auto-champion-select: Failed to pick Bravery, refreshing champ select state...");const n=await this.refreshPendingAction(t);return!n||!this.isActionAvailable(n)?e.ok?f.SATISFIED:f.STOP_CYCLE:this.isBraveryPickIntentSet(n)?f.SATISFIED:(this.rejectedBraveryActionIds.add(t.id),console.debug("auto-champion-select: Bravery was not applied after refresh, trying next pick..."),f.TRY_NEXT_PRIORITY_OPTION)}getLocalPlayerActions(){return ot(this.actions).filter(t=>this.isPendingLocalPlayerAction(t)).sort((t,e)=>bt(t)-bt(e))}isPendingLocalPlayerAction(t){return t.actorCellId===this.localPlayerCellId&&t.completed===!1}isActionAvailable(t){return t.type==="pick"||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 ct(e.priorityOptions||e.champions).filter(n=>!this.isPriorityOptionUnavailableForAction(t,n,e))}isPriorityOptionUnavailableForAction(t,e,n){return p(e)?this.isRandomPriorityOptionUnavailableForAction(t,n):C(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=A(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):C(e)?this.isBraveryPickIntentSet(t):this.isPickIntentSetToChampion(t,e)}hasAnyPickIntentSet(t){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentChampionId!==null||this.localPlayerIntentIsBravery||u(t.championId)!==null||W(t.championId))}isBraveryPickIntentSet(t){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentIsBravery||W(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:u(t.championId)??this.localPlayerIntentChampionId}async delayAndRefreshAutoSelectPlan(t){const e=_e();console.debug(`auto-champion-select: Quick action is off, waiting ${e}ms before ${t.type}...`);const n=this.watchVersion;if(await T(e),!this.mounted||n!==this.watchVersion)return null;let o=null;try{await this.refreshSessionState(),o=this.findPendingAction(t)}catch(r){return console.debug("auto-champion-select: Failed to refresh champion select after action delay",r),null}if(!o||!this.isActionAvailable(o))return null;const s=this.getConfigForActionType(t.type,At());return s!=null&&s.enabled?this.createAutoSelectPlan(o,s):null}async resolveChampionIdsForPriorityOption(t,e,n){return C(e)?[]:p(e)?this.resolveRandomChampionIdsForAction(t,n):[e]}async resolveRandomChampionIdsForAction(t,e){if(t.type==="pick"&&t.isInProgress===!0){const r=this.getPickIntentChampionId(t);if(r!==null&&!this.isChampionUnavailableForAction(t,r,e))return[r]}const n=await this.fetchRandomCandidateChampionIds(t);if(n.length===0)return[];const o=n.filter(r=>!this.isChampionUnavailableForAction(t,r,e)),s=t.type==="pick"&&!this.hasConfiguredRandomPoolPositions(e)?await this.preferAssignedPositionRandomPickCandidates(o):await this.filterRandomChampionIdsByConfiguredPoolPositions(o,e);return ke(s)}async fetchRandomCandidateChampionIds(t){const e=t.type==="pick"?m.pickableChampionIds:m.bannableChampionIds;try{const n=await S("GET",e);if(!n.ok)return console.debug(`auto-champion-select: Failed to load random ${t.type} candidates`,n),[];const o=await n.json();return t.type==="ban"&&Re(o)?(console.debug("auto-champion-select: Random ban endpoint returned unrestricted sentinel, falling back to all champions..."),await this.fetchAllChampionIdsForRandomBan()):re(o)}catch(n){return console.debug(`auto-champion-select: Failed to load random ${t.type} candidates`,n),[]}}async fetchAllChampionIdsForRandomBan(){return(await Gt()).map(e=>e.id)}hasConfiguredRandomPoolPositions(t){return A(t.randomPoolPositions).length>0}async filterRandomChampionIdsByConfiguredPoolPositions(t,e){const n=A(e.randomPoolPositions);if(n.length===0)return t;const o=new Set(n),s=await j(),r=t.filter(a=>{var c;return(c=s[String(a)])==null?void 0:c.some(d=>o.has(d))});return r.length===0&&console.debug(`auto-champion-select: No random candidates matched ${n.join(", ")} restriction.`),r}async preferAssignedPositionRandomPickCandidates(t){if(!this.localPlayerAssignedPosition)return t;const e=await j(),n=t.filter(o=>{var s;return(s=e[String(o)])==null?void 0:s.includes(this.localPlayerAssignedPosition)});return n.length>0?n:t}async attemptChampionForAction(t,e,n,o={}){const s=u(e);if(s===null||this.isChampionUnavailableForAction(t,s,n))return P.TRY_NEXT_CHAMPION;if(this.isPickIntentSetToChampion(t,s)||(console.debug(`auto-champion-select: Trying to ${t.type} ${s}...`),(await this.selectChampion(t.id,s)).ok))return P.SATISFIED;console.debug(`auto-champion-select: Failed to ${t.type} ${s}, refreshing champ select state...`);const a=await this.refreshPendingAction(t);return!a||!this.isActionAvailable(a)?P.STOP_CYCLE:o.tryNextRandomCandidateOnFailure===!0?this.hasAnyPickIntentSet(a)?P.SATISFIED:(console.debug(`auto-champion-select: Failed random ${t.type} candidate ${s}, trying next ${t.type}...`),P.TRY_NEXT_CHAMPION):this.isChampionUnavailableForAction(a,s,n)?(console.debug(`auto-champion-select: ${s} is unavailable after refresh, trying next ${t.type}...`),P.TRY_NEXT_CHAMPION):P.STOP_CYCLE}isPickIntentSetToChampion(t,e){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentChampionId===e||u(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 ot(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 o=Dt(n,e);return this.localPlayerAssignedPosition?console.debug(`auto-champion-select: Picking ${e} but assigned position ${this.localPlayerAssignedPosition} is not in ${o.join(", ")}, skipping...`):console.debug(`auto-champion-select: Picking ${e} but no assigned position is available for ${o.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.teammateIntentChampionIds.has(e))if(n.force===!0)console.debug(`auto-champion-select: Banning ${e} but it's already picked, forcing...`);else return console.debug(`auto-champion-select: Banning ${e} but it's already picked, skipping...`),!0;if(t.type==="pick"&&this.pickedChampionIds.has(e))if(n.force===!0)console.debug(`auto-champion-select: Picking ${e} but it's already picked, forcing...`);else return console.debug(`auto-champion-select: Picking ${e} but it's already picked, skipping...`),!0;return!1}selectChampion(t,e){const n=m.champSelectAction(t);return S("PATCH",n,{body:{championId:e,completed:!0}})}}const O=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"}),l=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:O.dropdownOption,dropdownOptionSelected:`${O.dropdownOption}[selected]`,dropdownOptionsContainer:".ui-dropdown-options-container",dropdownOptions:".ui-dropdown-options",dropdownScrollable:O.scrollable,socialRosterGroupArrow:".arrow",socialRosterGroupHeader:".group-header",socialRosterGroupLabel:"span"});function Ct(){return document.querySelector(l.socialRoster)}function it(){return document.querySelector(l.champSelectButtons)}const Le=50,Me=100,V=210,K=40,U="controlado-position-filter",st="controlado-position-filter-visible",I="controlado-position-filter__badge",rt="controlado-position-filter__badge--active",St="controlado-placeholder",Ot="controlado-search",jt="controlado-filter-input",Qt="controlado-tag--search",X="controlado-quick-action",q="controlado-quick-action-toggle",Wt="controlado-quick-action-toggle--active",Be=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='black' d='M13.1 2 4 13.2h6.7L9.9 22 20 9.8h-6.9L13.1 2z'/%3E%3C/svg%3E")`,Vt="controlado-tag",Kt="controlado-filter-icon",B="controlado-filter-icon--trash",wt="controlado-champion-option__content",Et="controlado-champion-option__icon",Ne="controlado-champion-option__text",It="controlado-champion-option__name",Fe="controlado-champion-option__description",De="controlado-champion-option__static-icon",Tt=`
10
+ import{request as S,sleep as T,linkEndpoint as pt}from"https://cdn.jsdelivr.net/npm/balaclava-utils@latest";const ee="1.9.6",ne={enabled:!1},oe={enabled:!1,force:!1,quickAction:!1,champions:[432,235],randomAssignedPositions:[],randomPoolPositions:[],positionsByChampionId:{235:["BOTTOM","UTILITY"],432:["UTILITY"]}},ie={enabled:!1,force:!1,quickAction:!1,champions:[157,777,238,38],randomPoolPositions:[]},se={controladoAutoAccept:ne,controladoPick:oe,controladoBan:ie};function u(i){const t=Number(i);return Number.isSafeInteger(t)&&t>0?t:null}function re(i,t=null){const e=[],n=new Set,o=ae(t);if(!Array.isArray(i))return e;for(const s of i){const r=u(s);r===null||n.has(r)||o&&!o.has(r)||(e.push(r),n.add(r))}return e}function ae(i){return i?new Set(Array.from(i,u).filter(t=>t!==null)):null}const F=[{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"}],ce=new Set(F.map(i=>i.value));function x(i){const t=String(i??"").toUpperCase();return ce.has(t)?t:null}function A(i){if(!Array.isArray(i))return[];const t=new Set;for(const e of i){const n=x(e);n&&t.add(n)}return F.map(e=>e.value).filter(e=>t.has(e))}function G(i,t=null){const e={};if(!i||typeof i!="object"||Array.isArray(i))return e;const n=le(t);for(const[o,s]of Object.entries(i)){const r=u(o);if(r===null||!Array.isArray(s))continue;const a=String(r);if(n&&!n.has(a))continue;const c=[],d=new Set;for(const g of s){const z=x(g);!z||d.has(z)||(c.push(z),d.add(z))}c.length>0&&(e[a]=c)}return e}function le(i){if(!i)return null;const t=new Set;for(const e of i){const n=u(e);n!==null&&t.add(String(n))}return t}function mt(i){return F.find(t=>t.value===i)}function Dt(i,t){var n;const e=u(t);return e===null?[]:((n=i==null?void 0:i.positionsByChampionId)==null?void 0:n[String(e)])||[]}function de(i,t,e){const n=Dt(i,t);if(n.length===0)return!0;const o=x(e);return o!==null&&n.includes(o)}const b="random",E="bravery";function p(i){return i===b}function C(i){return i===E}function _(i){return p(i)?b:C(i)?E:u(i)}function w(i){const t=_(i);return t===null?null:String(t)}function ct(i,t=null){const e=[],n=new Set,o=he(t);if(!Array.isArray(i))return e;for(const s of i){const r=_(s);if(r===null)continue;const a=String(r);n.has(a)||typeof r=="number"&&o&&!o.has(r)||(e.push(r),n.add(a))}return e}function M(i){return i?Array.from(i,u).filter(t=>t!==null):[]}function he(i){return i?new Set(Array.from(i,u).filter(t=>t!==null)):null}const ft=new Set;function xt(i,t){return Object.prototype.hasOwnProperty.call(i,t)}function R(i,t){return xt(i,t)}function ue(i){return Array.isArray(i.priorityOptions)?i.priorityOptions:i.champions}function pe(i,t){return xt(i,"randomPoolPositions")?i.randomPoolPositions:t.randomPositions}function lt(){if(!globalThis.DataStore)throw new Error("DataStore is not available");return globalThis.DataStore}function me(i){return i!==null&&typeof i=="object"&&!Array.isArray(i)}function dt(i){if(i!==void 0)return JSON.parse(JSON.stringify(i))}function $t(i){const t=se[i];if(!t)throw new Error(`Unknown auto-champion-select config key: ${i}`);return dt(t)}function qt(i,t,e={}){const n=$t(i),o=me(t)?dt(t):{},s={...n,...o},r={enabled:s.enabled===!0};return R(n,"force")&&(r.force=s.force===!0),R(n,"quickAction")&&(r.quickAction=s.quickAction===!0),R(n,"champions")&&(r.priorityOptions=ct(ue(s),e.allowedChampionIds),r.champions=M(r.priorityOptions)),R(n,"randomAssignedPositions")&&(r.randomAssignedPositions=A(s.randomAssignedPositions)),R(n,"randomPoolPositions")&&(r.randomPoolPositions=A(pe(o,s))),R(n,"positionsByChampionId")&&(r.positionsByChampionId=G(s.positionsByChampionId,e.selectedChampionIds||r.champions)),r}function zt(i,t,e={}){const n=t===void 0?$t(i):t;return qt(i,n,e)}function k(i,t={}){const n=lt().get(i);return zt(i,n,t)}function fe(i,t,e={}){const n=lt(),o=qt(i,t,e);return n.set(i,o),o}function ge(i,t){return JSON.stringify(i)===JSON.stringify(t)}function Pe(i,t,e){ft.has(i)||(ft.add(i),console.warn(`auto-champion-select: Repaired ${i} 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 Yt(i,t={}){const e=lt(),n=e.get(i),o=zt(i,n,t);return(n===void 0||!ge(n,o))&&(n!==void 0&&Pe(i,n,o),e.set(i,o)),o}function H(i,t,e={}){const n=k(i,e),o=dt(n),s=t(o)||o;return fe(i,s,e)}const m=Object.freeze({readyCheckAccept:"/lol-matchmaking/v1/ready-check/accept",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(i){return`/lol-game-data/assets/v1/champion-icons/${i}.png`},champSelectAction(i){return`/lol-champ-select/v1/session/actions/${i}`}}),ye=1e3;function ht(i){let t=null;return function(){return t||(t=Promise.resolve().then(i).finally(()=>{t=null})),t}}function Ut(i,t={}){const e=[],n=new Set;if(!Array.isArray(i))return e;for(const o of i){if(!o||typeof o!="object")continue;const s=u(o.id),r=typeof o.name=="string"?o.name:"";s===null||!r||n.has(r)||(e.push({...o,id:s,name:r,squarePortraitPath:o.squarePortraitPath||m.championIcon(s),recommendedPositions:t[String(s)]||[]}),n.add(r))}return e.sort((o,s)=>o.name.localeCompare(s.name)),e}function be(i){const t={};if(!i||typeof i!="object"||Array.isArray(i))return t;for(const[e,n]of Object.entries(i))!n||typeof n!="object"||Array.isArray(n)||(t[e]=n.recommendedPositions);return G(t)}async function Ae(){try{const i=await S("GET",m.recommendedChampionPositions);return i.ok?be(await i.json()):(console.warn("auto-champion-select(recommended-champion-positions): Request failed",i),{})}catch(i){return console.warn("auto-champion-select(recommended-champion-positions): Failed to load",i),{}}}const j=ht(Ae);async function Ce(){let i=await S("GET",m.ownedChampions);for(;!i.ok;)console.debug("auto-champion-select(owned-champions-minimal): Retrying..."),i=await S("GET",m.ownedChampions),await T(ye);return Ut(await i.json(),await j())}async function Se(){const[i,t]=await Promise.all([S("GET",m.championSummary),j()]);return Ut(await i.json(),t)}const Oe=ht(Ce),Gt=ht(Se),gt=300,Pt=2e3,we=4e3,Ee=-1,Ht=-3,P=Object.freeze({SATISFIED:"satisfied",TRY_NEXT_CHAMPION:"try-next-champion",STOP_CYCLE:"stop-cycle"}),v=Object.freeze({CONTINUE:"continue-cycle",STOP:"stop-cycle"}),y=Object.freeze({READY:"ready",SKIP_ACTION:"skip-action",STOP_CYCLE:"stop-cycle"}),f=Object.freeze({SATISFIED:"satisfied",TRY_NEXT_PRIORITY_OPTION:"try-next-priority-option",STOP_CYCLE:"stop-cycle"});function ot(i){return Array.isArray(i)?i.flat():[]}function Ie(i){return ot(i).filter(t=>t.type==="ban"&&t.completed===!0).map(t=>t.championId)}function yt(i){return Array.isArray(i)?i:[]}function Q(i){const t=new Set;for(const e of i){const n=u(e);n!==null&&t.add(n)}return t}function bt(i){return i.type==="pick"?0:1}function At(){return{pickConfig:k("controladoPick"),banConfig:k("controladoBan")}}function Te(i){return i.quickAction===!0}function _e(){const i=we-Pt;return Pt+Math.floor(Math.random()*(i+1))}function ke(i){const t=[...i];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 Re(i){return Array.isArray(i)&&i.length===1&&i[0]===Ee}function W(i){return Number(i)===Ht}class ve{constructor(){this.session=null,this.actions=null,this.localPlayerCellId=null,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.watchTask=null,this.watchVersion=0,this.mounted=!1}mount(){this.mounted||(this.mounted=!0,this.rejectedBraveryActionIds.clear(),this.watchVersion+=1,this.watchTask||(this.watchTask=this.watch()))}unmount(){this.mounted&&(this.mounted=!1,this.rejectedBraveryActionIds.clear(),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 T(gt);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 T(gt)}}finally{this.watchTask=null}}async refreshSessionState(){var s,r;const t=await S("GET",m.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=yt(this.session.myTeam),n=yt(this.session.theirTeam),o=e.find(a=>a.cellId===this.localPlayerCellId);this.localPlayerAssignedPosition=x(o==null?void 0:o.assignedPosition),this.localPlayerIntentChampionId=u(o==null?void 0:o.championPickIntent),this.localPlayerIntentIsBravery=W(o==null?void 0:o.championPickIntent),this.pickedChampionIds=Q([...e,...n].map(a=>a.championId)),this.bannedChampionIds=Q([...((s=this.session.bans)==null?void 0:s.myTeamBans)||[],...((r=this.session.bans)==null?void 0:r.theirTeamBans)||[],...Ie(this.actions)]),this.teammateIntentChampionIds=Q(e.map(a=>a.championPickIntent))}async runAutoSelectCycle(){const t=At();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)===v.STOP)return}async runAutoSelectForAction(t,e){const n=await this.prepareActionForAutoSelect(t,e);switch(n.status){case y.READY:return this.tryAutoSelectPlan(n.plan);case y.SKIP_ACTION:return v.CONTINUE;case y.STOP_CYCLE:return v.STOP;default:throw new Error(`Unexpected auto-select plan status: ${n.status}`)}}async prepareActionForAutoSelect(t,e){if(!this.isActionAvailable(t))return{status:y.SKIP_ACTION};const n=this.getConfigForActionType(t.type,e);if(!(n!=null&&n.enabled))return{status:y.SKIP_ACTION};const o=this.createAutoSelectPlan(t,n);if(!o)return{status:y.SKIP_ACTION};const s=this.createPlanLimitedToAlreadySatisfiedPriorityOption(o);if(s)return{status:y.READY,plan:s};if(Te(n))return{status:y.READY,plan:o};const r=await this.delayAndRefreshAutoSelectPlan(t);return r?{status:y.READY,plan:this.createPlanLimitedToAlreadySatisfiedPriorityOption(r)||r}:{status:y.STOP_CYCLE}}async tryAutoSelectPlan(t){for(const e of t.priorityOptions){const n=await this.tryPriorityOptionForAction(t.action,e,t.config);if(n===f.SATISFIED)return v.CONTINUE;if(n===f.STOP_CYCLE)return v.STOP}return v.CONTINUE}async tryPriorityOptionForAction(t,e,n){if(this.isPriorityOptionAlreadySatisfied(t,e))return f.SATISFIED;if(C(e))return this.tryBraveryForAction(t);const o=await this.resolveChampionIdsForPriorityOption(t,e,n),s=p(e)&&!this.isLockingExistingPickIntent(t,o);for(const r of o){const a={tryNextRandomCandidateOnFailure:s},c=await this.attemptChampionForAction(t,r,n,a);if(c===P.SATISFIED)return f.SATISFIED;if(c===P.STOP_CYCLE)return f.STOP_CYCLE}return f.TRY_NEXT_PRIORITY_OPTION}async tryBraveryForAction(t){if(t.type!=="pick")return f.TRY_NEXT_PRIORITY_OPTION;if(this.isBraveryPickIntentSet(t))return f.SATISFIED;console.debug("auto-champion-select: Trying to pick Bravery...");const e=await this.selectChampion(t.id,Ht);console.debug(e.ok?"auto-champion-select: Bravery request accepted, refreshing champ select state...":"auto-champion-select: Failed to pick Bravery, refreshing champ select state...");const n=await this.refreshPendingAction(t);return!n||!this.isActionAvailable(n)?e.ok?f.SATISFIED:f.STOP_CYCLE:this.isBraveryPickIntentSet(n)?f.SATISFIED:(this.rejectedBraveryActionIds.add(t.id),console.debug("auto-champion-select: Bravery was not applied after refresh, trying next pick..."),f.TRY_NEXT_PRIORITY_OPTION)}getLocalPlayerActions(){return ot(this.actions).filter(t=>this.isPendingLocalPlayerAction(t)).sort((t,e)=>bt(t)-bt(e))}isPendingLocalPlayerAction(t){return t.actorCellId===this.localPlayerCellId&&t.completed===!1}isActionAvailable(t){return t.type==="pick"||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 ct(e.priorityOptions||e.champions).filter(n=>!this.isPriorityOptionUnavailableForAction(t,n,e))}isPriorityOptionUnavailableForAction(t,e,n){return p(e)?this.isRandomPriorityOptionUnavailableForAction(t,n):C(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=A(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):C(e)?this.isBraveryPickIntentSet(t):this.isPickIntentSetToChampion(t,e)}hasAnyPickIntentSet(t){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentChampionId!==null||this.localPlayerIntentIsBravery||u(t.championId)!==null||W(t.championId))}isBraveryPickIntentSet(t){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentIsBravery||W(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:u(t.championId)??this.localPlayerIntentChampionId}async delayAndRefreshAutoSelectPlan(t){const e=_e();console.debug(`auto-champion-select: Quick action is off, waiting ${e}ms before ${t.type}...`);const n=this.watchVersion;if(await T(e),!this.mounted||n!==this.watchVersion)return null;let o=null;try{await this.refreshSessionState(),o=this.findPendingAction(t)}catch(r){return console.debug("auto-champion-select: Failed to refresh champion select after action delay",r),null}if(!o||!this.isActionAvailable(o))return null;const s=this.getConfigForActionType(t.type,At());return s!=null&&s.enabled?this.createAutoSelectPlan(o,s):null}async resolveChampionIdsForPriorityOption(t,e,n){return C(e)?[]:p(e)?this.resolveRandomChampionIdsForAction(t,n):[e]}async resolveRandomChampionIdsForAction(t,e){if(t.type==="pick"&&t.isInProgress===!0){const r=this.getPickIntentChampionId(t);if(r!==null&&!this.isChampionUnavailableForAction(t,r,e))return[r]}const n=await this.fetchRandomCandidateChampionIds(t);if(n.length===0)return[];const o=n.filter(r=>!this.isChampionUnavailableForAction(t,r,e)),s=t.type==="pick"&&!this.hasConfiguredRandomPoolPositions(e)?await this.preferAssignedPositionRandomPickCandidates(o):await this.filterRandomChampionIdsByConfiguredPoolPositions(o,e);return ke(s)}async fetchRandomCandidateChampionIds(t){const e=t.type==="pick"?m.pickableChampionIds:m.bannableChampionIds;try{const n=await S("GET",e);if(!n.ok)return console.debug(`auto-champion-select: Failed to load random ${t.type} candidates`,n),[];const o=await n.json();return t.type==="ban"&&Re(o)?(console.debug("auto-champion-select: Random ban endpoint returned unrestricted sentinel, falling back to all champions..."),await this.fetchAllChampionIdsForRandomBan()):re(o)}catch(n){return console.debug(`auto-champion-select: Failed to load random ${t.type} candidates`,n),[]}}async fetchAllChampionIdsForRandomBan(){return(await Gt()).map(e=>e.id)}hasConfiguredRandomPoolPositions(t){return A(t.randomPoolPositions).length>0}async filterRandomChampionIdsByConfiguredPoolPositions(t,e){const n=A(e.randomPoolPositions);if(n.length===0)return t;const o=new Set(n),s=await j(),r=t.filter(a=>{var c;return(c=s[String(a)])==null?void 0:c.some(d=>o.has(d))});return r.length===0&&console.debug(`auto-champion-select: No random candidates matched ${n.join(", ")} restriction.`),r}async preferAssignedPositionRandomPickCandidates(t){if(!this.localPlayerAssignedPosition)return t;const e=await j(),n=t.filter(o=>{var s;return(s=e[String(o)])==null?void 0:s.includes(this.localPlayerAssignedPosition)});return n.length>0?n:t}async attemptChampionForAction(t,e,n,o={}){const s=u(e);if(s===null||this.isChampionUnavailableForAction(t,s,n))return P.TRY_NEXT_CHAMPION;if(this.isPickIntentSetToChampion(t,s)||(console.debug(`auto-champion-select: Trying to ${t.type} ${s}...`),(await this.selectChampion(t.id,s)).ok))return P.SATISFIED;console.debug(`auto-champion-select: Failed to ${t.type} ${s}, refreshing champ select state...`);const a=await this.refreshPendingAction(t);return!a||!this.isActionAvailable(a)?P.STOP_CYCLE:o.tryNextRandomCandidateOnFailure===!0?this.hasAnyPickIntentSet(a)?P.SATISFIED:(console.debug(`auto-champion-select: Failed random ${t.type} candidate ${s}, trying next ${t.type}...`),P.TRY_NEXT_CHAMPION):this.isChampionUnavailableForAction(a,s,n)?(console.debug(`auto-champion-select: ${s} is unavailable after refresh, trying next ${t.type}...`),P.TRY_NEXT_CHAMPION):P.STOP_CYCLE}isPickIntentSetToChampion(t,e){return t.type==="pick"&&t.isInProgress!==!0&&(this.localPlayerIntentChampionId===e||u(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 ot(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 o=Dt(n,e);return this.localPlayerAssignedPosition?console.debug(`auto-champion-select: Picking ${e} but assigned position ${this.localPlayerAssignedPosition} is not in ${o.join(", ")}, skipping...`):console.debug(`auto-champion-select: Picking ${e} but no assigned position is available for ${o.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.teammateIntentChampionIds.has(e))if(n.force===!0)console.debug(`auto-champion-select: Banning ${e} but it's already picked, forcing...`);else return console.debug(`auto-champion-select: Banning ${e} but it's already picked, skipping...`),!0;if(t.type==="pick"&&this.pickedChampionIds.has(e))if(n.force===!0)console.debug(`auto-champion-select: Picking ${e} but it's already picked, forcing...`);else return console.debug(`auto-champion-select: Picking ${e} but it's already picked, skipping...`),!0;return!1}selectChampion(t,e){const n=m.champSelectAction(t);return S("PATCH",n,{body:{championId:e,completed:!0}})}}const O=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"}),l=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:O.dropdownOption,dropdownOptionSelected:`${O.dropdownOption}[selected]`,dropdownOptionsContainer:".ui-dropdown-options-container",dropdownOptions:".ui-dropdown-options",dropdownScrollable:O.scrollable,socialRosterGroupArrow:".arrow",socialRosterGroupHeader:".group-header",socialRosterGroupLabel:"span"});function Ct(){return document.querySelector(l.socialRoster)}function it(){return document.querySelector(l.champSelectButtons)}const Le=50,Me=100,V=210,K=40,U="controlado-position-filter",st="controlado-position-filter-visible",I="controlado-position-filter__badge",rt="controlado-position-filter__badge--active",St="controlado-placeholder",Ot="controlado-search",jt="controlado-filter-input",Qt="controlado-tag--search",X="controlado-quick-action",q="controlado-quick-action-toggle",Wt="controlado-quick-action-toggle--active",Be=`url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3E%3Cpath fill='black' d='M13.1 2 4 13.2h6.7L9.9 22 20 9.8h-6.9L13.1 2z'/%3E%3C/svg%3E")`,Vt="controlado-tag",Kt="controlado-filter-icon",B="controlado-filter-icon--trash",wt="controlado-champion-option__content",Et="controlado-champion-option__icon",Ne="controlado-champion-option__text",It="controlado-champion-option__name",Fe="controlado-champion-option__description",De="controlado-champion-option__static-icon",Tt=`
11
11
  ${l.dropdownRoot} {
12
12
  position: relative;
13
13
  }
@@ -228,4 +228,4 @@ import{request as S,sleep as T,linkEndpoint as pt}from"https://cdn.jsdelivr.net/
228
228
  background-color: #f0e6d2;
229
229
  filter: drop-shadow(0 0 3px rgba(200, 170, 110, 0.75));
230
230
  }
231
- `;function J(i){const t=document.createElement(O.dropdownOption);return t.setAttribute("slot",O.dropdownOption),t.innerText=i,t}class xe{constructor(t,e,n,o={}){this.dropdownElement=t,this.placeholderText=e,this.searchPlaceholderText=o.searchPlaceholderText||"Search",this.quickActionLabel=o.quickActionLabel||"Pick/ban instantly",this.staticOptions=Array.isArray(o.staticOptions)?o.staticOptions:[],this.isQuickActionEnabled=typeof o.isQuickActionEnabled=="function"?o.isQuickActionEnabled:null,this.onQuickActionToggle=typeof o.onQuickActionToggle=="function"?o.onQuickActionToggle:null,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=J(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),o=this.createChampionOption(e,n);n.length>0&&(this.hasRecommendedPositionData=!0),this.dropdownElement.appendChild(o)}this.hasRecommendedPositionData||(this.activePositionFilter=null),this.applyOptionFilters()}createChampionOption(t,e){const n=J("");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=J(""),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(wt);const n=document.createElement("img");n.classList.add(Et),n.src=t.squarePortraitPath,n.alt="",n.draggable=!1,n.loading="lazy";const o=document.createElement("span");return o.classList.add(It),o.innerText=t.name,e.append(n,o),e}createStaticOptionContent(t,e=""){const n=document.createElement("span");n.classList.add(wt);const o=t.iconPath?document.createElement("img"):document.createElement("span");o.classList.add(Et),t.iconClass&&o.classList.add(t.iconClass),t.iconPath?(o.src=t.iconPath,o.alt="",o.draggable=!1,o.loading="lazy"):(o.classList.add(De),o.innerText=t.iconText||"?");const s=document.createElement("span");s.classList.add(It),s.innerText=t.label;const r=document.createElement("span");if(r.classList.add(Ne),r.appendChild(s),e){const a=document.createElement("span");a.classList.add(Fe),a.innerText=e,r.appendChild(a)}return n.append(o,r),n}getChampionRecommendedPositions(t){return Array.isArray(t.recommendedPositions)?t.recommendedPositions:[]}async waitForRender(){for(let t=0;t<Le;t++){const e=this.dropdownElement.shadowRoot;if(this.dropdownElement.isConnected&&(e!=null&&e.querySelector(l.dropdownCurrent)))return e;await T(Me)}return null}ensureSearchPlaceholder(t){if(t.querySelector(`#${St}`))return;const e=t.querySelector(l.dropdownCurrent);e&&e.appendChild(this.createSearchPlaceholder())}ensureQuickActionToggle(t){if(!this.isQuickActionAvailable()||t.querySelector(`#${X}`)){this.syncQuickActionToggle(t);return}const e=t.querySelector(l.dropdownCurrent);e&&(e.appendChild(this.createQuickActionToggle()),this.syncQuickActionToggle(t))}ensurePositionFilter(t){var n;const e=t.querySelector(l.dropdownOptionsContainer);if(e){if(!this.hasRecommendedPositionData){(n=t.querySelector(`.${U}`))==null||n.remove(),e.classList.remove(st),this.activePositionFilter=null;return}e.classList.add(st),t.querySelector(`.${U}`)||e.insertBefore(this.createPositionFilter(),e.firstChild),this.syncPositionFilter(t)}}createPositionFilter(){const t=document.createElement("div");t.classList.add(U),t.setAttribute("role","toolbar"),t.setAttribute("aria-label","Filter champions by position");for(const e of F)t.appendChild(this.createPositionFilterBadge(e));return t}createPositionFilterBadge(t){const e=document.createElement("button");e.classList.add(I),e.type="button",e.dataset.position=t.value,e.title=t.label,e.setAttribute("aria-label",t.label),e.setAttribute("aria-pressed","false");const n=document.createElement("img");return n.src=t.iconPath,n.alt="",n.draggable=!1,e.appendChild(n),e.addEventListener("pointerdown",o=>{o.preventDefault(),o.stopPropagation()}),e.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),this.togglePositionFilter(t.value)}),e}createSearchPlaceholder(){const t=document.createElement("div");t.classList.add(Vt,Qt),t.id=St;const e=document.createElement("input");e.classList.add(jt),e.id=Ot,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(Kt),n.addEventListener("click",()=>{n.classList.contains(B)&&this.clearSearch(e,n)}),e.addEventListener("input",o=>{this.ensureOpen(),this.setSearchQuery(o.target.value),n.classList.toggle(B,!!o.target.value)}),["pointerdown","click"].forEach(o=>{t.addEventListener(o,s=>s.stopPropagation()),n.addEventListener(o,s=>s.stopPropagation())}),["pointerdown","focusin"].forEach(o=>{e.addEventListener(o,s=>s.stopPropagation(),!0)}),t.appendChild(n),t.appendChild(e),t}createQuickActionToggle(){const t=document.createElement("button");return t.classList.add(q),t.id=X,t.type="button",t.title=this.quickActionLabel,t.setAttribute("aria-label",this.quickActionLabel),t.setAttribute("aria-pressed","false"),["pointerdown","click"].forEach(e=>{t.addEventListener(e,n=>{n.preventDefault(),n.stopPropagation()})}),t.addEventListener("click",()=>{var e;(e=this.onQuickActionToggle)==null||e.call(this),this.syncQuickActionToggle()}),t}isQuickActionAvailable(){return!!(this.isQuickActionEnabled&&this.onQuickActionToggle)}syncQuickActionToggle(t=this.dropdownElement.shadowRoot){if(!this.isQuickActionAvailable()||!t)return;const e=t.querySelector(`#${X}`);if(!e)return;const n=this.isQuickActionEnabled()===!0;e.classList.toggle(Wt,n),e.setAttribute("aria-pressed",String(n)),e.title=this.quickActionLabel,e.setAttribute("aria-label",this.quickActionLabel)}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(`.${I}`).forEach(e=>{const n=e.dataset.position===this.activePositionFilter;e.classList.toggle(rt,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(l.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(l.dropdownOptionSelected).forEach(e=>{e.removeAttribute("selected")}),(t=this.placeholderOption)==null||t.setAttribute("selected","true"),this.withShadowRoot(e=>{var s;const n=e.querySelector(`#${Ot}`),o=e.querySelector(`.${B}`);n&&o?this.clearSearch(n,o):(n&&(n.value="",this.setSearchQuery("")),o&&o.classList.remove(B)),this.isOpen()&&((s=e.querySelector(l.dropdownCurrent))==null||s.click())})}isOpen(){return this.dropdownElement.classList.contains("active")}ensureOpen(){this.isOpen()||this.withShadowRoot(t=>{const e=t.querySelector(l.dropdownCurrent);e&&e.click()})}patchDropdownShadowDom(){this.withShadowRoot(t=>{this.ensureDropdownOpensUpward(t),this.injectDropdownSearchStyles(t),this.ensurePositionFilter(t)})}ensureDropdownOpensUpward(t){var e;(e=t.querySelector(l.dropdownRoot))==null||e.classList.add("opens-upward")}injectDropdownSearchStyles(t){const e=t.querySelector("style[data-controlado='dropdown-tags']");if(e){e.textContent=Tt;return}const n=document.createElement("style");n.dataset.controlado="dropdown-tags",n.textContent=Tt,t.appendChild(n)}withShadowRoot(t){const e=this.dropdownElement.shadowRoot;e&&t(e)}}const $e=".champion-priority-selector__position-badge",qe=".champion-priority-selector__position-option",Z=".champion-priority-selector__remove",tt="✕",_t="?",$="Random",L="Bravery",ze="For Arena mode.",kt="/fe/lol-champ-select/images/champion-grid/bravery-champion.png",Ye="controlado-champion-option__icon--bravery",Ue="champion-priority-selector__icon--bravery",Ge=0,Rt=1,Y=8,h=Object.freeze({CHAMPION_ASSIGNED:"champion-assigned",RANDOM_ASSIGNED:"random-assigned",RANDOM_POOL:"random-pool"}),He=5,je=150,Qe="cubic-bezier(0.2, 0, 0, 1)";class vt{constructor(t,e,n,o={}){this.element=this.createRootElement(),this.dropdownElement=this.createDropdownElement();const s=[{value:b,label:$,description:o.randomOptionDescription,iconText:_t}];o.enableBraveryOption===!0&&s.push({value:E,label:L,description:ze,iconPath:kt,iconClass:Ye}),this.championDropdown=new xe(this.dropdownElement,t,c=>this.addPriorityOption(c),{quickActionLabel:o.quickActionLabel,searchPlaceholderText:o.searchPlaceholderText,staticOptions:s,isQuickActionEnabled:()=>this.isQuickActionEnabled(),onQuickActionToggle:()=>this.toggleQuickAction()});const{scrollElement:r,trackElement:a}=this.createSelectedChampionsScroll();this.scrollElement=r,this.trackElement=a,this.enablePositionRestrictions=o.enablePositionRestrictions===!0,this.enableRandomPoolPositionFilters=o.enableRandomPoolPositionFilters===!0,this.enableRandomAssignedPositionRestrictions=o.enableRandomAssignedPositionRestrictions===!0,this.enableBraveryOption=o.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(t),this.element.append(this.dropdownElement,this.scrollElement),this.positionMenuElement&&this.element.appendChild(this.positionMenuElement),this.config=null,this.configKey=e,this.quickAction=!1,this.loadChampions=n,this.champions=[],this.championById=new Map,this.selectedPriorityOptions=[],this.optionButtons=new Map,this.dragState=null,this.handleWindowPointerMove=c=>this.moveDrag(c),this.handleWindowPointerUp=c=>this.finishDrag(c),this.handleWindowPointerCancel=c=>this.cancelDrag(c),this.handlePositionMenuOutsidePointerDown=c=>this.closePositionMenuOnOutsidePointerDown(c),this.handlePositionMenuKeyDown=c=>this.closePositionMenuOnKeyDown(c),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(O.dropdown);return t.classList.add("dropdown-champions-default","dropdown-drop-up"),t}createSelectedChampionsScroll(){const t=document.createElement(O.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="No champions";const o=document.createElement("span"),s=t.replace(/^Add\s+/i,"").toLowerCase();return o.innerText=`Use dropdown to add ${s} option`,e.append(n,o),e}createPositionMenu(){const t=document.createElement("div");t.classList.add("champion-priority-selector__position-menu"),t.hidden=!0;for(const e of F)t.appendChild(this.createPositionOption(e));return t}createPositionOption(t){const e=document.createElement("button");e.classList.add("champion-priority-selector__position-option"),e.type="button",e.dataset.position=t.value,e.title=t.label,e.setAttribute("aria-label",t.label),e.setAttribute("aria-pressed","false"),e.addEventListener("pointerdown",o=>o.stopPropagation()),e.addEventListener("click",o=>{o.stopPropagation(),this.togglePositionMenuPosition(t.value)});const n=document.createElement("img");return n.src=t.iconPath,n.alt=t.label,n.draggable=!1,e.appendChild(n),e}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=Yt(this.configKey,{allowedChampionIds:t}),this.quickAction=this.config.quickAction===!0,this.selectedPriorityOptions=ct(this.config.priorityOptions||this.config.champions,t).filter(n=>this.isPriorityOptionEnabled(n)),this.enablePositionRestrictions&&(this.positionsByChampionId=G(this.config.positionsByChampionId,M(this.selectedPriorityOptions))),this.enableRandomAssignedPositionRestrictions&&(this.randomAssignedPositions=A(this.config.randomAssignedPositions)),this.enableRandomPoolPositionFilters&&(this.randomPoolPositions=A(this.config.randomPoolPositions)),this.championDropdown.renderOptions(this.champions),this.renderSelectedPriorityOptions();const e=await this.championDropdown.waitForRender();e&&(this.championDropdown.ensureSearchPlaceholder(e),this.championDropdown.ensureQuickActionToggle(e),this.championDropdown.patchDropdownShadowDom())}getAllowedChampionIds(){return new Set(this.championById.keys())}isQuickActionEnabled(){return this.quickAction===!0}isPriorityOptionEnabled(t){return!C(t)||this.enableBraveryOption}toggleQuickAction(){const t=this.getAllowedChampionIds();return this.config=H(this.configKey,e=>(e.quickAction=e.quickAction!==!0,e),{allowedChampionIds:t,selectedChampionIds:M(this.selectedPriorityOptions)}),this.quickAction=this.config.quickAction===!0,this.championDropdown.syncQuickActionToggle(),this.quickAction}addPriorityOption(t){const e=_(t);e===null||this.selectedPriorityOptions.includes(e)||!this.isPriorityOptionEnabled(e)||!p(e)&&!C(e)&&!this.championById.has(e)||(this.selectedPriorityOptions.push(e),this.renderSelectedPriorityOptions(),this.saveConfig())}removePriorityOption(t){var s;const e=_(t),n=this.selectedPriorityOptions.indexOf(e);if(e===null||n===-1)return;this.selectedPriorityOptions.splice(n,1);const o=typeof e=="number"?e:null;((s=this.positionMenuTarget)==null?void 0:s.option)===e&&this.closePositionMenu(),this.enablePositionRestrictions&&o!==null&&delete this.positionsByChampionId[String(o)],this.enableRandomAssignedPositionRestrictions&&p(e)&&(this.randomAssignedPositions=[]),this.enableRandomPoolPositionFilters&&p(e)&&(this.randomPoolPositions=[]),this.renderSelectedPriorityOptions(),this.saveConfig()}movePriorityOptionToIndex(t,e){const n=_(t),o=this.selectedPriorityOptions.indexOf(n);if(n===null||o===-1)return!1;const[s]=this.selectedPriorityOptions.splice(o,1),r=Math.max(0,Math.min(e,this.selectedPriorityOptions.length));return this.selectedPriorityOptions.splice(r,0,s),o!==r}syncPositionsByChampionId(){this.enablePositionRestrictions&&(this.positionsByChampionId=G(this.positionsByChampionId,M(this.selectedPriorityOptions)))}syncRandomPoolPositions(){this.enableRandomPoolPositionFilters&&(this.randomPoolPositions=A(this.randomPoolPositions))}syncRandomAssignedPositions(){this.enableRandomAssignedPositionRestrictions&&(this.randomAssignedPositions=A(this.randomAssignedPositions))}saveConfig(){this.syncPositionsByChampionId(),this.syncRandomAssignedPositions(),this.syncRandomPoolPositions();const t=this.getAllowedChampionIds();this.config=H(this.configKey,e=>(e.priorityOptions=[...this.selectedPriorityOptions],e.champions=M(this.selectedPriorityOptions),this.enableRandomAssignedPositionRestrictions&&(e.randomAssignedPositions=[...this.randomAssignedPositions]),this.enableRandomPoolPositionFilters&&(e.randomPoolPositions=[...this.randomPoolPositions]),this.enablePositionRestrictions&&(e.positionsByChampionId={...this.positionsByChampionId}),e),{allowedChampionIds:t,selectedChampionIds:M(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=>w(s)));for(const[s,r]of this.optionButtons)n.has(s)||(r.remove(),this.optionButtons.delete(s));if(this.selectedPriorityOptions.length===0){this.trackElement.replaceChildren(this.emptyElement);return}this.emptyElement.remove();const o=this.selectedPriorityOptions.map((s,r)=>this.getPriorityOptionButton(s,r)).filter(Boolean);this.trackElement.append(...o),t&&this.animateReorder(t,e)}getPriorityOptionButton(t,e){return p(t)?this.getRandomOptionButton(e):C(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 o=String(t);let s=this.optionButtons.get(o);s||(s=this.createIconButton(n),this.optionButtons.set(o,s)),s.dataset.rank=String(e+1),s.classList.toggle("champion-priority-selector__icon--random",!1);const r=this.getChampionPositionTitleSuffix(t);s.title=`${e+1}. ${n.name}${r}`,s.setAttribute("aria-label",`${e+1}. ${n.name}${r}`);const a=s.querySelector("img");a.src=n.squarePortraitPath,a.alt=n.name;const c=s.querySelector(Z);return c.setAttribute("aria-label",`Remove ${n.name}`),c.title=`Remove ${n.name}`,this.renderPositionBadge(s,t),s}getRandomOptionButton(t){let e=this.optionButtons.get(b);e||(e=this.createRandomOptionButton(),this.optionButtons.set(b,e)),e.dataset.rank=String(t+1);const n=this.getRandomPositionTitleSuffix();e.title=`${t+1}. ${$}${n}`,e.setAttribute("aria-label",`${t+1}. ${$}${n}`);const o=e.querySelector(Z);return o.setAttribute("aria-label",`Remove ${$}`),o.title=`Remove ${$}`,this.renderPositionBadge(e,b),e}getBraveryOptionButton(t){let e=this.optionButtons.get(E);e||(e=this.createBraveryOptionButton(),this.optionButtons.set(E,e)),e.dataset.rank=String(t+1),e.title=`${t+1}. ${L}`,e.setAttribute("aria-label",`${t+1}. ${L}`);const n=e.querySelector("img");n.src=kt,n.alt=L;const o=e.querySelector(Z);return o.setAttribute("aria-label",`Remove ${L}`),o.title=`Remove ${L}`,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 o=document.createElement("button");if(o.classList.add("champion-priority-selector__remove"),o.type="button",o.dataset.icon=tt,o.addEventListener("pointerdown",s=>s.stopPropagation()),o.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:h.CHAMPION_ASSIGNED};e.addEventListener("contextmenu",r=>this.openPositionMenu(r,s))}return e.append(n,o),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=tt,n.addEventListener("pointerdown",o=>o.stopPropagation()),n.addEventListener("click",o=>{o.stopPropagation(),this.removePriorityOption(b)}),t.addEventListener("pointerdown",o=>this.startDrag(o,b)),t.addEventListener("auxclick",o=>this.removePriorityOptionOnMiddleClick(o,b)),this.enableRandomPoolPositionFilters){const o={option:b,kind:h.RANDOM_POOL};t.addEventListener("contextmenu",s=>this.openPositionMenu(s,o))}return t.append(e,n),t}createBraveryOptionButton(){const t=document.createElement("div");t.classList.add("champion-priority-selector__icon",Ue),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=tt,n.addEventListener("pointerdown",o=>o.stopPropagation()),n.addEventListener("click",o=>{o.stopPropagation(),this.removePriorityOption(E)}),t.addEventListener("pointerdown",o=>this.startDrag(o,E)),t.addEventListener("auxclick",o=>this.removePriorityOptionOnMiddleClick(o,E)),t.append(e,n),t}getChampionAllowedPositions(t){const e=u(t);return e===null?[]:this.positionsByChampionId[String(e)]||[]}getRandomPoolPositions(){return this.randomPoolPositions}getRandomAssignedPositions(){return this.randomAssignedPositions}getPositionLabels(t){return t.map(e=>{var n;return(n=mt(e))==null?void 0:n.label}).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(`runs only when assigned lane matches ${this.formatPositionLabelsForSentence(e)}`),n.length>0&&t.push(`filters random pool to ${this.formatPositionLabelsForSentence(n)}`),t.length>0?` (${t.join("; ")})`:""}formatPositionLabelsForSentence(t){return t.length<=1?t[0]||"":t.length===2?`${t[0]} or ${t[1]}`:`${t.slice(0,-1).join(", ")}, or ${t[t.length-1]}`}renderPositionBadge(t,e){t.querySelectorAll($e).forEach(o=>o.remove());const n=_(e);if(n!==null)for(const o of this.getPositionBadgeTargetsForOption(n)){const s=this.createPositionBadge(o);s&&t.appendChild(s)}}getPositionBadgeTargetsForOption(t){return this.selectedPriorityOptions.includes(t)?p(t)?[{option:t,kind:h.RANDOM_ASSIGNED},{option:t,kind:h.RANDOM_POOL}].filter(e=>this.canOpenPositionMenuForTarget(e)):C(t)?[]:[{option:t,kind:h.CHAMPION_ASSIGNED}].filter(e=>this.canOpenPositionMenuForTarget(e)):[]}createPositionBadge(t){const e=this.getAllowedPositionsForPositionMenuTarget(t),n=this.getAllowedPositionLabelsForPositionMenuTarget(t),o=t.kind===h.RANDOM_POOL,s=document.createElement("button");if(s.classList.add("champion-priority-selector__position-badge"),s.classList.toggle("champion-priority-selector__position-badge--random",o),s.type="button",s.dataset.positionTarget=t.kind,s.title=this.getPositionBadgeTitle(n,t),s.setAttribute("aria-label",s.title),s.addEventListener("pointerdown",c=>c.stopPropagation()),s.addEventListener("click",c=>this.openPositionMenu(c,t,s)),o)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 r=mt(e[0]);if(!r)return null;e.length>1&&(s.dataset.count=String(e.length));const a=document.createElement("img");return a.src=r.iconPath,a.alt=r.label,a.draggable=!1,s.appendChild(a),s}getPositionBadgeTitle(t,e){return e.kind===h.RANDOM_ASSIGNED?t.length===0?"The plugin can use Random in any lane. Click to run it only in selected draft lanes.":`The plugin will use Random only when your assigned lane matches ${this.formatPositionLabelsForSentence(t)}. Draft modes only. Click to edit.`:e.kind===h.RANDOM_POOL?t.length===0?"The plugin can choose any available champion at random. Click to filter the pool first.":`The plugin filters Random to champions for ${this.formatPositionLabelsForSentence(t)}, then picks one. Click to edit.`:t.length>0?`The plugin will pick this champion only when your assigned lane matches ${this.formatPositionLabelsForSentence(t)}. Draft modes only. Click to edit.`:"The plugin can pick this champion in any lane. Click to limit it to selected draft lanes."}canOpenPositionMenuForTarget(t){if(!this.selectedPriorityOptions.includes(t.option))return!1;switch(t.kind){case h.CHAMPION_ASSIGNED:return typeof t.option=="number"&&this.enablePositionRestrictions;case h.RANDOM_ASSIGNED:return p(t.option)&&this.enableRandomAssignedPositionRestrictions;case h.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=_(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 h.CHAMPION_ASSIGNED:return this.getChampionAllowedPositions(t.option);case h.RANDOM_ASSIGNED:return this.getRandomAssignedPositions();case h.RANDOM_POOL:return this.getRandomPoolPositions();default:return[]}}getAllowedPositionLabelsForPositionMenuTarget(t){return this.getPositionLabels(this.getAllowedPositionsForPositionMenuTarget(t))}setAllowedPositionsForPositionMenuTarget(t,e){switch(t.kind){case h.CHAMPION_ASSIGNED:{const n=String(t.option);e.length>0?this.positionsByChampionId[n]=e:delete this.positionsByChampionId[n];break}case h.RANDOM_ASSIGNED:this.randomAssignedPositions=e;break;case h.RANDOM_POOL:this.randomPoolPositions=e;break}}openPositionMenu(t,e,n=null){if(!this.positionMenuElement)return;const o=this.normalizePositionMenuTarget(e);if(o===null)return;t.preventDefault(),t.stopPropagation(),this.positionMenuTarget=o,this.renderPositionMenu(),this.positionMenuElement.hidden=!1,this.positionMenuElement.style.left="0px",this.positionMenuElement.style.top="0px";const{left:s,top:r}=this.getPositionMenuCoordinates(t,n);this.positionMenuElement.style.left=`${s}px`,this.positionMenuElement.style.top=`${r}px`,document.addEventListener("pointerdown",this.handlePositionMenuOutsidePointerDown,!0),document.addEventListener("keydown",this.handlePositionMenuKeyDown,!0)}getPositionMenuCoordinates(t,e=null){const n=this.positionMenuElement.getBoundingClientRect();let o=t.clientX,s=t.clientY;if(e&&t.type==="click"&&t.detail===0){const c=e.getBoundingClientRect();o=c.left+c.width/2,s=c.bottom}const r=Math.min(Math.max(o,Y),window.innerWidth-n.width-Y),a=Math.min(Math.max(s,Y),window.innerHeight-n.height-Y);return{left:r,top:a}}renderPositionMenu(){if(!this.positionMenuElement||this.positionMenuTarget===null)return;const t=new Set(this.getAllowedPositionsForPositionMenuTarget(this.positionMenuTarget));this.positionMenuElement.querySelectorAll(qe).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,o=n.option,s=new Set(this.getAllowedPositionsForPositionMenuTarget(n));s.has(e)?s.delete(e):s.add(e);const r=F.map(g=>g.value).filter(g=>s.has(g));this.setAllowedPositionsForPositionMenuTarget(n,r),this.renderPositionMenu();const a=w(o),c=a?this.optionButtons.get(a):null,d=this.selectedPriorityOptions.indexOf(o);c&&d!==-1&&(p(o)?this.getRandomOptionButton(d):this.getChampionOptionButton(o,d)),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===Rt){t.preventDefault();return}if(t.button!==Ge)return;this.dragState&&this.clearDragState();const n=w(e),o=n?this.optionButtons.get(n):null;if(o){this.dragState={option:e,pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,active:!1,moved:!1};try{(s=o.setPointerCapture)==null||s.call(o,t.pointerId)}catch{}window.addEventListener("pointermove",this.handleWindowPointerMove),window.addEventListener("pointerup",this.handleWindowPointerUp),window.addEventListener("pointercancel",this.handleWindowPointerCancel)}}removePriorityOptionOnMiddleClick(t,e){t.button===Rt&&(t.preventDefault(),t.stopPropagation(),this.removePriorityOption(e))}moveDrag(t){var g;if(!this.dragState||this.dragState.pointerId!==t.pointerId)return;const e=this.dragState.option,n=w(e),o=t.clientX-this.dragState.startX,s=t.clientY-this.dragState.startY,r=Math.hypot(o,s);if(!this.dragState.active){if(r<He)return;this.dragState.active=!0,n&&((g=this.optionButtons.get(n))==null||g.classList.add("champion-priority-selector__icon--dragging"))}t.preventDefault();const a=this.getDropIndex(t.clientX,e),c=this.selectedPriorityOptions.indexOf(e);if(a===c||a===-1)return;const d=this.getIconPositions();this.movePriorityOptionToIndex(e,a)&&(this.dragState.moved=!0,this.renderSelectedPriorityOptions(d,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=w(t),o=n?this.optionButtons.get(n):null;o==null||o.classList.remove("champion-priority-selector__icon--dragging");try{(s=o==null?void 0:o.releasePointerCapture)==null||s.call(o,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(o=>o!==e);for(let o=0;o<n.length;o++){const s=w(n[o]),r=s?this.optionButtons.get(s):null;if(!r)continue;const a=r.getBoundingClientRect();if(t<a.left+a.width/2)return o}return n.length}getIconPositions(){const t=new Map;for(const e of this.selectedPriorityOptions){const n=w(e),o=n?this.optionButtons.get(n):null;o&&t.set(n,o.getBoundingClientRect())}return t}animateReorder(t,e){for(const n of this.selectedPriorityOptions){if(n===e)continue;const o=w(n),s=o?this.optionButtons.get(o):null,r=o?t.get(o):null;if(!s||!r||typeof s.animate!="function")continue;const a=s.getBoundingClientRect(),c=r.left-a.left,d=r.top-a.top;c===0&&d===0||s.animate([{transform:`translate(${c}px, ${d}px)`},{transform:"translate(0, 0)"}],{duration:je,easing:Qe})}}}const We=200,et="auto-select-champ-select-menu--collapsed",Ve="auto-select-champ-select-menu-button-wrapper--open";class nt{constructor(t,e){this.element=document.createElement(O.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=Yt(this.configKey),this.element.toggleAttribute("selected",this.config.enabled===!0)}toggle(){return console.debug("auto-champion-select: Toggling",this.configKey),this.config=H(this.configKey,t=>(t.enabled=!t.enabled,t)),this.element.toggleAttribute("selected",this.config.enabled===!0),this.config.enabled}}class Ke{constructor(t,e,n){this.element=document.createElement("div"),this.element.classList.add("auto-select-champ-select-menu",et),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.buttonWrapper.append(this.headerElement,this.element),this.contentElement.appendChild(this.titleElement),this.element.appendChild(this.contentElement),this.returnControlsToSocialRoster=e,this.controlElements=n,this.boundCloseOnOutsideInteraction=o=>this.closeOnOutsideInteraction(o),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(et)}setOpen(t){this.element.classList.toggle(et,!t),this.buttonWrapper.classList.toggle(Ve,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=it();for(;this.mounted&&!t;)await T(We),t=it();if(!this.mounted||!t)return;const e=t.querySelector(l.firstChampSelectSquareButton);this.buttonWrapper.parentNode===t&&this.buttonWrapper.nextSibling===e||t.insertBefore(this.buttonWrapper,e)}}class Xe{constructor(t,...e){this.element=document.createElement(O.socialRosterGroup),this.element.addEventListener("post-render",()=>this.onPostRender()),this.element.addEventListener("click",()=>this.onClick()),this.label=t,this.collapsibleElements=e,this.waitRender()}waitRender(){new MutationObserver((t,e)=>{if(this.element.querySelector(l.socialRosterGroupLabel)){const n=new Event("post-render");this.element.dispatchEvent(n),e.disconnect()}}).observe(this.element,{childList:!0})}onPostRender(){var t;this.element.querySelector(l.socialRosterGroupLabel).innerText=this.label,(t=this.element.querySelector(l.socialRosterGroupHeader))==null||t.removeAttribute("draggable")}onClick(){var t;this.collapsibleElements.forEach(e=>{e.closest(".auto-select-champ-select-menu")||e.classList.toggle("hidden")}),(t=this.element.querySelector(l.socialRosterGroupArrow))==null||t.toggleAttribute("open")}}function Xt(i){var t,e;i&&((e=(t=globalThis.Toast)==null?void 0:t.success)==null||e.call(t,i))}function at(i){var t,e;i&&((e=(t=globalThis.Toast)==null?void 0:t.error)==null||e.call(t,i))}function Je(i,t){const e=globalThis.Toast;return typeof(e==null?void 0:e.promise)=="function"?e.promise(i,t):i}const D="Balaclava: Auto Champion Select";function Ze(i){return typeof(i==null?void 0:i.then)=="function"}class ut{constructor({id:t,name:e,legend:n,tags:o,group:s,callback:r,toasts:a}){this.id=t,this.name=e,this.legend=n,this.tags=o,this.group=s,this.perform=this.perform.bind(this),this.callback=r,this.toasts=a}perform(){try{const t=this.callback();if(Ze(t))return Je(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);Xt(e)}catch(t){at(this.toasts.error),console.error(t)}}}class Jt extends ut{constructor(t,e,n){super({id:`${e}Switch`,name:()=>`Auto ${t} [${k(e).enabled?"ON":"OFF"}]`,legend:()=>k(e).enabled?"Turn OFF":"Turn ON",tags:[D,e,"switch"],group:D,callback:n,toasts:{on:`Auto ${t} is ON!`,off:`Auto ${t} is OFF!`,error:`Failed to toggle Auto ${t}. Check console.`}})}}function tn(i){return H(i,e=>(e.force=!e.force,e)).force}class Zt extends ut{constructor(t,e){super({id:`${e}ForceSwitch`,name:()=>`Force ${t} [${k(e).force?"ON":"OFF"}]`,legend:()=>`Ignore team intent and force ${t} the selected champion`,tags:[D,e,"force","switch"],group:D,callback:()=>tn(e),toasts:{on:`Force ${t} is ON!`,off:`Force ${t} is OFF!`,error:`Failed to toggle Force ${t}. Check console.`}})}}class en extends ut{constructor(t){super({id:"RefreshDropdowns",name:()=>"Refresh Champions",legend:()=>"Normally champion selectors refresh automatically...",tags:[D,"refresh"],group:D,callback:t,toasts:{success:"Refreshed Champions!",error:"Failed to refresh Champions. Check console."}})}}class nn extends Jt{constructor(t){super("Pick","controladoPick",t)}}class on extends Jt{constructor(t){super("Ban","controladoBan",t)}}class sn extends Zt{constructor(){super("Pick","controladoPick")}}class rn extends Zt{constructor(){super("Ban","controladoBan")}}function an(i){for(const t of i)CommandBar.addAction(t)}const cn=200,ln=6e4,Lt=2e3,dn=".ready-check-root-element",hn="#lol-uikit-layer-manager-wrapper > .modal",un="Accepted ready check!",Mt="Failed to accept ready check. Check console.",pn=".auto-select-champ-select-menu__header",N=Object.freeze({autoAccept:"controladoAutoAccept",pick:"controladoPick",ban:"controladoBan"});function te(){return k(N.autoAccept).enabled===!0}class mn{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=fn();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);Bt(t,"display",e==null?void 0:e.display,e==null?void 0:e.displayPriority),Bt(t,"pointer-events",e==null?void 0:e.pointerEvents,e==null?void 0:e.pointerEventsPriority),this.hiddenModalStyles.delete(t),this.hiddenModal=null}}function fn(){const i=document.querySelector(dn);return(i==null?void 0:i.closest(hn))||null}function Bt(i,t,e,n){e?i.style.setProperty(t,e,n||""):i.style.removeProperty(t)}async function gn(i){function t(){return te()?!1:(i.restore(),!0)}if(t()||(console.debug(`auto-champion-select(auto-accept): Ready check detected, accepting in ${Lt}ms...`),await T(Lt),t()))return;let e=!1;try{e=await Pn()}catch(n){throw i.restore(),at(Mt),n}e?Xt(un):(i.restore(),at(Mt))}async function Pn(){const i=await S("POST",m.readyCheckAccept);return i.ok?(console.debug("auto-champion-select(auto-accept): Accepted ready check"),!0):(console.error("auto-champion-select(auto-accept): Failed to accept ready check",i),!1)}async function yn(i){const t=await S("GET",m.gameflowPhase),e=t.ok?await t.json():null;i.handleGameflowPhase(e)}function bn({championSelect:i,champSelectControlsMenu:t,readyCheckModalSuppressor:e,setupChampionSelectors:n}){let o=0;return async function(c){const d=++o;try{await s(c,d)}catch(g){console.error("auto-champion-select: Failed to handle gameflow phase",g)}};async function s(a,c){a==="ReadyCheck"?gn(e).catch(d=>{console.error("auto-champion-select(auto-accept): Failed to handle ready check",d)}):e.restore(),await r(a),c===o&&await n()}async function r(a){a==="ChampSelect"?(i.mount(),await t.mount()):(i.unmount(),await t.unmount())}}function An(){const i=new ve,t=new nt("Accept",N.autoAccept),e=new nt("Pick",N.pick),n=new vt("Add pick",N.pick,Oe,{enablePositionRestrictions:!0,enableRandomAssignedPositionRestrictions:!0,enableBraveryOption:!0,quickActionLabel:"Pick instantly",enableRandomPoolPositionFilters:!0,randomOptionDescription:"Picks a random available champion. Badges limit draft lanes or filter the pool."}),o=new nt("Ban",N.ban),s=new vt("Add ban",N.ban,Gt,{quickActionLabel:"Ban instantly",enableRandomPoolPositionFilters:!0,randomOptionDescription:"Bans a random available champion. Lane badges filter the pool first."}),r=Cn(n,s),a=Sn(t,e,o),c=new Xe("Auto champion select",r,a);return{championSelect:i,autoAcceptToggle:t,pickToggle:e,banToggle:o,pickChampionSelector:n,banChampionSelector:s,selectorsContainer:r,checkboxesContainer:a,pluginSection:c,championSelectors:[n,s]}}function Cn(...i){const t=document.createElement("div");return t.append(...i.map(e=>e.element)),t}function Sn(...i){const t=document.createElement("div");return t.classList.add("auto-select-checkboxes-div"),t.append(...i.map(e=>e.element)),t}function On({pluginSection:i,checkboxesContainer:t,selectorsContainer:e}){let n=null,o=0,s=()=>!1;async function r(a){let c=Ct();for(;!c;){if(s()||a!==o)return;await T(cn),c=Ct()}s()||a!==o||c.append(i.element,t,e)}return{setIsChampSelectControlsMounted(a){s=a},returnControlsToSocialRoster(){if(n)return n;const a=++o;return n=r(a).catch(c=>console.error("auto-champion-select: Failed to return controls to social roster",c)).finally(()=>{n=null}),n}}}function wn({autoAcceptToggle:i,pickToggle:t,banToggle:e,readyCheckModalSuppressor:n}){i.setup(),i.element.addEventListener("click",()=>n.sync()),t.setup(),e.setup()}async function En(i){await Promise.all(i.map(t=>t.setup()))}async function In(i){await Promise.all(i.map(t=>t.refresh()))}function Tn(){const i=An(),t=new mn(te),e=On(i),n=new Ke("Auto Champion Select",e.returnControlsToSocialRoster,[i.checkboxesContainer,i.selectorsContainer]);e.setIsChampSelectControlsMounted(()=>n.mounted);const o={...i,champSelectControlsMenu:n,readyCheckModalSuppressor:t,setupToggles:()=>wn({...i,readyCheckModalSuppressor:t}),setupChampionSelectors:()=>En(i.championSelectors),refreshChampionSelectors:()=>In(i.championSelectors),refreshPickChampionSelector:async()=>{await i.pickChampionSelector.refresh()}};return o.handleGameflowPhase=bn(o),o}function _n(i){pt(m.gameflowPhase,t=>{i.handleGameflowPhase(t.data)}),pt(m.wallet,async t=>{if(t.eventType==="Update"){console.debug("auto-champion-select(wallet): Refreshing champion selectors...");try{await i.refreshPickChampionSelector()}catch(e){console.error("auto-champion-select(wallet): Failed to refresh champion selectors",e)}}})}function kn({pickToggle:i,banToggle:t,refreshChampionSelectors:e}){an([new nn(()=>i.toggle()),new on(()=>t.toggle()),new sn,new rn,new en(e)])}function Rn(i){let t=null,e=null;function n(){e==null||e.disconnect(),e=null,t!==null&&(cancelAnimationFrame(t),t=null)}const o=setTimeout(()=>{n()},ln);function s(){if(!(it()!==null))return;clearTimeout(o),n(),document.querySelector(pn)!==null||i.handleGameflowPhase("ChampSelect")}e=new MutationObserver(()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,s()}))}),e.observe(document.body,{childList:!0,subtree:!0}),s()}async function vn(){const i=Tn();i.setupToggles(),i.readyCheckModalSuppressor.start(),kn(i),_n(i),await yn(i),Rn(i),console.debug(`auto-champion-select(${ee}): Report bugs to Balaclava#1912`)}let Nt=!1;function Ft(){Nt||(Nt=!0,vn().catch(i=>console.error("auto-champion-select: Failed to initialize",i)))}document.readyState==="loading"?window.addEventListener("load",Ft,{once:!0}):Ft();export{Ft as load};
231
+ `;function J(i){const t=document.createElement(O.dropdownOption);return t.setAttribute("slot",O.dropdownOption),t.innerText=i,t}class xe{constructor(t,e,n,o={}){this.dropdownElement=t,this.placeholderText=e,this.searchPlaceholderText=o.searchPlaceholderText||"Search",this.quickActionLabel=o.quickActionLabel||"Pick/ban instantly",this.staticOptions=Array.isArray(o.staticOptions)?o.staticOptions:[],this.isQuickActionEnabled=typeof o.isQuickActionEnabled=="function"?o.isQuickActionEnabled:null,this.onQuickActionToggle=typeof o.onQuickActionToggle=="function"?o.onQuickActionToggle:null,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=J(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),o=this.createChampionOption(e,n);n.length>0&&(this.hasRecommendedPositionData=!0),this.dropdownElement.appendChild(o)}this.hasRecommendedPositionData||(this.activePositionFilter=null),this.applyOptionFilters()}createChampionOption(t,e){const n=J("");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=J(""),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(wt);const n=document.createElement("img");n.classList.add(Et),n.src=t.squarePortraitPath,n.alt="",n.draggable=!1,n.loading="lazy";const o=document.createElement("span");return o.classList.add(It),o.innerText=t.name,e.append(n,o),e}createStaticOptionContent(t,e=""){const n=document.createElement("span");n.classList.add(wt);const o=t.iconPath?document.createElement("img"):document.createElement("span");o.classList.add(Et),t.iconClass&&o.classList.add(t.iconClass),t.iconPath?(o.src=t.iconPath,o.alt="",o.draggable=!1,o.loading="lazy"):(o.classList.add(De),o.innerText=t.iconText||"?");const s=document.createElement("span");s.classList.add(It),s.innerText=t.label;const r=document.createElement("span");if(r.classList.add(Ne),r.appendChild(s),e){const a=document.createElement("span");a.classList.add(Fe),a.innerText=e,r.appendChild(a)}return n.append(o,r),n}getChampionRecommendedPositions(t){return Array.isArray(t.recommendedPositions)?t.recommendedPositions:[]}async waitForRender(){for(let t=0;t<Le;t++){const e=this.dropdownElement.shadowRoot;if(this.dropdownElement.isConnected&&(e!=null&&e.querySelector(l.dropdownCurrent)))return e;await T(Me)}return null}ensureSearchPlaceholder(t){if(t.querySelector(`#${St}`))return;const e=t.querySelector(l.dropdownCurrent);e&&e.appendChild(this.createSearchPlaceholder())}ensureQuickActionToggle(t){if(!this.isQuickActionAvailable()||t.querySelector(`#${X}`)){this.syncQuickActionToggle(t);return}const e=t.querySelector(l.dropdownCurrent);e&&(e.appendChild(this.createQuickActionToggle()),this.syncQuickActionToggle(t))}ensurePositionFilter(t){var n;const e=t.querySelector(l.dropdownOptionsContainer);if(e){if(!this.hasRecommendedPositionData){(n=t.querySelector(`.${U}`))==null||n.remove(),e.classList.remove(st),this.activePositionFilter=null;return}e.classList.add(st),t.querySelector(`.${U}`)||e.insertBefore(this.createPositionFilter(),e.firstChild),this.syncPositionFilter(t)}}createPositionFilter(){const t=document.createElement("div");t.classList.add(U),t.setAttribute("role","toolbar"),t.setAttribute("aria-label","Filter champions by position");for(const e of F)t.appendChild(this.createPositionFilterBadge(e));return t}createPositionFilterBadge(t){const e=document.createElement("button");e.classList.add(I),e.type="button",e.dataset.position=t.value,e.title=t.label,e.setAttribute("aria-label",t.label),e.setAttribute("aria-pressed","false");const n=document.createElement("img");return n.src=t.iconPath,n.alt="",n.draggable=!1,e.appendChild(n),e.addEventListener("pointerdown",o=>{o.preventDefault(),o.stopPropagation()}),e.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),this.togglePositionFilter(t.value)}),e}createSearchPlaceholder(){const t=document.createElement("div");t.classList.add(Vt,Qt),t.id=St;const e=document.createElement("input");e.classList.add(jt),e.id=Ot,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(Kt),n.addEventListener("click",()=>{n.classList.contains(B)&&this.clearSearch(e,n)}),e.addEventListener("input",o=>{this.ensureOpen(),this.setSearchQuery(o.target.value),n.classList.toggle(B,!!o.target.value)}),["pointerdown","click"].forEach(o=>{t.addEventListener(o,s=>s.stopPropagation()),n.addEventListener(o,s=>s.stopPropagation())}),["pointerdown","focusin"].forEach(o=>{e.addEventListener(o,s=>s.stopPropagation(),!0)}),t.appendChild(n),t.appendChild(e),t}createQuickActionToggle(){const t=document.createElement("button");return t.classList.add(q),t.id=X,t.type="button",t.title=this.quickActionLabel,t.setAttribute("aria-label",this.quickActionLabel),t.setAttribute("aria-pressed","false"),["pointerdown","click"].forEach(e=>{t.addEventListener(e,n=>{n.preventDefault(),n.stopPropagation()})}),t.addEventListener("click",()=>{var e;(e=this.onQuickActionToggle)==null||e.call(this),this.syncQuickActionToggle()}),t}isQuickActionAvailable(){return!!(this.isQuickActionEnabled&&this.onQuickActionToggle)}syncQuickActionToggle(t=this.dropdownElement.shadowRoot){if(!this.isQuickActionAvailable()||!t)return;const e=t.querySelector(`#${X}`);if(!e)return;const n=this.isQuickActionEnabled()===!0;e.classList.toggle(Wt,n),e.setAttribute("aria-pressed",String(n)),e.title=this.quickActionLabel,e.setAttribute("aria-label",this.quickActionLabel)}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(`.${I}`).forEach(e=>{const n=e.dataset.position===this.activePositionFilter;e.classList.toggle(rt,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(l.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(l.dropdownOptionSelected).forEach(e=>{e.removeAttribute("selected")}),(t=this.placeholderOption)==null||t.setAttribute("selected","true"),this.withShadowRoot(e=>{var s;const n=e.querySelector(`#${Ot}`),o=e.querySelector(`.${B}`);n&&o?this.clearSearch(n,o):(n&&(n.value="",this.setSearchQuery("")),o&&o.classList.remove(B)),this.isOpen()&&((s=e.querySelector(l.dropdownCurrent))==null||s.click())})}isOpen(){return this.dropdownElement.classList.contains("active")}ensureOpen(){this.isOpen()||this.withShadowRoot(t=>{const e=t.querySelector(l.dropdownCurrent);e&&e.click()})}patchDropdownShadowDom(){this.withShadowRoot(t=>{this.ensureDropdownOpensUpward(t),this.injectDropdownSearchStyles(t),this.ensurePositionFilter(t)})}ensureDropdownOpensUpward(t){var e;(e=t.querySelector(l.dropdownRoot))==null||e.classList.add("opens-upward")}injectDropdownSearchStyles(t){const e=t.querySelector("style[data-controlado='dropdown-tags']");if(e){e.textContent=Tt;return}const n=document.createElement("style");n.dataset.controlado="dropdown-tags",n.textContent=Tt,t.appendChild(n)}withShadowRoot(t){const e=this.dropdownElement.shadowRoot;e&&t(e)}}const $e=".champion-priority-selector__position-badge",qe=".champion-priority-selector__position-option",Z=".champion-priority-selector__remove",tt="✕",_t="?",$="Random",L="Bravery",ze="For Arena mode",kt="/fe/lol-champ-select/images/champion-grid/bravery-champion.png",Ye="controlado-champion-option__icon--bravery",Ue="champion-priority-selector__icon--bravery",Ge=0,Rt=1,Y=8,h=Object.freeze({CHAMPION_ASSIGNED:"champion-assigned",RANDOM_ASSIGNED:"random-assigned",RANDOM_POOL:"random-pool"}),He=5,je=150,Qe="cubic-bezier(0.2, 0, 0, 1)";class vt{constructor(t,e,n,o={}){this.element=this.createRootElement(),this.dropdownElement=this.createDropdownElement();const s=[];o.enableBraveryOption===!0&&s.push({value:E,label:L,description:ze,iconPath:kt,iconClass:Ye}),s.push({value:b,label:$,iconText:_t}),this.championDropdown=new xe(this.dropdownElement,t,c=>this.addPriorityOption(c),{quickActionLabel:o.quickActionLabel,searchPlaceholderText:o.searchPlaceholderText,staticOptions:s,isQuickActionEnabled:()=>this.isQuickActionEnabled(),onQuickActionToggle:()=>this.toggleQuickAction()});const{scrollElement:r,trackElement:a}=this.createSelectedChampionsScroll();this.scrollElement=r,this.trackElement=a,this.enablePositionRestrictions=o.enablePositionRestrictions===!0,this.enableRandomPoolPositionFilters=o.enableRandomPoolPositionFilters===!0,this.enableRandomAssignedPositionRestrictions=o.enableRandomAssignedPositionRestrictions===!0,this.enableBraveryOption=o.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(t),this.element.append(this.dropdownElement,this.scrollElement),this.positionMenuElement&&this.element.appendChild(this.positionMenuElement),this.config=null,this.configKey=e,this.quickAction=!1,this.loadChampions=n,this.champions=[],this.championById=new Map,this.selectedPriorityOptions=[],this.optionButtons=new Map,this.dragState=null,this.handleWindowPointerMove=c=>this.moveDrag(c),this.handleWindowPointerUp=c=>this.finishDrag(c),this.handleWindowPointerCancel=c=>this.cancelDrag(c),this.handlePositionMenuOutsidePointerDown=c=>this.closePositionMenuOnOutsidePointerDown(c),this.handlePositionMenuKeyDown=c=>this.closePositionMenuOnKeyDown(c),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(O.dropdown);return t.classList.add("dropdown-champions-default","dropdown-drop-up"),t}createSelectedChampionsScroll(){const t=document.createElement(O.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="No champions";const o=document.createElement("span"),s=t.replace(/^Add\s+/i,"").toLowerCase();return o.innerText=`Use dropdown to add ${s} option`,e.append(n,o),e}createPositionMenu(){const t=document.createElement("div");t.classList.add("champion-priority-selector__position-menu"),t.hidden=!0;for(const e of F)t.appendChild(this.createPositionOption(e));return t}createPositionOption(t){const e=document.createElement("button");e.classList.add("champion-priority-selector__position-option"),e.type="button",e.dataset.position=t.value,e.title=t.label,e.setAttribute("aria-label",t.label),e.setAttribute("aria-pressed","false"),e.addEventListener("pointerdown",o=>o.stopPropagation()),e.addEventListener("click",o=>{o.stopPropagation(),this.togglePositionMenuPosition(t.value)});const n=document.createElement("img");return n.src=t.iconPath,n.alt=t.label,n.draggable=!1,e.appendChild(n),e}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=Yt(this.configKey,{allowedChampionIds:t}),this.quickAction=this.config.quickAction===!0,this.selectedPriorityOptions=ct(this.config.priorityOptions||this.config.champions,t).filter(n=>this.isPriorityOptionEnabled(n)),this.enablePositionRestrictions&&(this.positionsByChampionId=G(this.config.positionsByChampionId,M(this.selectedPriorityOptions))),this.enableRandomAssignedPositionRestrictions&&(this.randomAssignedPositions=A(this.config.randomAssignedPositions)),this.enableRandomPoolPositionFilters&&(this.randomPoolPositions=A(this.config.randomPoolPositions)),this.championDropdown.renderOptions(this.champions),this.renderSelectedPriorityOptions();const e=await this.championDropdown.waitForRender();e&&(this.championDropdown.ensureSearchPlaceholder(e),this.championDropdown.ensureQuickActionToggle(e),this.championDropdown.patchDropdownShadowDom())}getAllowedChampionIds(){return new Set(this.championById.keys())}isQuickActionEnabled(){return this.quickAction===!0}isPriorityOptionEnabled(t){return!C(t)||this.enableBraveryOption}toggleQuickAction(){const t=this.getAllowedChampionIds();return this.config=H(this.configKey,e=>(e.quickAction=e.quickAction!==!0,e),{allowedChampionIds:t,selectedChampionIds:M(this.selectedPriorityOptions)}),this.quickAction=this.config.quickAction===!0,this.championDropdown.syncQuickActionToggle(),this.quickAction}addPriorityOption(t){const e=_(t);e===null||this.selectedPriorityOptions.includes(e)||!this.isPriorityOptionEnabled(e)||!p(e)&&!C(e)&&!this.championById.has(e)||(this.selectedPriorityOptions.push(e),this.renderSelectedPriorityOptions(),this.saveConfig())}removePriorityOption(t){var s;const e=_(t),n=this.selectedPriorityOptions.indexOf(e);if(e===null||n===-1)return;this.selectedPriorityOptions.splice(n,1);const o=typeof e=="number"?e:null;((s=this.positionMenuTarget)==null?void 0:s.option)===e&&this.closePositionMenu(),this.enablePositionRestrictions&&o!==null&&delete this.positionsByChampionId[String(o)],this.enableRandomAssignedPositionRestrictions&&p(e)&&(this.randomAssignedPositions=[]),this.enableRandomPoolPositionFilters&&p(e)&&(this.randomPoolPositions=[]),this.renderSelectedPriorityOptions(),this.saveConfig()}movePriorityOptionToIndex(t,e){const n=_(t),o=this.selectedPriorityOptions.indexOf(n);if(n===null||o===-1)return!1;const[s]=this.selectedPriorityOptions.splice(o,1),r=Math.max(0,Math.min(e,this.selectedPriorityOptions.length));return this.selectedPriorityOptions.splice(r,0,s),o!==r}syncPositionsByChampionId(){this.enablePositionRestrictions&&(this.positionsByChampionId=G(this.positionsByChampionId,M(this.selectedPriorityOptions)))}syncRandomPoolPositions(){this.enableRandomPoolPositionFilters&&(this.randomPoolPositions=A(this.randomPoolPositions))}syncRandomAssignedPositions(){this.enableRandomAssignedPositionRestrictions&&(this.randomAssignedPositions=A(this.randomAssignedPositions))}saveConfig(){this.syncPositionsByChampionId(),this.syncRandomAssignedPositions(),this.syncRandomPoolPositions();const t=this.getAllowedChampionIds();this.config=H(this.configKey,e=>(e.priorityOptions=[...this.selectedPriorityOptions],e.champions=M(this.selectedPriorityOptions),this.enableRandomAssignedPositionRestrictions&&(e.randomAssignedPositions=[...this.randomAssignedPositions]),this.enableRandomPoolPositionFilters&&(e.randomPoolPositions=[...this.randomPoolPositions]),this.enablePositionRestrictions&&(e.positionsByChampionId={...this.positionsByChampionId}),e),{allowedChampionIds:t,selectedChampionIds:M(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=>w(s)));for(const[s,r]of this.optionButtons)n.has(s)||(r.remove(),this.optionButtons.delete(s));if(this.selectedPriorityOptions.length===0){this.trackElement.replaceChildren(this.emptyElement);return}this.emptyElement.remove();const o=this.selectedPriorityOptions.map((s,r)=>this.getPriorityOptionButton(s,r)).filter(Boolean);this.trackElement.append(...o),t&&this.animateReorder(t,e)}getPriorityOptionButton(t,e){return p(t)?this.getRandomOptionButton(e):C(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 o=String(t);let s=this.optionButtons.get(o);s||(s=this.createIconButton(n),this.optionButtons.set(o,s)),s.dataset.rank=String(e+1),s.classList.toggle("champion-priority-selector__icon--random",!1);const r=this.getChampionPositionTitleSuffix(t);s.title=`${e+1}. ${n.name}${r}`,s.setAttribute("aria-label",`${e+1}. ${n.name}${r}`);const a=s.querySelector("img");a.src=n.squarePortraitPath,a.alt=n.name;const c=s.querySelector(Z);return c.setAttribute("aria-label",`Remove ${n.name}`),c.title=`Remove ${n.name}`,this.renderPositionBadge(s,t),s}getRandomOptionButton(t){let e=this.optionButtons.get(b);e||(e=this.createRandomOptionButton(),this.optionButtons.set(b,e)),e.dataset.rank=String(t+1);const n=this.getRandomPositionTitleSuffix();e.title=`${t+1}. ${$}${n}`,e.setAttribute("aria-label",`${t+1}. ${$}${n}`);const o=e.querySelector(Z);return o.setAttribute("aria-label",`Remove ${$}`),o.title=`Remove ${$}`,this.renderPositionBadge(e,b),e}getBraveryOptionButton(t){let e=this.optionButtons.get(E);e||(e=this.createBraveryOptionButton(),this.optionButtons.set(E,e)),e.dataset.rank=String(t+1),e.title=`${t+1}. ${L}`,e.setAttribute("aria-label",`${t+1}. ${L}`);const n=e.querySelector("img");n.src=kt,n.alt=L;const o=e.querySelector(Z);return o.setAttribute("aria-label",`Remove ${L}`),o.title=`Remove ${L}`,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 o=document.createElement("button");if(o.classList.add("champion-priority-selector__remove"),o.type="button",o.dataset.icon=tt,o.addEventListener("pointerdown",s=>s.stopPropagation()),o.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:h.CHAMPION_ASSIGNED};e.addEventListener("contextmenu",r=>this.openPositionMenu(r,s))}return e.append(n,o),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=tt,n.addEventListener("pointerdown",o=>o.stopPropagation()),n.addEventListener("click",o=>{o.stopPropagation(),this.removePriorityOption(b)}),t.addEventListener("pointerdown",o=>this.startDrag(o,b)),t.addEventListener("auxclick",o=>this.removePriorityOptionOnMiddleClick(o,b)),this.enableRandomPoolPositionFilters){const o={option:b,kind:h.RANDOM_POOL};t.addEventListener("contextmenu",s=>this.openPositionMenu(s,o))}return t.append(e,n),t}createBraveryOptionButton(){const t=document.createElement("div");t.classList.add("champion-priority-selector__icon",Ue),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=tt,n.addEventListener("pointerdown",o=>o.stopPropagation()),n.addEventListener("click",o=>{o.stopPropagation(),this.removePriorityOption(E)}),t.addEventListener("pointerdown",o=>this.startDrag(o,E)),t.addEventListener("auxclick",o=>this.removePriorityOptionOnMiddleClick(o,E)),t.append(e,n),t}getChampionAllowedPositions(t){const e=u(t);return e===null?[]:this.positionsByChampionId[String(e)]||[]}getRandomPoolPositions(){return this.randomPoolPositions}getRandomAssignedPositions(){return this.randomAssignedPositions}getPositionLabels(t){return t.map(e=>{var n;return(n=mt(e))==null?void 0:n.label}).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(`runs only when assigned lane matches ${this.formatPositionLabelsForSentence(e)}`),n.length>0&&t.push(`filters random pool to ${this.formatPositionLabelsForSentence(n)}`),t.length>0?` (${t.join("; ")})`:""}formatPositionLabelsForSentence(t){return t.length<=1?t[0]||"":t.length===2?`${t[0]} or ${t[1]}`:`${t.slice(0,-1).join(", ")}, or ${t[t.length-1]}`}renderPositionBadge(t,e){t.querySelectorAll($e).forEach(o=>o.remove());const n=_(e);if(n!==null)for(const o of this.getPositionBadgeTargetsForOption(n)){const s=this.createPositionBadge(o);s&&t.appendChild(s)}}getPositionBadgeTargetsForOption(t){return this.selectedPriorityOptions.includes(t)?p(t)?[{option:t,kind:h.RANDOM_ASSIGNED},{option:t,kind:h.RANDOM_POOL}].filter(e=>this.canOpenPositionMenuForTarget(e)):C(t)?[]:[{option:t,kind:h.CHAMPION_ASSIGNED}].filter(e=>this.canOpenPositionMenuForTarget(e)):[]}createPositionBadge(t){const e=this.getAllowedPositionsForPositionMenuTarget(t),n=this.getAllowedPositionLabelsForPositionMenuTarget(t),o=t.kind===h.RANDOM_POOL,s=document.createElement("button");if(s.classList.add("champion-priority-selector__position-badge"),s.classList.toggle("champion-priority-selector__position-badge--random",o),s.type="button",s.dataset.positionTarget=t.kind,s.title=this.getPositionBadgeTitle(n,t),s.setAttribute("aria-label",s.title),s.addEventListener("pointerdown",c=>c.stopPropagation()),s.addEventListener("click",c=>this.openPositionMenu(c,t,s)),o)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 r=mt(e[0]);if(!r)return null;e.length>1&&(s.dataset.count=String(e.length));const a=document.createElement("img");return a.src=r.iconPath,a.alt=r.label,a.draggable=!1,s.appendChild(a),s}getPositionBadgeTitle(t,e){return e.kind===h.RANDOM_ASSIGNED?t.length===0?"The plugin can use Random in any lane. Click to run it only in selected draft lanes.":`The plugin will use Random only when your assigned lane matches ${this.formatPositionLabelsForSentence(t)}. Draft modes only. Click to edit.`:e.kind===h.RANDOM_POOL?t.length===0?"The plugin can choose any available champion at random. Click to filter the pool first.":`The plugin filters Random to champions for ${this.formatPositionLabelsForSentence(t)}, then picks one. Click to edit.`:t.length>0?`The plugin will pick this champion only when your assigned lane matches ${this.formatPositionLabelsForSentence(t)}. Draft modes only. Click to edit.`:"The plugin can pick this champion in any lane. Click to limit it to selected draft lanes."}canOpenPositionMenuForTarget(t){if(!this.selectedPriorityOptions.includes(t.option))return!1;switch(t.kind){case h.CHAMPION_ASSIGNED:return typeof t.option=="number"&&this.enablePositionRestrictions;case h.RANDOM_ASSIGNED:return p(t.option)&&this.enableRandomAssignedPositionRestrictions;case h.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=_(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 h.CHAMPION_ASSIGNED:return this.getChampionAllowedPositions(t.option);case h.RANDOM_ASSIGNED:return this.getRandomAssignedPositions();case h.RANDOM_POOL:return this.getRandomPoolPositions();default:return[]}}getAllowedPositionLabelsForPositionMenuTarget(t){return this.getPositionLabels(this.getAllowedPositionsForPositionMenuTarget(t))}setAllowedPositionsForPositionMenuTarget(t,e){switch(t.kind){case h.CHAMPION_ASSIGNED:{const n=String(t.option);e.length>0?this.positionsByChampionId[n]=e:delete this.positionsByChampionId[n];break}case h.RANDOM_ASSIGNED:this.randomAssignedPositions=e;break;case h.RANDOM_POOL:this.randomPoolPositions=e;break}}openPositionMenu(t,e,n=null){if(!this.positionMenuElement)return;const o=this.normalizePositionMenuTarget(e);if(o===null)return;t.preventDefault(),t.stopPropagation(),this.positionMenuTarget=o,this.renderPositionMenu(),this.positionMenuElement.hidden=!1,this.positionMenuElement.style.left="0px",this.positionMenuElement.style.top="0px";const{left:s,top:r}=this.getPositionMenuCoordinates(t,n);this.positionMenuElement.style.left=`${s}px`,this.positionMenuElement.style.top=`${r}px`,document.addEventListener("pointerdown",this.handlePositionMenuOutsidePointerDown,!0),document.addEventListener("keydown",this.handlePositionMenuKeyDown,!0)}getPositionMenuCoordinates(t,e=null){const n=this.positionMenuElement.getBoundingClientRect();let o=t.clientX,s=t.clientY;if(e&&t.type==="click"&&t.detail===0){const c=e.getBoundingClientRect();o=c.left+c.width/2,s=c.bottom}const r=Math.min(Math.max(o,Y),window.innerWidth-n.width-Y),a=Math.min(Math.max(s,Y),window.innerHeight-n.height-Y);return{left:r,top:a}}renderPositionMenu(){if(!this.positionMenuElement||this.positionMenuTarget===null)return;const t=new Set(this.getAllowedPositionsForPositionMenuTarget(this.positionMenuTarget));this.positionMenuElement.querySelectorAll(qe).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,o=n.option,s=new Set(this.getAllowedPositionsForPositionMenuTarget(n));s.has(e)?s.delete(e):s.add(e);const r=F.map(g=>g.value).filter(g=>s.has(g));this.setAllowedPositionsForPositionMenuTarget(n,r),this.renderPositionMenu();const a=w(o),c=a?this.optionButtons.get(a):null,d=this.selectedPriorityOptions.indexOf(o);c&&d!==-1&&(p(o)?this.getRandomOptionButton(d):this.getChampionOptionButton(o,d)),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===Rt){t.preventDefault();return}if(t.button!==Ge)return;this.dragState&&this.clearDragState();const n=w(e),o=n?this.optionButtons.get(n):null;if(o){this.dragState={option:e,pointerId:t.pointerId,startX:t.clientX,startY:t.clientY,active:!1,moved:!1};try{(s=o.setPointerCapture)==null||s.call(o,t.pointerId)}catch{}window.addEventListener("pointermove",this.handleWindowPointerMove),window.addEventListener("pointerup",this.handleWindowPointerUp),window.addEventListener("pointercancel",this.handleWindowPointerCancel)}}removePriorityOptionOnMiddleClick(t,e){t.button===Rt&&(t.preventDefault(),t.stopPropagation(),this.removePriorityOption(e))}moveDrag(t){var g;if(!this.dragState||this.dragState.pointerId!==t.pointerId)return;const e=this.dragState.option,n=w(e),o=t.clientX-this.dragState.startX,s=t.clientY-this.dragState.startY,r=Math.hypot(o,s);if(!this.dragState.active){if(r<He)return;this.dragState.active=!0,n&&((g=this.optionButtons.get(n))==null||g.classList.add("champion-priority-selector__icon--dragging"))}t.preventDefault();const a=this.getDropIndex(t.clientX,e),c=this.selectedPriorityOptions.indexOf(e);if(a===c||a===-1)return;const d=this.getIconPositions();this.movePriorityOptionToIndex(e,a)&&(this.dragState.moved=!0,this.renderSelectedPriorityOptions(d,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=w(t),o=n?this.optionButtons.get(n):null;o==null||o.classList.remove("champion-priority-selector__icon--dragging");try{(s=o==null?void 0:o.releasePointerCapture)==null||s.call(o,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(o=>o!==e);for(let o=0;o<n.length;o++){const s=w(n[o]),r=s?this.optionButtons.get(s):null;if(!r)continue;const a=r.getBoundingClientRect();if(t<a.left+a.width/2)return o}return n.length}getIconPositions(){const t=new Map;for(const e of this.selectedPriorityOptions){const n=w(e),o=n?this.optionButtons.get(n):null;o&&t.set(n,o.getBoundingClientRect())}return t}animateReorder(t,e){for(const n of this.selectedPriorityOptions){if(n===e)continue;const o=w(n),s=o?this.optionButtons.get(o):null,r=o?t.get(o):null;if(!s||!r||typeof s.animate!="function")continue;const a=s.getBoundingClientRect(),c=r.left-a.left,d=r.top-a.top;c===0&&d===0||s.animate([{transform:`translate(${c}px, ${d}px)`},{transform:"translate(0, 0)"}],{duration:je,easing:Qe})}}}const We=200,et="auto-select-champ-select-menu--collapsed",Ve="auto-select-champ-select-menu-button-wrapper--open";class nt{constructor(t,e){this.element=document.createElement(O.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=Yt(this.configKey),this.element.toggleAttribute("selected",this.config.enabled===!0)}toggle(){return console.debug("auto-champion-select: Toggling",this.configKey),this.config=H(this.configKey,t=>(t.enabled=!t.enabled,t)),this.element.toggleAttribute("selected",this.config.enabled===!0),this.config.enabled}}class Ke{constructor(t,e,n){this.element=document.createElement("div"),this.element.classList.add("auto-select-champ-select-menu",et),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.buttonWrapper.append(this.headerElement,this.element),this.contentElement.appendChild(this.titleElement),this.element.appendChild(this.contentElement),this.returnControlsToSocialRoster=e,this.controlElements=n,this.boundCloseOnOutsideInteraction=o=>this.closeOnOutsideInteraction(o),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(et)}setOpen(t){this.element.classList.toggle(et,!t),this.buttonWrapper.classList.toggle(Ve,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=it();for(;this.mounted&&!t;)await T(We),t=it();if(!this.mounted||!t)return;const e=t.querySelector(l.firstChampSelectSquareButton);this.buttonWrapper.parentNode===t&&this.buttonWrapper.nextSibling===e||t.insertBefore(this.buttonWrapper,e)}}class Xe{constructor(t,...e){this.element=document.createElement(O.socialRosterGroup),this.element.addEventListener("post-render",()=>this.onPostRender()),this.element.addEventListener("click",()=>this.onClick()),this.label=t,this.collapsibleElements=e,this.waitRender()}waitRender(){new MutationObserver((t,e)=>{if(this.element.querySelector(l.socialRosterGroupLabel)){const n=new Event("post-render");this.element.dispatchEvent(n),e.disconnect()}}).observe(this.element,{childList:!0})}onPostRender(){var t;this.element.querySelector(l.socialRosterGroupLabel).innerText=this.label,(t=this.element.querySelector(l.socialRosterGroupHeader))==null||t.removeAttribute("draggable")}onClick(){var t;this.collapsibleElements.forEach(e=>{e.closest(".auto-select-champ-select-menu")||e.classList.toggle("hidden")}),(t=this.element.querySelector(l.socialRosterGroupArrow))==null||t.toggleAttribute("open")}}function Xt(i){var t,e;i&&((e=(t=globalThis.Toast)==null?void 0:t.success)==null||e.call(t,i))}function at(i){var t,e;i&&((e=(t=globalThis.Toast)==null?void 0:t.error)==null||e.call(t,i))}function Je(i,t){const e=globalThis.Toast;return typeof(e==null?void 0:e.promise)=="function"?e.promise(i,t):i}const D="Balaclava: Auto Champion Select";function Ze(i){return typeof(i==null?void 0:i.then)=="function"}class ut{constructor({id:t,name:e,legend:n,tags:o,group:s,callback:r,toasts:a}){this.id=t,this.name=e,this.legend=n,this.tags=o,this.group=s,this.perform=this.perform.bind(this),this.callback=r,this.toasts=a}perform(){try{const t=this.callback();if(Ze(t))return Je(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);Xt(e)}catch(t){at(this.toasts.error),console.error(t)}}}class Jt extends ut{constructor(t,e,n){super({id:`${e}Switch`,name:()=>`Auto ${t} [${k(e).enabled?"ON":"OFF"}]`,legend:()=>k(e).enabled?"Turn OFF":"Turn ON",tags:[D,e,"switch"],group:D,callback:n,toasts:{on:`Auto ${t} is ON!`,off:`Auto ${t} is OFF!`,error:`Failed to toggle Auto ${t}. Check console.`}})}}function tn(i){return H(i,e=>(e.force=!e.force,e)).force}class Zt extends ut{constructor(t,e){super({id:`${e}ForceSwitch`,name:()=>`Force ${t} [${k(e).force?"ON":"OFF"}]`,legend:()=>`Ignore team intent and force ${t} the selected champion`,tags:[D,e,"force","switch"],group:D,callback:()=>tn(e),toasts:{on:`Force ${t} is ON!`,off:`Force ${t} is OFF!`,error:`Failed to toggle Force ${t}. Check console.`}})}}class en extends ut{constructor(t){super({id:"RefreshDropdowns",name:()=>"Refresh Champions",legend:()=>"Normally champion selectors refresh automatically...",tags:[D,"refresh"],group:D,callback:t,toasts:{success:"Refreshed Champions!",error:"Failed to refresh Champions. Check console."}})}}class nn extends Jt{constructor(t){super("Pick","controladoPick",t)}}class on extends Jt{constructor(t){super("Ban","controladoBan",t)}}class sn extends Zt{constructor(){super("Pick","controladoPick")}}class rn extends Zt{constructor(){super("Ban","controladoBan")}}function an(i){for(const t of i)CommandBar.addAction(t)}const cn=200,ln=6e4,Lt=2e3,dn=".ready-check-root-element",hn="#lol-uikit-layer-manager-wrapper > .modal",un="Accepted ready check!",Mt="Failed to accept ready check. Check console.",pn=".auto-select-champ-select-menu__header",N=Object.freeze({autoAccept:"controladoAutoAccept",pick:"controladoPick",ban:"controladoBan"});function te(){return k(N.autoAccept).enabled===!0}class mn{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=fn();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);Bt(t,"display",e==null?void 0:e.display,e==null?void 0:e.displayPriority),Bt(t,"pointer-events",e==null?void 0:e.pointerEvents,e==null?void 0:e.pointerEventsPriority),this.hiddenModalStyles.delete(t),this.hiddenModal=null}}function fn(){const i=document.querySelector(dn);return(i==null?void 0:i.closest(hn))||null}function Bt(i,t,e,n){e?i.style.setProperty(t,e,n||""):i.style.removeProperty(t)}async function gn(i){function t(){return te()?!1:(i.restore(),!0)}if(t()||(console.debug(`auto-champion-select(auto-accept): Ready check detected, accepting in ${Lt}ms...`),await T(Lt),t()))return;let e=!1;try{e=await Pn()}catch(n){throw i.restore(),at(Mt),n}e?Xt(un):(i.restore(),at(Mt))}async function Pn(){const i=await S("POST",m.readyCheckAccept);return i.ok?(console.debug("auto-champion-select(auto-accept): Accepted ready check"),!0):(console.error("auto-champion-select(auto-accept): Failed to accept ready check",i),!1)}async function yn(i){const t=await S("GET",m.gameflowPhase),e=t.ok?await t.json():null;i.handleGameflowPhase(e)}function bn({championSelect:i,champSelectControlsMenu:t,readyCheckModalSuppressor:e,setupChampionSelectors:n}){let o=0;return async function(c){const d=++o;try{await s(c,d)}catch(g){console.error("auto-champion-select: Failed to handle gameflow phase",g)}};async function s(a,c){a==="ReadyCheck"?gn(e).catch(d=>{console.error("auto-champion-select(auto-accept): Failed to handle ready check",d)}):e.restore(),await r(a),c===o&&await n()}async function r(a){a==="ChampSelect"?(i.mount(),await t.mount()):(i.unmount(),await t.unmount())}}function An(){const i=new ve,t=new nt("Accept",N.autoAccept),e=new nt("Pick",N.pick),n=new vt("Add pick",N.pick,Oe,{enablePositionRestrictions:!0,enableRandomAssignedPositionRestrictions:!0,enableBraveryOption:!0,quickActionLabel:"Pick instantly",enableRandomPoolPositionFilters:!0}),o=new nt("Ban",N.ban),s=new vt("Add ban",N.ban,Gt,{quickActionLabel:"Ban instantly",enableRandomPoolPositionFilters:!0}),r=Cn(n,s),a=Sn(t,e,o),c=new Xe("Auto champion select",r,a);return{championSelect:i,autoAcceptToggle:t,pickToggle:e,banToggle:o,pickChampionSelector:n,banChampionSelector:s,selectorsContainer:r,checkboxesContainer:a,pluginSection:c,championSelectors:[n,s]}}function Cn(...i){const t=document.createElement("div");return t.append(...i.map(e=>e.element)),t}function Sn(...i){const t=document.createElement("div");return t.classList.add("auto-select-checkboxes-div"),t.append(...i.map(e=>e.element)),t}function On({pluginSection:i,checkboxesContainer:t,selectorsContainer:e}){let n=null,o=0,s=()=>!1;async function r(a){let c=Ct();for(;!c;){if(s()||a!==o)return;await T(cn),c=Ct()}s()||a!==o||c.append(i.element,t,e)}return{setIsChampSelectControlsMounted(a){s=a},returnControlsToSocialRoster(){if(n)return n;const a=++o;return n=r(a).catch(c=>console.error("auto-champion-select: Failed to return controls to social roster",c)).finally(()=>{n=null}),n}}}function wn({autoAcceptToggle:i,pickToggle:t,banToggle:e,readyCheckModalSuppressor:n}){i.setup(),i.element.addEventListener("click",()=>n.sync()),t.setup(),e.setup()}async function En(i){await Promise.all(i.map(t=>t.setup()))}async function In(i){await Promise.all(i.map(t=>t.refresh()))}function Tn(){const i=An(),t=new mn(te),e=On(i),n=new Ke("Auto Champion Select",e.returnControlsToSocialRoster,[i.checkboxesContainer,i.selectorsContainer]);e.setIsChampSelectControlsMounted(()=>n.mounted);const o={...i,champSelectControlsMenu:n,readyCheckModalSuppressor:t,setupToggles:()=>wn({...i,readyCheckModalSuppressor:t}),setupChampionSelectors:()=>En(i.championSelectors),refreshChampionSelectors:()=>In(i.championSelectors),refreshPickChampionSelector:async()=>{await i.pickChampionSelector.refresh()}};return o.handleGameflowPhase=bn(o),o}function _n(i){pt(m.gameflowPhase,t=>{i.handleGameflowPhase(t.data)}),pt(m.wallet,async t=>{if(t.eventType==="Update"){console.debug("auto-champion-select(wallet): Refreshing champion selectors...");try{await i.refreshPickChampionSelector()}catch(e){console.error("auto-champion-select(wallet): Failed to refresh champion selectors",e)}}})}function kn({pickToggle:i,banToggle:t,refreshChampionSelectors:e}){an([new nn(()=>i.toggle()),new on(()=>t.toggle()),new sn,new rn,new en(e)])}function Rn(i){let t=null,e=null;function n(){e==null||e.disconnect(),e=null,t!==null&&(cancelAnimationFrame(t),t=null)}const o=setTimeout(()=>{n()},ln);function s(){if(!(it()!==null))return;clearTimeout(o),n(),document.querySelector(pn)!==null||i.handleGameflowPhase("ChampSelect")}e=new MutationObserver(()=>{t===null&&(t=requestAnimationFrame(()=>{t=null,s()}))}),e.observe(document.body,{childList:!0,subtree:!0}),s()}async function vn(){const i=Tn();i.setupToggles(),i.readyCheckModalSuppressor.start(),kn(i),_n(i),await yn(i),Rn(i),console.debug(`auto-champion-select(${ee}): Report bugs to Balaclava#1912`)}let Nt=!1;function Ft(){Nt||(Nt=!0,vn().catch(i=>console.error("auto-champion-select: Failed to initialize",i)))}document.readyState==="loading"?window.addEventListener("load",Ft,{once:!0}):Ft();export{Ft as load};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "auto-champion-select",
3
- "version": "1.9.5",
3
+ "version": "1.9.6",
4
4
  "description": "Pick or ban automatically! 🐧",
5
5
  "author": "balaclava",
6
6
  "repository": {