diff --git a/script.js b/script.js index a8f0d36..c43be71 100644 --- a/script.js +++ b/script.js @@ -1,10 +1,50 @@ -"use strict";(()=>{function Z(c){if(c<3)return[];if(c===3)return[3];if(c===4)return[4];if(c===5)return[5];if(c===6)return[3,3];if(c===7)return[4,3];if(c===8)return[4,4];if(c===9)return[3,3,3];if(c===10)return[5,5];let e=Math.floor(c/4),t=c%4;return t===0?Array(e).fill(4):t===1?e>=2?[...Array(e-2).fill(4),5,4]:[3,3,3,2]:t===2?e>=1?[...Array(e-1).fill(4),3,3]:[3,3,3,3]:t===3?[...Array(e).fill(4),3]:[]}function ye(c){if(c<3)return[];if(c<9)return Z(c);if(c===9)return[3,3,3];if(c===10)return[4,3,3];if(c===11)return[4,4,3];if(c===12)return[4,4,4];if(c===13)return[4,3,3,3];if(c===14)return[4,4,3,3];if(c===15)return[4,4,4,3];let e=[],t=c;for(;t>=7;)e.push(4),t-=4;if(t===6)e.push(3,3);else if(t===5)if(e.length>0)e.pop(),t+=4,e.push(3,3,3);else return Z(c);else t===4?e.push(4):t===3&&e.push(3);return e.sort((r,n)=>n-r)}function fe(){let c=document.getElementById("avoid-five-pods-radio");return c&&c.checked?"avoid-five":"balanced"}function ve(){let c=document.getElementById("bracket-radio");if(c&&c.checked)return{allowLeniency:!1,allowSuperLeniency:!1,maxTolerance:0};let e=document.getElementById("no-leniency-radio"),t=document.getElementById("leniency-radio");return document.getElementById("super-leniency-radio").checked?{allowLeniency:!0,allowSuperLeniency:!0,maxTolerance:1}:t.checked?{allowLeniency:!0,allowSuperLeniency:!1,maxTolerance:.5}:{allowLeniency:!1,allowSuperLeniency:!1,maxTolerance:0}}function be(c){let e=[];if(c.forEach(n=>{if(n.checked){let o=parseFloat(n.value);isNaN(o)||e.push(o)}}),e.length===0)return{availablePowers:[],powerRange:"",averagePower:0};e.sort((n,o)=>n-o);let t;e.length===1?t=e[0].toString():t=e.join(", ");let r=e.reduce((n,o)=>n+o,0)/e.length;return{availablePowers:e,powerRange:t,averagePower:Math.round(r*2)/2}}function Me(){let c=document.querySelector("#leniency-radio");return document.querySelector("#super-leniency-radio")?.checked?1:c?.checked?.5:0}function J(c){let e=c.players.flatMap(o=>"players"in o?o.players:[o]);if(e.length===0)return c.power.toString();let t=Me(),r=[],n=new Set;e.forEach(o=>{o.availablePowers.forEach(s=>n.add(s))});for(let o of n)e.every(a=>a.availablePowers.some(i=>Math.abs(o-i)<=t))&&r.push(o);return r.sort((o,s)=>o-s),r.length===0?c.power.toString():r.length===1?r[0].toString():r.every((s,a)=>a===0||s-r[a-1]<=.5)&&r.length>2?`${r[0]}-${r[r.length-1]}`:r.join(", ")}function j(c,e){let t=[];if(Array.isArray(c.availablePowers))t=c.availablePowers;else if(typeof c.powerRange=="string")if(c.powerRange.includes("-")){let[n,o]=c.powerRange.split("-").map(s=>parseFloat(s.trim()));for(let s=n;s<=o;s+=.5)t.push(s)}else t=c.powerRange.split(",").map(n=>parseFloat(n.trim()));return t.map(n=>e.includes(n)?`${n}`:n.toString()).join(", ")}function Ee(c,e){let t=[];if(Array.isArray(c.availableBrackets))t=c.availableBrackets;else if(typeof c.bracketRange=="string")if(c.bracketRange.includes("-")){let[n,o]=c.bracketRange.split("-").map(i=>i.trim()),s=parseInt(n),a=parseInt(o);if(!isNaN(s)&&!isNaN(a))for(let i=s;i<=a;i++)t.push(i.toString());else t=[n,o]}else t=c.bracketRange.split(",").map(n=>n.trim());return t.map(n=>e.includes(n)?`${n}`:n.toString()).join(", ")}function Y(c){let e=c.players.flatMap(s=>"players"in s?s.players:[s]);if(e.length===0)return[];let t=new Map,r=new Set;if(e.forEach(s=>{s.availablePowers.length===1&&r.add(s.availablePowers[0]),s.availablePowers.forEach(a=>{t.set(a,(t.get(a)||0)+1)})}),t.size===0)return[];let n=Math.max(...t.values()),o=[];for(let[s,a]of t.entries())(a===n||r.has(s))&&o.push(s);return o.sort((s,a)=>s-a),o}var X=class{constructor(){this.groups=new Map;this.nextPlayerId=0;this.nextGroupId=1;this.availableColors=[];this.groupColorAssignments=new Map;this.initializeAvailableColors()}initializeAvailableColors(){this.availableColors=Array.from({length:50},(e,t)=>t+1),this.shuffleArray(this.availableColors)}shuffleArray(e){for(let t=e.length-1;t>0;t--){let r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]]}}assignRandomColor(e){if(this.groupColorAssignments.has(e))return this.groupColorAssignments.get(e);this.availableColors.length===0&&this.initializeAvailableColors();let t=this.availableColors.pop();return this.groupColorAssignments.set(e,t),t}releaseColor(e){let t=this.groupColorAssignments.get(e);t&&(this.availableColors.push(t),this.groupColorAssignments.delete(e))}getNextPlayerId(){return this.nextPlayerId++}resetPlayerIds(){this.nextPlayerId=0}getNextGroupId(){let e=new Set;document.querySelectorAll(".group-select").forEach(r=>{if(r.value.startsWith("group-")){let n=parseInt(r.value.split("-")[1]);isNaN(n)||e.add(n)}if(r.value==="new-group"&&r.dataset.createdGroupId&&r.dataset.createdGroupId.startsWith("group-")){let n=parseInt(r.dataset.createdGroupId.split("-")[1]);isNaN(n)||e.add(n)}});for(let r=1;r<=50;r++)if(!e.has(r))return r;return this.nextGroupId++}resetGroupIds(){this.nextGroupId=1}getGroups(){return this.groups}clearGroups(){this.groups.clear()}getPlayerFromRow(e){let t=e.querySelector(".player-name");t.classList.remove("input-error");let r=t.value.trim();if(!r)return t.classList.add("input-error"),null;if(document.getElementById("bracket-radio").checked){let s=e.querySelectorAll('.bracket-checkbox input[type="checkbox"]'),a=[];if(s.forEach(p=>{p.checked&&a.push(p.value)}),a.length===0)return e.querySelector(".bracket-selector-btn").classList.add("error"),null;e.querySelector(".bracket-selector-btn").classList.remove("error");let i={1:1,2:2,3:3,4:4,cedh:10},l=a.map(p=>i[p]),d=l.reduce((p,u)=>p+u,0)/l.length;return{id:parseInt(e.dataset.playerId),name:r,power:Math.round(d*2)/2,availablePowers:l,powerRange:a.join(", "),brackets:a,bracketRange:a.join(", "),rowElement:e}}else{let s=e.querySelectorAll('.power-checkbox input[type="checkbox"]'),a=be(s);return a.availablePowers.length===0?(e.querySelector(".power-selector-btn").classList.add("error"),null):(e.querySelector(".power-selector-btn").classList.remove("error"),{id:parseInt(e.dataset.playerId),name:r,power:a.averagePower,availablePowers:a.availablePowers,powerRange:a.powerRange,rowElement:e})}}handleGroupChange(e){this.groups.clear();let t=Array.from(e.querySelectorAll(".player-row"));t.forEach(n=>{for(let o=1;o<=50;o++)n.querySelector(".group-select").classList.remove(`group-${o}`)});let r=new Set;t.forEach(n=>{let o=n.querySelector(".group-select");o.dataset.createdGroupId?r.add(o.dataset.createdGroupId):o.value.startsWith("group-")&&r.add(o.value)}),t.forEach(n=>{let o=n.querySelector(".group-select"),s="";if(o.value==="new-group"){o.dataset.createdGroupId?s=o.dataset.createdGroupId:(s=`group-${this.getNextGroupId()}`,r.add(s),o.dataset.createdGroupId=s);let a=this.getPlayerFromRow(n);a&&(this.groups.has(s)||this.groups.set(s,[]),this.groups.get(s).push(a))}else if(o.value.startsWith("group-")){s=o.value;let a=this.getPlayerFromRow(n);a&&(this.groups.has(o.value)||this.groups.set(o.value,[]),this.groups.get(o.value).push(a))}else o.dataset.createdGroupId&&delete o.dataset.createdGroupId;if(s){let a=parseInt(s.split("-")[1]);a>=1&&a<=50&&o.classList.add(`group-${a}`)}}),this.cleanupUnusedGroups(r),this.updateAllGroupDropdowns(e)}updateAllGroupDropdowns(e){let t=new Set,r=Array.from(e.querySelectorAll(".player-row"));r.forEach(n=>{let o=n.querySelector(".group-select");o.value==="new-group"&&o.dataset.createdGroupId?t.add(o.dataset.createdGroupId):o.value.startsWith("group-")&&t.add(o.value)}),r.forEach(n=>{let o=n.querySelector(".group-select"),s=o.value,a=o.dataset.createdGroupId;if(Array.from(o.options).forEach(l=>{l.value.startsWith("group-")&&o.remove(l.index)}),t.forEach(l=>{let d=l.split("-")[1],p=new Option(`Group ${d}`,l);o.add(p)}),a&&t.has(a)&&(s==="new-group"||s==="no-group")){o.value=a;let l=parseInt(a.split("-")[1]);l>=1&&l<=50&&o.classList.add(`group-${l}`)}else if(s.startsWith("group-")&&t.has(s)){o.value=s;let l=parseInt(s.split("-")[1]);l>=1&&l<=50&&o.classList.add(`group-${l}`)}else{o.value="no-group";for(let l=1;l<=50;l++)o.classList.remove(`group-${l}`)}})}arePlayersCompatible(e,t,r){return e.availablePowers.some(o=>t.availablePowers.some(s=>Math.abs(o-s)<.01))?!0:r.allowLeniency?e.availablePowers.some(o=>t.availablePowers.some(s=>Math.abs(o-s)<=r.maxTolerance)):!1}findAllCommonPowers(e,t){return e.length===0?[]:[...new Set(e.flatMap(n=>n.availablePowers))].sort((n,o)=>n-o).filter(n=>e.every(o=>o.availablePowers.some(s=>{let a=Math.abs(s-n);return a<.01||t.allowLeniency&&a<=t.maxTolerance})))}findBestCommonPowerLevel(e){if(e.length===0)return null;let t=new Map;for(let o of e)for(let s of o.availablePowers)t.set(s,(t.get(s)||0)+1);if(t.size===0)return null;let r=e[0].availablePowers[0],n=0;for(let[o,s]of t.entries())s>n&&(n=s,r=o);return r}calculatePodPower(e){if(e.length===0)return 0;let t=e.reduce((r,n)=>{if("players"in n)return r+n.averagePower;{let o=n.powerRange.split(",").map(a=>parseFloat(a.trim())),s=o.reduce((a,i)=>a+i,0)/o.length;return r+s}},0);return Math.round(t/e.length*10)/10}cleanupUnusedGroups(e){Array.from(this.groupColorAssignments.keys()).forEach(o=>{e.has(o)||this.releaseColor(o)}),Array.from(this.groups.keys()).forEach(o=>{e.has(o)||this.groups.delete(o)}),document.querySelectorAll(".group-select").forEach(o=>{let s=o.dataset.createdGroupId;s&&!e.has(s)&&delete o.dataset.createdGroupId})}};var ee=class{constructor(){this.shuffleSeed=null;this.sizeCache=new Map}setShuffleSeed(e){this.shuffleSeed=e,this.sizeCache.clear()}seededRandom(e){let t=e;return()=>(t=t*1103515245+12345&2147483647,t/2147483647)}shuffleArray(e){let t=[...e],r;this.shuffleSeed!==null?r=this.seededRandom(this.shuffleSeed):r=Math.random;for(let n=t.length-1;n>0;n--){let o=Math.floor(r()*(n+1));[t[n],t[o]]=[t[o],t[n]]}return t}getItemSize(e){let t="players"in e?`group-${e.id}`:`player-${e.id}`;if(!this.sizeCache.has(t)){let r="players"in e?e.size:1;this.sizeCache.set(t,r)}return this.sizeCache.get(t)}getItemId(e){return"players"in e?e.id:e.id.toString()}generatePodsWithBacktracking(e,t,r){let n=this.shuffleArray(e),o=n.reduce((l,d)=>l+("size"in d?d.size:1),0);if(o>=3&&o<=5){let l=n.flatMap(p=>"players"in p?p.players:[p]),d=this.findBestCommonPowerLevel(l);return d!==null?{pods:[{players:n,power:d}],unassigned:[]}:{pods:[],unassigned:n}}let s=this.findOptimalPodAssignment(n,t,r),a=new Set;for(let l of s)for(let d of l.players)"players"in d?a.add(d.id):a.add(d.id.toString());let i=n.filter(l=>"players"in l?!a.has(l.id):!a.has(l.id.toString()));return{pods:s,unassigned:i}}findOptimalPodAssignment(e,t,r){return this.optimizeVirtualPlayerAssignmentUnified(e,t,r)}optimizeVirtualPlayerAssignmentUnified(e,t,r){if(e.length===0)return[];let n=this.createVirtualPlayersUnified(e),o=new Map;for(let a of n)o.has(a.powerLevel)||o.set(a.powerLevel,[]),o.get(a.powerLevel).push(a);let s={pods:[],totalPods:0};return r.allowLeniency?this.backtrackVirtualPlayersWithLeniencyUnified(n,t,r.maxTolerance,[],new Set,t,s):this.backtrackVirtualPlayersUnified(Array.from(o.entries()),[],new Set,t,s),s.pods}createVirtualPlayersUnified(e){let t=[];for(let r of e)if("players"in r){let n=r.players.flatMap(d=>d.availablePowers),o=Math.min(...n),s=Math.max(...n),i=[r.averagePower,o,s],l=[...new Set(i)];for(let d of l)t.push({item:r,powerLevel:d})}else for(let n of r.availablePowers)t.push({item:r,powerLevel:n});return t}backtrackVirtualPlayersUnified(e,t,r,n,o){if(n.length===0){t.length>o.totalPods&&(o.pods=[...t],o.totalPods=t.length);return}if(t.length+n.length<=o.totalPods)return;let s=n[0],a=n.slice(1);for(let[i,l]of e){let d=l.filter(E=>{let f=this.getItemId(E.item);return!r.has(f)}),p=0;for(let E=0;E=u){let E=d.sort((v,m)=>{let h=this.getItemSize(v.item);return this.getItemSize(m.item)-h}),f=[],P=new Set,g=0;for(let v of E){let m=this.getItemId(v.item),h=this.getItemSize(v.item);if(!P.has(m)&&g+h<=s&&(f.push(v),P.add(m),g+=h,g===s))break}if(g>=3){let v=f.map(y=>y.item),m={players:v,power:i},h=new Set(r);for(let y of v){let w="players"in y?y.id:y.id.toString();h.add(w)}this.backtrackVirtualPlayersUnified(e,[...t,m],h,a,o)}}}this.backtrackVirtualPlayersUnified(e,t,r,a,o)}backtrackVirtualPlayersWithLeniencyUnified(e,t,r,n,o,s,a){if(s.length===0){n.length>a.totalPods&&(a.pods=[...n],a.totalPods=n.length);return}if(n.length+s.length<=a.totalPods)return;let i=s[0],l=s.slice(1),d=e.filter(u=>{let E="players"in u.item?u.item.id:u.item.id.toString();return!o.has(E)}),p=[...new Set(d.map(u=>u.powerLevel))].sort((u,E)=>u-E);for(let u of p){let E=d.filter(h=>("players"in h.item,Math.abs(h.powerLevel-u)<=r)),f=new Map;for(let h of E){let y="players"in h.item?h.item.id:h.item.id.toString();if(!f.has(y))f.set(y,h);else{let w=f.get(y),k=Math.abs(w.powerLevel-u);Math.abs(h.powerLevel-u){if("players"in h.item&&"players"in y.item){let w=Math.abs(h.powerLevel-h.item.averagePower)<.01,k=Math.abs(y.powerLevel-y.item.averagePower)<.01;return w&&!k?-1:!w&&k?1:Math.abs(h.powerLevel-u)-Math.abs(y.powerLevel-u)}return"players"in h.item&&!("players"in y.item)?1:!("players"in h.item)&&"players"in y.item?-1:Math.abs(h.powerLevel-u)-Math.abs(y.powerLevel-u)}),v=0;for(let h=0;h=m){let h=g.sort((b,L)=>{let T=this.getItemSize(b.item);return this.getItemSize(L.item)-T}),y=[],w=new Set,k=0;for(let b of h){let L=this.getItemId(b.item),T=this.getItemSize(b.item);if(!w.has(L)&&k+T<=i&&(y.push(b),w.add(L),k+=T,k===i))break}if(k>=3){let b=y.map(I=>I.item);if(!this.isPodPowerSpreadValid(y,r))continue;let L=y.reduce((I,$)=>I+$.powerLevel,0)/y.length,T={players:b,power:Math.round(L*2)/2},S=new Set(o);for(let I of b){let $="players"in I?I.id:I.id.toString();S.add($),e.forEach(G=>{let ae="players"in G.item?G.item.id:G.item.id.toString();ae===$&&S.add(ae)})}this.backtrackVirtualPlayersWithLeniencyUnified(e,t,r,[...n,T],S,l,a)}}}this.backtrackVirtualPlayersWithLeniencyUnified(e,t,r,n,o,l,a)}isPodPowerSpreadValid(e,t){if(e.length===0)return!0;let r=e.map(a=>a.powerLevel),n=Math.min(...r);return Math.max(...r)-n<=t}findBestCommonPowerLevel(e){if(e.length===0)return null;let t=new Map;for(let o of e)for(let s of o.availablePowers)t.set(s,(t.get(s)||0)+1);if(t.size===0)return null;let r=e[0].availablePowers[0],n=0;for(let[o,s]of t.entries())s>n&&(n=s,r=o);return r}};var te=class{constructor(e,t){this.draggedElement=null;this.draggedItemData=null;this.currentPods=[];this.currentUnassigned=[];this.handleDragStart=e=>{let t=e.target;this.draggedElement=t,t.classList.add("dragging"),this.draggedItemData={type:t.dataset.itemType,id:t.dataset.itemId,podIndex:t.dataset.podIndex,itemIndex:t.dataset.itemIndex},e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/html",t.outerHTML)};this.handleDragEnd=e=>{e.target.classList.remove("dragging"),this.draggedElement=null,this.draggedItemData=null};this.handleDragOver=e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",e.currentTarget.classList.add("drag-over")};this.handleDragLeave=e=>{e.currentTarget.classList.remove("drag-over")};this.handleDrop=e=>{e.preventDefault();let t=e.currentTarget;if(t.classList.remove("drag-over"),!this.draggedItemData)return;let r=t.dataset.podIndex,n=this.draggedItemData.podIndex;r!==n&&this.moveItemBetweenPods(this.draggedItemData,r)};this.playerManager=e,this.onPodsChanged=t}setCurrentPods(e,t=[]){this.currentPods=[...e],this.currentUnassigned=[...t]}moveItemBetweenPods(e,t){let r=e.podIndex,n=parseInt(e.itemIndex),o=null;if(r==="unassigned")o=this.currentUnassigned[n],this.currentUnassigned.splice(n,1);else{let s=this.currentPods[parseInt(r)];o=s.players[n],s.players.splice(n,1),s.power=this.playerManager.calculatePodPower(s.players)}if(o){if(t==="unassigned")this.currentUnassigned.push(o);else if(t==="new-pod"){let s={players:[o],power:this.playerManager.calculatePodPower([o])};this.currentPods.push(s)}else{let s=this.currentPods[parseInt(t)];s.players.push(o),s.power=this.playerManager.calculatePodPower(s.players)}this.cleanupEmptyPods(),this.onPodsChanged(this.currentPods,this.currentUnassigned)}}cleanupEmptyPods(){this.currentPods=this.currentPods.filter(e=>e.players.length>0)}};var ie=class{constructor(){this.pools=new Map;this.POOL_SIZE=15}get(e){let t=this.pools.get(e.toLowerCase())||[];if(t.length>0){let r=t.pop();return this.resetElement(r),r}return document.createElement(e)}release(e){let t=e.tagName.toLowerCase(),r=this.pools.get(t);r||(r=[],this.pools.set(t,r)),r.length{delete e.dataset[t]})}clear(){this.pools.clear()}getStats(){let e={};return this.pools.forEach((t,r)=>{e[r]=t.length}),e}preWarm(){[{tag:"div",count:8},{tag:"li",count:6},{tag:"ul",count:4},{tag:"h3",count:3},{tag:"p",count:3},{tag:"strong",count:3},{tag:"button",count:2}].forEach(({tag:t,count:r})=>{let n=[];for(let o=0;o0;r--){let n=Math.floor(Math.random()*(r+1));[t[r],t[n]]=[t[n],t[r]]}if(e>t.length){let r=[];for(let n=0;n"players"in s?s.players:[s]);if(t.length===0)return"Unknown";let r=[],n=new Set;t.forEach(s=>{s.brackets&&s.brackets.forEach(a=>n.add(a))});for(let s of n)t.every(i=>i.brackets&&i.brackets.includes(s))&&r.push(s);let o=["1","2","3","4","cedh"];if(r.sort((s,a)=>o.indexOf(s)-o.indexOf(a)),r.length===0)return"Unknown";if(r.length===1)return r[0];{let s=r.filter(i=>i!=="cedh");return s.length>1&&s.every((i,l)=>{if(l===0)return!0;let d=parseInt(i),p=parseInt(s[l-1]);return d===p+1})&&s.length===r.length&&r.length>1?`${r[0]}-${r[r.length-1]}`:r.join(", ")}}getValidBracketsArrayForPod(e){let t=e.players.flatMap(a=>"players"in a?a.players:[a]);if(t.length===0)return[];let r=new Map;if(t.forEach(a=>{a.brackets&&a.brackets.forEach(i=>{r.set(i,(r.get(i)||0)+1)})}),r.size===0)return[];let n=Math.ceil(t.length/2),o=[];for(let[a,i]of r.entries())i>=n&&o.push(a);let s=["1","2","3","4","cedh"];return o.sort((a,i)=>s.indexOf(a)-s.indexOf(i)),o}enterDisplayMode(e){if(e.length===0)return;this.isDisplayMode=!0,document.body.classList.add("display-mode");let t=Math.ceil(Math.sqrt(e.length)),r=A.get("div");r.className="display-mode-container",r.style.position="fixed",r.style.top="0",r.style.left="0",r.style.width="100vw",r.style.height="100vh",r.style.background="#1a1a1a",r.style.zIndex="1000",r.style.padding="20px",r.style.boxSizing="border-box",r.style.overflow="hidden",r.innerHTML=` +"use strict";(()=>{function Z(c){if(c<3)return[];if(c===3)return[3];if(c===4)return[4];if(c===5)return[5];if(c===6)return[3,3];if(c===7)return[4,3];if(c===8)return[4,4];if(c===9)return[3,3,3];if(c===10)return[5,5];let e=Math.floor(c/4),t=c%4;return t===0?Array(e).fill(4):t===1?e>=2?[...Array(e-2).fill(4),5,4]:[3,3,3,2]:t===2?e>=1?[...Array(e-1).fill(4),3,3]:[3,3,3,3]:t===3?[...Array(e).fill(4),3]:[]}function fe(c){if(c<3)return[];if(c<9)return Z(c);if(c===9)return[3,3,3];if(c===10)return[4,3,3];if(c===11)return[4,4,3];if(c===12)return[4,4,4];if(c===13)return[4,3,3,3];if(c===14)return[4,4,3,3];if(c===15)return[4,4,4,3];let e=[],t=c;for(;t>=7;)e.push(4),t-=4;if(t===6)e.push(3,3);else if(t===5)if(e.length>0)e.pop(),t+=4,e.push(3,3,3);else return Z(c);else t===4?e.push(4):t===3&&e.push(3);return e.sort((r,n)=>n-r)}function ve(){let c=document.getElementById("avoid-five-pods-radio");return c&&c.checked?"avoid-five":"balanced"}function be(){let c=document.getElementById("bracket-radio");if(c&&c.checked)return{allowLeniency:!1,allowSuperLeniency:!1,maxTolerance:0};let e=document.getElementById("no-leniency-radio"),t=document.getElementById("leniency-radio");return document.getElementById("super-leniency-radio").checked?{allowLeniency:!0,allowSuperLeniency:!0,maxTolerance:1}:t.checked?{allowLeniency:!0,allowSuperLeniency:!1,maxTolerance:.5}:{allowLeniency:!1,allowSuperLeniency:!1,maxTolerance:0}}function Ee(c){let e=[];if(c.forEach(n=>{if(n.checked){let o=parseFloat(n.value);isNaN(o)||e.push(o)}}),e.length===0)return{availablePowers:[],powerRange:"",averagePower:0};e.sort((n,o)=>n-o);let t;e.length===1?t=e[0].toString():t=e.join(", ");let r=e.reduce((n,o)=>n+o,0)/e.length;return{availablePowers:e,powerRange:t,averagePower:Math.round(r*2)/2}}function Pe(){let c=document.querySelector("#leniency-radio");return document.querySelector("#super-leniency-radio")?.checked?1:c?.checked?.5:0}function J(c){let e=c.players.flatMap(o=>"players"in o?o.players:[o]);if(e.length===0)return c.power.toString();let t=Pe(),r=[],n=new Set;e.forEach(o=>{o.availablePowers.forEach(s=>n.add(s))});for(let o of n)e.every(a=>a.availablePowers.some(i=>Math.abs(o-i)<=t))&&r.push(o);return r.sort((o,s)=>o-s),r.length===0?c.power.toString():r.length===1?r[0].toString():r.every((s,a)=>a===0||s-r[a-1]<=.5)&&r.length>2?`${r[0]}-${r[r.length-1]}`:r.join(", ")}function j(c,e){let t=[];if(Array.isArray(c.availablePowers))t=c.availablePowers;else if(typeof c.powerRange=="string")if(c.powerRange.includes("-")){let[n,o]=c.powerRange.split("-").map(s=>parseFloat(s.trim()));for(let s=n;s<=o;s+=.5)t.push(s)}else t=c.powerRange.split(",").map(n=>parseFloat(n.trim()));return t.map(n=>e.includes(n)?`${n}`:n.toString()).join(", ")}function we(c,e){let t=[];if(Array.isArray(c.availableBrackets))t=c.availableBrackets;else if(typeof c.bracketRange=="string")if(c.bracketRange.includes("-")){let[n,o]=c.bracketRange.split("-").map(i=>i.trim()),s=parseInt(n),a=parseInt(o);if(!isNaN(s)&&!isNaN(a))for(let i=s;i<=a;i++)t.push(i.toString());else t=[n,o]}else t=c.bracketRange.split(",").map(n=>n.trim());return t.map(n=>e.includes(n)?`${n}`:n.toString()).join(", ")}function Y(c){let e=c.players.flatMap(s=>"players"in s?s.players:[s]);if(e.length===0)return[];let t=new Map,r=new Set;if(e.forEach(s=>{s.availablePowers.length===1&&r.add(s.availablePowers[0]),s.availablePowers.forEach(a=>{t.set(a,(t.get(a)||0)+1)})}),t.size===0)return[];let n=Math.max(...t.values()),o=[];for(let[s,a]of t.entries())(a===n||r.has(s))&&o.push(s);return o.sort((s,a)=>s-a),o}var X=class{constructor(){this.groups=new Map;this.nextPlayerId=0;this.nextGroupId=1;this.availableColors=[];this.groupColorAssignments=new Map;this.initializeAvailableColors()}initializeAvailableColors(){this.availableColors=Array.from({length:50},(e,t)=>t+1),this.shuffleArray(this.availableColors)}shuffleArray(e){for(let t=e.length-1;t>0;t--){let r=Math.floor(Math.random()*(t+1));[e[t],e[r]]=[e[r],e[t]]}}assignRandomColor(e){if(this.groupColorAssignments.has(e))return this.groupColorAssignments.get(e);this.availableColors.length===0&&this.initializeAvailableColors();let t=this.availableColors.pop();return this.groupColorAssignments.set(e,t),t}releaseColor(e){let t=this.groupColorAssignments.get(e);t&&(this.availableColors.push(t),this.groupColorAssignments.delete(e))}getNextPlayerId(){return this.nextPlayerId++}resetPlayerIds(){this.nextPlayerId=0}getNextGroupId(){let e=new Set;document.querySelectorAll(".group-select").forEach(r=>{if(r.value.startsWith("group-")){let n=parseInt(r.value.split("-")[1]);isNaN(n)||e.add(n)}if(r.value==="new-group"&&r.dataset.createdGroupId&&r.dataset.createdGroupId.startsWith("group-")){let n=parseInt(r.dataset.createdGroupId.split("-")[1]);isNaN(n)||e.add(n)}});for(let r=1;r<=50;r++)if(!e.has(r))return r;return this.nextGroupId++}resetGroupIds(){this.nextGroupId=1}getGroups(){return this.groups}clearGroups(){this.groups.clear()}getPlayerFromRow(e){let t=e.querySelector(".player-name");t.classList.remove("input-error");let r=t.value.trim();if(!r)return t.classList.add("input-error"),null;if(document.getElementById("bracket-radio").checked){let s=e.querySelectorAll('.bracket-checkbox input[type="checkbox"]'),a=[];if(s.forEach(p=>{p.checked&&a.push(p.value)}),a.length===0)return e.querySelector(".bracket-selector-btn").classList.add("error"),null;e.querySelector(".bracket-selector-btn").classList.remove("error");let i={1:1,2:2,3:3,4:4,cedh:10},l=a.map(p=>i[p]),d=l.reduce((p,u)=>p+u,0)/l.length;return{id:parseInt(e.dataset.playerId),name:r,power:Math.round(d*2)/2,availablePowers:l,powerRange:a.join(", "),brackets:a,bracketRange:a.join(", "),rowElement:e}}else{let s=e.querySelectorAll('.power-checkbox input[type="checkbox"]'),a=Ee(s);return a.availablePowers.length===0?(e.querySelector(".power-selector-btn").classList.add("error"),null):(e.querySelector(".power-selector-btn").classList.remove("error"),{id:parseInt(e.dataset.playerId),name:r,power:a.averagePower,availablePowers:a.availablePowers,powerRange:a.powerRange,rowElement:e})}}handleGroupChange(e){this.groups.clear();let t=Array.from(e.querySelectorAll(".player-row"));t.forEach(n=>{for(let o=1;o<=50;o++)n.querySelector(".group-select").classList.remove(`group-${o}`)});let r=new Set;t.forEach(n=>{let o=n.querySelector(".group-select");o.dataset.createdGroupId?r.add(o.dataset.createdGroupId):o.value.startsWith("group-")&&r.add(o.value)}),t.forEach(n=>{let o=n.querySelector(".group-select"),s="";if(o.value==="new-group"){o.dataset.createdGroupId?s=o.dataset.createdGroupId:(s=`group-${this.getNextGroupId()}`,r.add(s),o.dataset.createdGroupId=s);let a=this.getPlayerFromRow(n);a&&(this.groups.has(s)||this.groups.set(s,[]),this.groups.get(s).push(a))}else if(o.value.startsWith("group-")){s=o.value;let a=this.getPlayerFromRow(n);a&&(this.groups.has(o.value)||this.groups.set(o.value,[]),this.groups.get(o.value).push(a))}else o.dataset.createdGroupId&&delete o.dataset.createdGroupId;if(s){let a=parseInt(s.split("-")[1]);a>=1&&a<=50&&o.classList.add(`group-${a}`)}}),this.cleanupUnusedGroups(r),this.updateAllGroupDropdowns(e)}updateAllGroupDropdowns(e){let t=new Set,r=Array.from(e.querySelectorAll(".player-row"));r.forEach(n=>{let o=n.querySelector(".group-select");o.value==="new-group"&&o.dataset.createdGroupId?t.add(o.dataset.createdGroupId):o.value.startsWith("group-")&&t.add(o.value)}),r.forEach(n=>{let o=n.querySelector(".group-select"),s=o.value,a=o.dataset.createdGroupId;if(Array.from(o.options).forEach(l=>{l.value.startsWith("group-")&&o.remove(l.index)}),t.forEach(l=>{let d=l.split("-")[1],p=new Option(`Group ${d}`,l);o.add(p)}),a&&t.has(a)&&(s==="new-group"||s==="no-group")){o.value=a;let l=parseInt(a.split("-")[1]);l>=1&&l<=50&&o.classList.add(`group-${l}`)}else if(s.startsWith("group-")&&t.has(s)){o.value=s;let l=parseInt(s.split("-")[1]);l>=1&&l<=50&&o.classList.add(`group-${l}`)}else{o.value="no-group";for(let l=1;l<=50;l++)o.classList.remove(`group-${l}`)}})}arePlayersCompatible(e,t,r){return e.availablePowers.some(o=>t.availablePowers.some(s=>Math.abs(o-s)<.01))?!0:r.allowLeniency?e.availablePowers.some(o=>t.availablePowers.some(s=>Math.abs(o-s)<=r.maxTolerance)):!1}findAllCommonPowers(e,t){return e.length===0?[]:[...new Set(e.flatMap(n=>n.availablePowers))].sort((n,o)=>n-o).filter(n=>e.every(o=>o.availablePowers.some(s=>{let a=Math.abs(s-n);return a<.01||t.allowLeniency&&a<=t.maxTolerance})))}findBestCommonPowerLevel(e){if(e.length===0)return null;let t=new Map;for(let o of e)for(let s of o.availablePowers)t.set(s,(t.get(s)||0)+1);if(t.size===0)return null;let r=e[0].availablePowers[0],n=0;for(let[o,s]of t.entries())s>n&&(n=s,r=o);return r}calculatePodPower(e){if(e.length===0)return 0;let t=e.reduce((r,n)=>{if("players"in n)return r+n.averagePower;{let o=n.powerRange.split(",").map(a=>parseFloat(a.trim())),s=o.reduce((a,i)=>a+i,0)/o.length;return r+s}},0);return Math.round(t/e.length*10)/10}cleanupUnusedGroups(e){Array.from(this.groupColorAssignments.keys()).forEach(o=>{e.has(o)||this.releaseColor(o)}),Array.from(this.groups.keys()).forEach(o=>{e.has(o)||this.groups.delete(o)}),document.querySelectorAll(".group-select").forEach(o=>{let s=o.dataset.createdGroupId;s&&!e.has(s)&&delete o.dataset.createdGroupId})}};var ee=class{constructor(){this.shuffleSeed=null;this.sizeCache=new Map}setShuffleSeed(e){this.shuffleSeed=e,this.sizeCache.clear()}seededRandom(e){let t=e;return()=>(t=t*1103515245+12345&2147483647,t/2147483647)}shuffleArray(e){let t=[...e],r;this.shuffleSeed!==null?r=this.seededRandom(this.shuffleSeed):r=Math.random;for(let n=t.length-1;n>0;n--){let o=Math.floor(r()*(n+1));[t[n],t[o]]=[t[o],t[n]]}return t}getItemSize(e){let t="players"in e?`group-${e.id}`:`player-${e.id}`;if(!this.sizeCache.has(t)){let r="players"in e?e.size:1;this.sizeCache.set(t,r)}return this.sizeCache.get(t)}getItemId(e){return"players"in e?e.id:e.id.toString()}generatePodsWithBacktracking(e,t,r){let n=this.shuffleArray(e),o=n.reduce((l,d)=>l+("size"in d?d.size:1),0);if(o>=3&&o<=5){let l=n.flatMap(p=>"players"in p?p.players:[p]),d=this.findBestCommonPowerLevel(l);return d!==null?{pods:[{players:n,power:d}],unassigned:[]}:{pods:[],unassigned:n}}let s=this.findOptimalPodAssignment(n,t,r),a=new Set;for(let l of s)for(let d of l.players)"players"in d?a.add(d.id):a.add(d.id.toString());let i=n.filter(l=>"players"in l?!a.has(l.id):!a.has(l.id.toString()));return{pods:s,unassigned:i}}findOptimalPodAssignment(e,t,r){return this.optimizeVirtualPlayerAssignmentUnified(e,t,r)}optimizeVirtualPlayerAssignmentUnified(e,t,r){if(e.length===0)return[];let n=this.createVirtualPlayersUnified(e),o=new Map;for(let a of n)o.has(a.powerLevel)||o.set(a.powerLevel,[]),o.get(a.powerLevel).push(a);let s={pods:[],totalPods:0};return r.allowLeniency?this.backtrackVirtualPlayersWithLeniencyUnified(n,t,r.maxTolerance,[],new Set,t,s):this.backtrackVirtualPlayersUnified(Array.from(o.entries()),[],new Set,t,s),s.pods}createVirtualPlayersUnified(e){let t=[];for(let r of e)if("players"in r){let n=r.players.flatMap(d=>d.availablePowers),o=Math.min(...n),s=Math.max(...n),i=[r.averagePower,o,s],l=[...new Set(i)];for(let d of l)t.push({item:r,powerLevel:d})}else for(let n of r.availablePowers)t.push({item:r,powerLevel:n});return t}backtrackVirtualPlayersUnified(e,t,r,n,o){if(n.length===0){t.length>o.totalPods&&(o.pods=[...t],o.totalPods=t.length);return}if(t.length+n.length<=o.totalPods)return;let s=n[0],a=n.slice(1);for(let[i,l]of e){let d=l.filter(E=>{let f=this.getItemId(E.item);return!r.has(f)}),p=0;for(let E=0;E=u){let E=d.sort((v,m)=>{let h=this.getItemSize(v.item);return this.getItemSize(m.item)-h}),f=[],P=new Set,g=0;for(let v of E){let m=this.getItemId(v.item),h=this.getItemSize(v.item);if(!P.has(m)&&g+h<=s&&(f.push(v),P.add(m),g+=h,g===s))break}if(g>=3){let v=f.map(y=>y.item),m={players:v,power:i},h=new Set(r);for(let y of v){let w="players"in y?y.id:y.id.toString();h.add(w)}this.backtrackVirtualPlayersUnified(e,[...t,m],h,a,o)}}}this.backtrackVirtualPlayersUnified(e,t,r,a,o)}backtrackVirtualPlayersWithLeniencyUnified(e,t,r,n,o,s,a){if(s.length===0){n.length>a.totalPods&&(a.pods=[...n],a.totalPods=n.length);return}if(n.length+s.length<=a.totalPods)return;let i=s[0],l=s.slice(1),d=e.filter(u=>{let E="players"in u.item?u.item.id:u.item.id.toString();return!o.has(E)}),p=[...new Set(d.map(u=>u.powerLevel))].sort((u,E)=>u-E);for(let u of p){let E=d.filter(h=>("players"in h.item,Math.abs(h.powerLevel-u)<=r)),f=new Map;for(let h of E){let y="players"in h.item?h.item.id:h.item.id.toString();if(!f.has(y))f.set(y,h);else{let w=f.get(y),M=Math.abs(w.powerLevel-u);Math.abs(h.powerLevel-u){if("players"in h.item&&"players"in y.item){let w=Math.abs(h.powerLevel-h.item.averagePower)<.01,M=Math.abs(y.powerLevel-y.item.averagePower)<.01;return w&&!M?-1:!w&&M?1:Math.abs(h.powerLevel-u)-Math.abs(y.powerLevel-u)}return"players"in h.item&&!("players"in y.item)?1:!("players"in h.item)&&"players"in y.item?-1:Math.abs(h.powerLevel-u)-Math.abs(y.powerLevel-u)}),v=0;for(let h=0;h=m){let h=g.sort((b,L)=>{let T=this.getItemSize(b.item);return this.getItemSize(L.item)-T}),y=[],w=new Set,M=0;for(let b of h){let L=this.getItemId(b.item),T=this.getItemSize(b.item);if(!w.has(L)&&M+T<=i&&(y.push(b),w.add(L),M+=T,M===i))break}if(M>=3){let b=y.map(I=>I.item);if(!this.isPodPowerSpreadValid(y,r))continue;let L=y.reduce((I,$)=>I+$.powerLevel,0)/y.length,T={players:b,power:Math.round(L*2)/2},S=new Set(o);for(let I of b){let $="players"in I?I.id:I.id.toString();S.add($),e.forEach(G=>{let ie="players"in G.item?G.item.id:G.item.id.toString();ie===$&&S.add(ie)})}this.backtrackVirtualPlayersWithLeniencyUnified(e,t,r,[...n,T],S,l,a)}}}this.backtrackVirtualPlayersWithLeniencyUnified(e,t,r,n,o,l,a)}isPodPowerSpreadValid(e,t){if(e.length===0)return!0;let r=e.map(a=>a.powerLevel),n=Math.min(...r);return Math.max(...r)-n<=t}findBestCommonPowerLevel(e){if(e.length===0)return null;let t=new Map;for(let o of e)for(let s of o.availablePowers)t.set(s,(t.get(s)||0)+1);if(t.size===0)return null;let r=e[0].availablePowers[0],n=0;for(let[o,s]of t.entries())s>n&&(n=s,r=o);return r}};var le=class{constructor(){this.pools=new Map;this.POOL_SIZE=15}get(e){let t=this.pools.get(e.toLowerCase())||[];if(t.length>0){let r=t.pop();return this.resetElement(r),r}return document.createElement(e)}release(e){let t=e.tagName.toLowerCase(),r=this.pools.get(t);r||(r=[],this.pools.set(t,r)),r.length{delete e.dataset[t]})}clear(){this.pools.clear()}getStats(){let e={};return this.pools.forEach((t,r)=>{e[r]=t.length}),e}preWarm(){[{tag:"div",count:8},{tag:"li",count:6},{tag:"ul",count:4},{tag:"h3",count:3},{tag:"p",count:3},{tag:"strong",count:3},{tag:"button",count:2}].forEach(({tag:t,count:r})=>{let n=[];for(let o=0;o + ${n} +

${e.title}

+ + +
+

${e.message}

+ ${s} + ${o} +
+ `,this.setupToastEventListeners(r,t),this.toastContainer.appendChild(r),this.activeToasts.add(r),requestAnimationFrame(()=>{r.classList.add("toast-show")}),e.duration&&e.duration>0&&setTimeout(()=>{this.hideToast(t)},e.duration)}async showConfirm(e){return this.modalContainer?new Promise(t=>{let r=`modal-${++this.toastCounter}`,n=document.createElement("div");n.id=r,n.className="modal-overlay";let o=e.icon||this.getIconForConfirmStyle(e.confirmStyle||"primary"),s=e.confirmText||"Confirm",a=e.cancelText||"Cancel",i=`btn btn-${e.confirmStyle||"primary"}`;n.innerHTML=` + + `;let l=n.querySelector(".modal-confirm"),d=n.querySelector(".modal-cancel"),p=n,u=()=>{this.hideModal(r),t(!0)},E=()=>{this.hideModal(r),t(!1)};l.addEventListener("click",u),d.addEventListener("click",E),p.addEventListener("click",g=>{g.target===p&&E()});let f=g=>{g.key==="Escape"?E():g.key==="Enter"&&u()};document.addEventListener("keydown",f);let P=()=>{document.removeEventListener("keydown",f)};n.addEventListener("modal-hidden",P,{once:!0}),this.modalContainer&&this.modalContainer.appendChild(n),requestAnimationFrame(()=>{n.classList.add("modal-show")})}):!1}hideToast(e){let t=document.getElementById(e);t&&this.activeToasts.has(t)&&(t.classList.add("toast-hide"),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),this.activeToasts.delete(t)},300))}hideModal(e){let t=document.getElementById(e);t&&(t.classList.add("modal-hide"),t.dispatchEvent(new CustomEvent("modal-hidden")),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t)},300))}setupToastEventListeners(e,t){let r=e.querySelector(".toast-close");r&&r.addEventListener("click",()=>{this.hideToast(t)}),e.querySelectorAll("[data-toast-action]").forEach(o=>{o.addEventListener("click",()=>{this.hideToast(t)})})}getIconForType(e){let t={error:"\u274C",warning:"\u26A0\uFE0F",success:"\u2705",info:"\u2139\uFE0F"};return t[e]||t.info}getIconForConfirmStyle(e){let t={danger:"\u26A0\uFE0F",warning:"\u26A0\uFE0F",primary:"\u2753"};return t[e]||t.primary}createActionsHtml(e,t){return!e||e.length===0?"":`
${e.map(n=>``).join("")}
`}createSuggestionsHtml(e){return` +
+
Problems:
+
    ${e.map(r=>`
  • ${r}
  • `).join("")}
+
+ `}clearAllToasts(){this.activeToasts.forEach(e=>{e.id&&this.hideToast(e.id)})}async clearErrorToasts(){let e=Array.from(this.activeToasts).filter(r=>r.classList.contains("toast-error"));if(e.length===0)return Promise.resolve();let t=e.map(r=>r.id?new Promise(n=>{let o=()=>{r.removeEventListener("transitionend",o),r.parentNode&&r.parentNode.removeChild(r),n()};r.addEventListener("transitionend",o),this.hideToast(r.id)}):Promise.resolve());await Promise.all(t),await new Promise(r=>setTimeout(r,50))}alert(e,t="Alert"){this.showToast({type:"info",title:t,message:e,duration:5e3})}async confirm(e,t="Confirm"){return this.showConfirm({title:t,message:e})}async showError(e,t,r){await this.clearErrorToasts(),this.showToast({type:"error",title:e,message:t,suggestions:r,duration:0})}showSuccess(e,t="Success"){this.showToast({type:"success",title:t,message:e,duration:3e3})}showWarning(e,t,r){this.showToast({type:"warning",title:e,message:t,suggestions:r,duration:0})}},H=ce.getInstance();var Se={E001:{title:"Player Name Required",message:"All players must have a name before generating pods.",suggestions:["Fill in the empty name field(s) highlighted in red","Use unique names for each player"]},E002:{title:"Duplicate Player Names",message:"Multiple players have the same name.",suggestions:["Change one of the highlighted duplicate names","Each player must have a unique name"]},E003:{title:"Power Level Selection Required",message:"Each player must have at least one power level selected.",suggestions:["Click the power level button for highlighted players","Use keyboard shortcuts: 7, 7-9, 6.5-8","Check at least one power level for each player"]},E004:{title:"Bracket Selection Required",message:"Each player must have at least one bracket selected.",suggestions:["Click the bracket button for highlighted players","Check at least one bracket level for each player","Switch to Power Level mode if preferred"]},E005:{title:"Not Enough Players",message:"You need at least 3 players to form a pod.",suggestions:['Add more players using the "Add Player" button','Use "Add 4 Players" for quick setup',"Remove unused empty player rows"]},E009:{title:"Validation Errors Found",message:"Please fix the highlighted errors before generating pods.",suggestions:["Check red highlighted fields for missing information","Ensure all names are unique","Verify power levels or brackets are selected"]},E010:{title:"Incompatible Power Levels",message:"Some players have power levels too far apart to form balanced pods.",suggestions:["Increase the leniency setting to allow wider power ranges","Adjust player power levels to be closer together","Consider grouping players manually to keep them together"]},E011:{title:"Incompatible Bracket Levels",message:"Some players have brackets with no overlap for balanced pods.",suggestions:["Select additional brackets for flexibility","Group incompatible players manually","Adjust bracket selections to have some overlap"]},E012:{title:"Group Configuration Issues",message:"Some groups have internal conflicts preventing pod assignment.",suggestions:["Check grouped players have compatible power/bracket levels","Consider splitting problematic groups","Adjust group member selections for better compatibility"]},E006:{title:"Pod Generation Failed",message:"Unable to create balanced pods with current settings.",suggestions:["Try enabling leniency for more flexible matching","Adjust player power levels or brackets","Reduce group sizes or ungroup some players"]},E007:{title:"Display Mode Error",message:"Unable to switch to display mode.",suggestions:["Generate pods first before using display mode","Refresh the page if issues persist"]},E008:{title:"Initialization Error",message:"Application failed to start properly.",suggestions:["Refresh the page","Clear browser cache","Check browser console for details"]}},k=class{static get(e){return Se[e]||{title:"Unknown Error",message:"An unexpected error occurred.",suggestions:["Try refreshing the page","Check browser console for details"]}}static getSimple(e,t){let r=this.get(e);return t?`${r.message}: ${t}`:r.message}static showEnhanced(e,t){let r=this.get(e);console.error(`[${e}] ${r.title}: ${r.message}`),H.showError(r.title,t?`${r.message} + +Details: ${t}`:r.message,r.suggestions)}static show(e,t){let r=this.get(e),n=t?`${r.message}: ${t}`:r.message;console.error(`[${e}] ${n}`),H.showError(r.title,n,r.suggestions)}static showSuccess(e){console.log(`\u2705 ${e}`),H.showSuccess(e)}};k.PLAYER_NAME_REQUIRED="E001",k.PLAYER_NAME_DUPLICATE="E002",k.POWER_LEVEL_REQUIRED="E003",k.BRACKET_LEVEL_REQUIRED="E004",k.INSUFFICIENT_PLAYERS="E005",k.GENERATION_FAILED="E006",k.DISPLAY_MODE_FAILED="E007",k.INITIALIZATION_FAILED="E008",k.VALIDATION_FAILED="E009",k.INCOMPATIBLE_POWER_LEVELS="E010",k.INCOMPATIBLE_BRACKETS="E011",k.GROUP_CONFLICTS="E012";var te=class{constructor(e,t,r,n,o){this.displayModeBtnBottom=null;this.outputSection=e,this.displayModeBtn=t,this.dragDropManager=r,this.enterDisplayModeCallback=n,this.updateResultsCardVisibilityCallback=o}createElement(e){return R.get(e)}cleanupBottomDisplayButton(){if(this.displayModeBtnBottom){let e=this.displayModeBtnBottom.parentNode;e&&e.parentNode&&e.parentNode.removeChild(e),this.displayModeBtnBottom=null}}renderPods(e,t=[],r,n){try{if(!Array.isArray(e))throw new Error("Invalid pods array provided to renderPods");if(!Array.isArray(t))throw new Error("Invalid unassignedPlayers array provided to renderPods");if(this.dragDropManager.setCurrentPods(r,n),this.cleanupBottomDisplayButton(),!this.outputSection)throw new Error("Output section not found - cannot render pods");if(this.outputSection.innerHTML="",this.updateResultsCardVisibilityCallback(),e.length===0){this.outputSection.textContent="Could not form pods with the given players.",this.displayModeBtn&&(this.displayModeBtn.style.display="none");return}this.displayModeBtn&&(this.displayModeBtn.style.display="inline-block"),this.renderPodsToDOM(e,t)}catch(o){console.error("Error in renderPods:",o),k.show(k.DISPLAY_MODE_FAILED,`Error: ${o instanceof Error?o.message:"Unknown error"}`),this.outputSection&&(this.outputSection.textContent="Error displaying pods. Please try again."),this.displayModeBtn&&(this.displayModeBtn.style.display="none")}}renderPodsToDOM(e,t){let r=Math.ceil(Math.sqrt(e.length)),n=document.createDocumentFragment(),o=this.createElement("div");if(o.classList.add("pods-container"),o.style.gridTemplateColumns=`repeat(${r}, 1fr)`,o.style.gridTemplateRows=`repeat(${r}, 1fr)`,e.forEach((a,i)=>{let l=this.createElement("div");l.classList.add("pod",`pod-color-${i%10}`),l.dataset.podIndex=i.toString(),l.addEventListener("dragover",this.dragDropManager.handleDragOver),l.addEventListener("drop",this.dragDropManager.handleDrop),l.addEventListener("dragleave",this.dragDropManager.handleDragLeave);let d=this.createElement("h3"),p=document.getElementById("bracket-radio");if(p&&p.checked){let f=this.calculateValidBracketRange(a);d.textContent=`Pod ${i+1} (Bracket: ${f})`}else{let f=J(a);d.textContent=`Pod ${i+1} (Power: ${f})`}l.appendChild(d);let E=this.createElement("ul");a.players.forEach((f,P)=>{if("players"in f){let g=this.createElement("li");g.classList.add("pod-group"),g.draggable=!0,g.dataset.itemType="group",g.dataset.itemId=f.id,g.dataset.podIndex=i.toString(),g.dataset.itemIndex=P.toString(),g.addEventListener("dragstart",this.dragDropManager.handleDragStart),g.addEventListener("dragend",this.dragDropManager.handleDragEnd);let v=document.getElementById("bracket-radio"),m=v&&v.checked,h=this.createElement("strong");m?h.textContent=`Group ${f.id.split("-")[1]}:`:h.textContent=`Group ${f.id.split("-")[1]} (Avg Power: ${f.averagePower}):`,g.appendChild(h);let y=this.createElement("ul");f.players.forEach(w=>{let M=this.createElement("li");if(m&&w.bracketRange)M.textContent=`${w.name} (B: ${w.bracketRange})`;else{let b=Y(a),L=j(w,b);M.innerHTML=`${w.name} (P: ${L})`}y.appendChild(M)}),g.appendChild(y),E.appendChild(g)}else{let g=this.createElement("li");g.classList.add("pod-player"),g.draggable=!0,g.dataset.itemType="player",g.dataset.itemId=f.id.toString(),g.dataset.podIndex=i.toString(),g.dataset.itemIndex=P.toString(),g.addEventListener("dragstart",this.dragDropManager.handleDragStart),g.addEventListener("dragend",this.dragDropManager.handleDragEnd);let v=document.getElementById("bracket-radio");if(v&&v.checked&&f.bracketRange)g.textContent=`${f.name} (B: ${f.bracketRange})`;else{let h=Y(a),y=j(f,h);g.innerHTML=`${f.name} (P: ${y})`}E.appendChild(g)}}),l.appendChild(E),o.appendChild(l)}),e.length>0){let a=this.createElement("div");a.classList.add("pod","new-pod","new-pod-target"),a.style.borderColor="#4CAF50",a.style.backgroundColor="#1f2a1f",a.style.borderStyle="dashed",a.dataset.podIndex="new-pod",a.addEventListener("dragover",this.dragDropManager.handleDragOver),a.addEventListener("drop",this.dragDropManager.handleDrop),a.addEventListener("dragleave",this.dragDropManager.handleDragLeave);let i=this.createElement("h3");i.textContent="Create New Pod",i.style.color="#4CAF50",a.appendChild(i);let l=this.createElement("p");l.textContent="Drag players or groups here to create a new pod",l.style.color="#999",l.style.fontStyle="italic",l.style.textAlign="center",l.style.margin="20px 0",a.appendChild(l),o.appendChild(a)}if(t.length>0){let a=this.createElement("div");a.classList.add("pod","unassigned-pod"),a.style.borderColor="#ff6b6b",a.style.backgroundColor="#2a1f1f",a.dataset.podIndex="unassigned",a.addEventListener("dragover",this.dragDropManager.handleDragOver),a.addEventListener("drop",this.dragDropManager.handleDrop),a.addEventListener("dragleave",this.dragDropManager.handleDragLeave);let i=this.createElement("h3");i.textContent="Unassigned Players",i.style.color="#ff6b6b",a.appendChild(i);let l=this.createElement("ul");t.forEach((d,p)=>{if("players"in d){let u=this.createElement("li");u.classList.add("pod-group"),u.draggable=!0,u.dataset.itemType="group",u.dataset.itemId=d.id,u.dataset.podIndex="unassigned",u.dataset.itemIndex=p.toString(),u.addEventListener("dragstart",this.dragDropManager.handleDragStart),u.addEventListener("dragend",this.dragDropManager.handleDragEnd);let E=document.getElementById("bracket-radio"),f=E&&E.checked;f?u.innerHTML=`Group ${d.id.split("-")[1]}:`:u.innerHTML=`Group ${d.id.split("-")[1]} (Avg Power: ${d.averagePower}):`;let P=this.createElement("ul");d.players.forEach(g=>{let v=this.createElement("li");f&&g.bracketRange?v.textContent=`${g.name} (B: ${g.bracketRange})`:v.textContent=`${g.name} (P: ${g.powerRange})`,P.appendChild(v)}),u.appendChild(P),l.appendChild(u)}else{let u=this.createElement("li");u.classList.add("pod-player"),u.draggable=!0,u.dataset.itemType="player",u.dataset.itemId=d.id.toString(),u.dataset.podIndex="unassigned",u.dataset.itemIndex=p.toString(),u.addEventListener("dragstart",this.dragDropManager.handleDragStart),u.addEventListener("dragend",this.dragDropManager.handleDragEnd);let E=document.getElementById("bracket-radio");E&&E.checked&&d.bracketRange?u.textContent=`${d.name} (B: ${d.bracketRange})`:u.textContent=`${d.name} (P: ${d.powerRange})`,l.appendChild(u)}}),a.appendChild(l),o.appendChild(a)}n.appendChild(o),this.outputSection.appendChild(n),this.updateResultsCardVisibilityCallback();let s=document.querySelector(".help-section");if(s&&s.parentNode){let a=this.createElement("div");a.style.textAlign="center",a.style.marginTop="20px",a.style.marginBottom="20px",this.displayModeBtnBottom=this.displayModeBtn.cloneNode(!0),this.displayModeBtnBottom.id="display-mode-btn-bottom",this.displayModeBtnBottom.style.display="inline-block",this.displayModeBtnBottom.addEventListener("click",async()=>await this.enterDisplayModeCallback()),a.appendChild(this.displayModeBtnBottom),s.parentNode.insertBefore(a,s)}}calculateValidBracketRange(e){let t=e.players.flatMap(s=>"players"in s?s.players:[s]);if(t.length===0)return"Unknown";let r=[],n=new Set;t.forEach(s=>{s.brackets&&s.brackets.forEach(a=>n.add(a))});for(let s of n)t.every(i=>i.brackets&&i.brackets.includes(s))&&r.push(s);let o=["1","2","3","4","cedh"];if(r.sort((s,a)=>o.indexOf(s)-o.indexOf(a)),r.length===0)return"Unknown";if(r.length===1)return r[0];{let s=r.filter(i=>i!=="cedh");return s.length>1&&s.every((i,l)=>{if(l===0)return!0;let d=parseInt(i),p=parseInt(s[l-1]);return d===p+1})&&s.length===r.length&&r.length>1?`${r[0]}-${r[r.length-1]}`:r.join(", ")}}};var re=class{constructor(e,t){this.draggedElement=null;this.draggedItemData=null;this.currentPods=[];this.currentUnassigned=[];this.handleDragStart=e=>{let t=e.target;this.draggedElement=t,t.classList.add("dragging"),this.draggedItemData={type:t.dataset.itemType,id:t.dataset.itemId,podIndex:t.dataset.podIndex,itemIndex:t.dataset.itemIndex},e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/html",t.outerHTML)};this.handleDragEnd=e=>{e.target.classList.remove("dragging"),this.draggedElement=null,this.draggedItemData=null};this.handleDragOver=e=>{e.preventDefault(),e.dataTransfer.dropEffect="move",e.currentTarget.classList.add("drag-over")};this.handleDragLeave=e=>{e.currentTarget.classList.remove("drag-over")};this.handleDrop=e=>{e.preventDefault();let t=e.currentTarget;if(t.classList.remove("drag-over"),!this.draggedItemData)return;let r=t.dataset.podIndex,n=this.draggedItemData.podIndex;r!==n&&this.moveItemBetweenPods(this.draggedItemData,r)};this.playerManager=e,this.onPodsChanged=t}setCurrentPods(e,t=[]){this.currentPods=[...e],this.currentUnassigned=[...t]}moveItemBetweenPods(e,t){let r=e.podIndex,n=parseInt(e.itemIndex),o=null;if(r==="unassigned")o=this.currentUnassigned[n],this.currentUnassigned.splice(n,1);else{let s=this.currentPods[parseInt(r)];o=s.players[n],s.players.splice(n,1),s.power=this.playerManager.calculatePodPower(s.players)}if(o){if(t==="unassigned")this.currentUnassigned.push(o);else if(t==="new-pod"){let s={players:[o],power:this.playerManager.calculatePodPower([o])};this.currentPods.push(s)}else{let s=this.currentPods[parseInt(t)];s.players.push(o),s.power=this.playerManager.calculatePodPower(s.players)}this.cleanupEmptyPods(),this.onPodsChanged(this.currentPods,this.currentUnassigned)}}cleanupEmptyPods(){this.currentPods=this.currentPods.filter(e=>e.players.length>0)}};var ne=class{constructor(){this.isDisplayMode=!1;this.handleKeyDown=null;this.borderColors=["#FF6B6B","#4ECDC4","#45B7D1","#FFA726","#66BB6A","#AB47BC","#EF5350","#26A69A","#42A5F5","#FF7043","#9CCC65","#7E57C2","#EC407A","#29B6F6","#FFCA28","#8BC34A","#673AB7","#F06292","#00BCD4","#FFEB3B","#795548","#607D8B","#E91E63","#009688","#FF9800"]}getShuffledColors(e){let t=[...this.borderColors];for(let r=t.length-1;r>0;r--){let n=Math.floor(Math.random()*(r+1));[t[r],t[n]]=[t[n],t[r]]}if(e>t.length){let r=[];for(let n=0;n"players"in s?s.players:[s]);if(t.length===0)return"Unknown";let r=[],n=new Set;t.forEach(s=>{s.brackets&&s.brackets.forEach(a=>n.add(a))});for(let s of n)t.every(i=>i.brackets&&i.brackets.includes(s))&&r.push(s);let o=["1","2","3","4","cedh"];if(r.sort((s,a)=>o.indexOf(s)-o.indexOf(a)),r.length===0)return"Unknown";if(r.length===1)return r[0];{let s=r.filter(i=>i!=="cedh");return s.length>1&&s.every((i,l)=>{if(l===0)return!0;let d=parseInt(i),p=parseInt(s[l-1]);return d===p+1})&&s.length===r.length&&r.length>1?`${r[0]}-${r[r.length-1]}`:r.join(", ")}}getValidBracketsArrayForPod(e){let t=e.players.flatMap(a=>"players"in a?a.players:[a]);if(t.length===0)return[];let r=new Map;if(t.forEach(a=>{a.brackets&&a.brackets.forEach(i=>{r.set(i,(r.get(i)||0)+1)})}),r.size===0)return[];let n=Math.ceil(t.length/2),o=[];for(let[a,i]of r.entries())i>=n&&o.push(a);let s=["1","2","3","4","cedh"];return o.sort((a,i)=>s.indexOf(a)-s.indexOf(i)),o}enterDisplayMode(e){if(e.length===0)return;this.isDisplayMode=!0,document.body.classList.add("display-mode");let t=Math.ceil(Math.sqrt(e.length)),r=R.get("div");r.className="display-mode-container",r.style.position="fixed",r.style.top="0",r.style.left="0",r.style.width="100vw",r.style.height="100vh",r.style.background="#1a1a1a",r.style.zIndex="1000",r.style.padding="20px",r.style.boxSizing="border-box",r.style.overflow="hidden",r.innerHTML=`

MTG Commander Pods

- `;let n=document.querySelector(".container");n&&(n.style.display="none"),document.body.appendChild(r);let o=r.querySelector("#display-output"),s=A.get("div");s.style.display="grid",s.style.gap="20px",s.style.height="100%",s.style.gridTemplateColumns=`repeat(${t}, 1fr)`,s.style.gridTemplateRows=`repeat(${t}, 1fr)`;let a=this.getShuffledColors(e.length);e.forEach((l,d)=>{let p=A.get("div");p.style.display="flex",p.style.flexDirection="column",p.style.background="#2a2a2a",p.style.border=`3px solid ${a[d]}`,p.style.borderRadius="8px",p.style.padding="15px",p.style.boxSizing="border-box",p.style.minHeight="0",p.style.boxShadow=`0 0 10px ${a[d]}40`,p.classList.add("pod",`pod-color-${d%10}`);let u=A.get("h3"),E=document.getElementById("bracket-radio"),f=E&&E.checked;if(f){let b=this.calculateValidBracketRange(l);u.textContent=`Pod ${d+1} (Bracket: ${b})`}else{let b=J(l);u.textContent=`Pod ${d+1} (Power: ${b})`}u.style.fontSize="1.6rem",u.style.margin="0 0 15px 0",u.style.textAlign="center",u.style.color=a[d],u.style.fontWeight="bold",u.style.flexShrink="0",u.style.textShadow="1px 1px 2px rgba(0,0,0,0.8)",p.appendChild(u);let P=0;l.players.forEach(b=>{"players"in b?P+=b.players.length:P+=1});let g="";l.players.forEach(b=>{if("players"in b)b.players.forEach(L=>{let T=f&&L.bracketRange?`${L.name} (B: ${L.bracketRange})`:`${L.name} (P: ${L.powerRange})`;T.length>g.length&&(g=T)});else{let L=f&&b.bracketRange?`${b.name} (B: ${b.bracketRange})`:`${b.name} (P: ${b.powerRange})`;L.length>g.length&&(g=L)}});let v=A.get("ul");v.style.flexGrow="1",v.style.display="flex";let m=Math.ceil(Math.sqrt(P)),h=Math.ceil(P/m);v.style.display="grid",v.style.gridTemplateColumns=`repeat(${m}, 1fr)`,v.style.gridTemplateRows=`repeat(${h}, 1fr)`,v.style.gap="12px",v.style.margin="0",v.style.padding="0",v.style.listStyle="none",v.style.width="100%",v.style.height="100%",v.style.alignItems="stretch",v.style.justifyItems="stretch";let y=[];l.players.forEach(b=>{"players"in b?b.players.forEach(L=>y.push(L)):y.push(b)});let w=document.getElementById("bracket-radio"),k=w&&w.checked;y.forEach((b,L)=>{let T=A.get("li"),S=A.get("div");S.textContent=b.name,S.className="player-name";let I=A.get("div");if(k&&b.bracketRange){let $=this.getValidBracketsArrayForPod(l),G=Ee(b,$);I.innerHTML=`B: ${G}`}else{let $=Y(l),G=j(b,$);I.innerHTML=`P: ${G}`}I.className="player-power",T.appendChild(S),T.appendChild(I),T.style.display="flex",T.style.flexDirection="column",T.style.justifyContent="center",T.style.alignItems="center",T.style.backgroundColor="rgba(255, 255, 255, 0.12)",T.style.border="2px solid rgba(255, 255, 255, 0.2)",T.style.borderRadius="12px",T.style.padding="8px",T.style.boxSizing="border-box",T.style.textAlign="center",T.style.height="100%",S.style.color="#ffffff",S.style.fontWeight="bold",S.style.lineHeight="1.1",S.style.marginBottom="4px",S.style.wordBreak="break-word",S.style.hyphens="auto",S.style.flexGrow="1",S.style.display="flex",S.style.alignItems="center",S.style.justifyContent="center",I.style.color="#b0b0b0",I.style.fontWeight="500",I.style.lineHeight="1",I.style.opacity="0.9",T.dataset.podRef=d.toString(),T.classList.add("dynamic-font-item"),v.appendChild(T)}),p.appendChild(v),s.appendChild(p)}),o.appendChild(s),requestAnimationFrame(()=>{s.querySelectorAll(".pod").forEach((d,p)=>{let u=d.getBoundingClientRect(),E=u.width,f=u.height,P=0;e[p].players.forEach(m=>{"players"in m?P+=m.players.length:P+=1});let g=this.calculateFontSizeForPod(E,f,P);d.querySelectorAll(".dynamic-font-item").forEach(m=>{let h=m.querySelector(".player-name"),y=m.querySelector(".player-power");if(h&&(h.style.fontSize=g),y){let w=Math.round(parseInt(g)*.75);y.style.fontSize=`${w}px`}})})}),r.querySelector("#exit-display-btn").addEventListener("click",()=>this.exitDisplayMode()),this.handleKeyDown=l=>{l.key==="Escape"&&this.isDisplayMode&&this.exitDisplayMode()},document.addEventListener("keydown",this.handleKeyDown)}exitDisplayMode(){this.isDisplayMode=!1,document.body.classList.remove("display-mode");let e=document.querySelector(".container");e&&(e.style.display="");let t=document.querySelector(".display-mode-container");t&&t.remove(),this.handleKeyDown&&(document.removeEventListener("keydown",this.handleKeyDown),this.handleKeyDown=null)}getIsDisplayMode(){return this.isDisplayMode}};var ne=class{constructor(){this.currentStep=0;this.tourSteps=[];this.tourOverlay=null;this.tourHighlight=null;this.tourTooltip=null;this.isActive=!1;this.originalScrollPosition=0;this.handleTourKeydown=e=>{if(this.isActive)switch(e.key){case"Escape":e.preventDefault(),e.stopPropagation(),this.endTour().catch(console.error);break;case"ArrowRight":case"Enter":e.preventDefault(),e.stopPropagation(),this.currentStep>=this.tourSteps.length-1?this.endTour().catch(console.error):this.nextStep().catch(console.error);break;case"ArrowLeft":e.preventDefault(),e.stopPropagation(),this.previousStep().catch(console.error);break}};this.initializeTourSteps()}initializeTourSteps(){this.tourSteps=[{id:"welcome",title:"\u{1F3AF} Welcome to Commander Pod Generator!",content:"This interactive tour will guide you through all the features step by step. You can exit at any time by pressing Escape or clicking the \u2715 Exit Tour button.",target:".container",position:"bottom",action:"none"},{id:"settings-button",title:"\u2699\uFE0F Settings Button",content:"This gear icon opens the settings panel where you can configure your ranking system (Power Level vs Bracket), manage players, and access help resources. Click it to access all configuration options.",target:"#settings-toggle",position:"bottom",action:"none"},{id:"ranking-system",title:"\u2699\uFE0F Choose Your Ranking System",content:"First, choose between Power Level (1-10 scale) or Bracket (1,2,3,4,cEDH) system. Power Level gives more granular control, while Brackets are simpler and tournament-friendly.",target:"fieldset:first-of-type",position:"bottom",action:"none",beforeStep:()=>this.openSettingsForTour(),afterStep:()=>this.closeSettingsAfterTour()},{id:"add-players",title:"\u{1F465} Adding Players",content:'Player names are entered here. The "Add Player" button and keyboard shortcut Ctrl+Enter are available for quickly adding more players when you use the app.',target:".player-row:first-child .player-name",position:"right",action:"type",actionData:"Alice",beforeStep:()=>this.ensurePlayerRows(1)},{id:"power-levels",title:"\u26A1 Setting Power Levels",content:'This button opens the power level selector. Individual levels or ranges can be selected, and typing shortcuts like "7-8" are supported for quick range selection.',target:".player-row:first-child .power-selector-btn",position:"left",action:"click",beforeStep:()=>this.ensurePowerMode()},{id:"power-selection",title:"\u{1F3AF} Power Level Selection",content:`Multiple power levels can be selected for each player. The quick range buttons (6-7, 7-8, 8-9) make common selections easy. We'll now select "7-8" for a medium power deck.`,target:".player-row:first-child .power-selector-dropdown",position:"right",action:"none",beforeStep:()=>{let e=document.querySelector(".player-row:first-child .power-selector-btn");e&&e.click(),setTimeout(()=>{let t=document.querySelector('.player-row:first-child .range-btn[data-range="7-8"]');t&&t.click()},200)}},{id:"add-more-players",title:"\u{1F680} Quick Player Addition",content:`The "Add 4 Players" button enables bulk addition, and Ctrl+Enter can be pressed repeatedly for individual players. We'll add more players for our demonstration.`,target:"#bulk-add-btn",position:"bottom",action:"click"},{id:"fill-players",title:"\u{1F4DD} Complete Player Information",content:"The remaining players will be filled with names and power levels. The tour will automatically provide example data to demonstrate the features.",target:".player-row:nth-child(2) .player-name",position:"right",action:"none",beforeStep:()=>this.fillExamplePlayers()},{id:"groups",title:"\u{1F46B} Creating Groups",content:'This dropdown allows grouping players who want to play together. "Start a New Group" creates a group, then other players can "Join Group" to join them.',target:".player-row:first-child .group-select",position:"left",action:"none"},{id:"group-demo",title:"\u{1F465} Group Creation Demo",content:"Now we'll create a group! Alice and Henry will be grouped together to demonstrate how the system works with compatible power levels.",target:".player-row:first-child .group-select",position:"left",action:"none",beforeStep:()=>this.createGroupDemo()},{id:"tolerance",title:"\u{1F39A}\uFE0F Power Level Tolerance",content:'In Power Level mode, tolerance can be adjusted. "No Leniency" requires exact matches, while "Regular" and "Super" leniency allow \xB10.5 and \xB11.0 differences respectively.',target:"fieldset:nth-of-type(2)",position:"top",action:"none",beforeStep:()=>{this.ensurePowerMode(),this.openSettingsForTour()},afterStep:()=>this.closeSettingsAfterTour()},{id:"pod-size-preference",title:"\u{1F4CF} Pod Size Preference",content:'Pod size preference determines how pods are organized. "Balanced" allows 3-5 player pods for flexibility, while "Avoid Large Pods" prefers smaller 3-4 player pods for more intimate games.',target:"fieldset:nth-of-type(3)",position:"top",action:"none",beforeStep:()=>this.openSettingsForTour(),afterStep:()=>this.closeSettingsAfterTour()},{id:"generate",title:"\u{1F3B2} Generate Pods",content:"Once all players have names and power levels, this button generates balanced pods. The algorithm creates 3-4 player pods with similar power levels.",target:"#generate-pods-btn",position:"top",action:"click"},{id:"results",title:"\u{1F3C6} Pod Results",content:"Here are the generated pods! Players are grouped by compatible power levels. Players can be moved between pods using drag and drop if needed.",target:"#output-section",position:"top",action:"none"},{id:"unassigned-players",title:"\u26A0\uFE0F Unassigned Players",content:`If players can't be balanced into pods (due to power level mismatches or odd numbers), they'll appear as "unassigned." They can be manually dragged into existing pods.`,target:"#output-section",position:"top",action:"none"},{id:"drag-drop",title:"\u{1F5B1}\uFE0F Drag and Drop",content:"Pods can be reorganized by dragging players between them. This is useful for manual adjustments or accommodating player preferences after initial pod generation.",target:"#output-section",position:"top",action:"none"},{id:"display-mode",title:"\u{1F4FA} Display Mode",content:"This button enters Display Mode - a clean, full-screen view perfect for showing pods to players on a projector or large screen.",target:"#display-mode-btn",position:"bottom",action:"click"},{id:"display-features",title:"\u{1F3A8} Display Mode Features",content:"In Display Mode, pod titles show power level ranges, player names are clearly displayed, and automatic font scaling ensures readability. All editing controls are hidden for a clean presentation view.",target:".display-mode-container",position:"top",action:"none"},{id:"exit-display",title:"\u{1F6AA} Exit Display Mode",content:"This button exits Display Mode and returns to the main interface where changes can be made.",target:"#exit-display-btn",position:"bottom",action:"click"},{id:"reset",title:"\u{1F504} Reset and Undo",content:"The Reset All button clears everything. It includes a smart confirmation system and an undo feature that lasts 30 seconds - so experimentation is safe!",target:"#reset-all-btn",position:"top",action:"none"},{id:"keyboard-shortcuts",title:"\u2328\uFE0F Keyboard Shortcuts",content:'Pro tip: Ctrl+Enter adds players quickly, power ranges like "7-8" can be typed in selector buttons, and Escape closes any dropdown. The help contains the full list of shortcuts!',target:"#help-btn",position:"left",action:"none"},{id:"support-donation",title:"\u{1F49D} Support This Project",content:"If you find this tool helpful for organizing your Commander games, please consider supporting its development! Your donations help keep this tool free, ad-free, and continuously improved for the entire Magic: The Gathering community. Every contribution, no matter how small, is greatly appreciated!",target:'div[id*="kofi-widget-overlay"], [class*="floatingchat-donate"], img[class*="kofiImg"]',position:"top",action:"none"},{id:"complete",title:"\u{1F389} Tour Complete!",content:"Congratulations! You now know all the main features. The Help button contains detailed information about keyboard shortcuts and advanced features. Happy pod organizing!",target:"#help-btn",position:"left",action:"none"}]}async startTour(){this.isActive||(this.isActive=!0,this.currentStep=0,this.originalScrollPosition=window.scrollY,this.createTourUI(),await this.showStep(0),this.setupTourEventListeners())}async endTour(){if(!this.isActive)return;this.isActive=!1,this.tourOverlay&&this.tourOverlay.classList.add("tour-ending"),this.tourHighlight&&this.tourHighlight.classList.add("tour-ending"),this.tourTooltip&&this.tourTooltip.classList.add("tour-ending");let e=document.querySelector(".tour-progress");if(e&&e.classList.add("tour-ending"),this.removeEventListeners(),document.body.classList.contains("display-mode")){let r=document.getElementById("exit-display-btn");r&&(r.click(),await this.waitForCondition(()=>!document.body.classList.contains("display-mode"),2e3))}setTimeout(()=>{this.removeTourUI(),this.cleanupRemainingElements()},50);let t=document.getElementById("reset-all-btn");t&&(t.click(),setTimeout(async()=>{let r=document.querySelector(".modal-confirm");r&&r.click()},50)),window.scrollTo(0,this.originalScrollPosition)}async forceEndTour(){if(this.isActive=!1,document.body.classList.contains("display-mode")){let t=document.getElementById("exit-display-btn");t&&(t.click(),await this.waitForCondition(()=>!document.body.classList.contains("display-mode"),2e3))}this.removeTourUI(),this.cleanupRemainingElements();let e=document.getElementById("reset-all-btn");e&&(e.click(),setTimeout(async()=>{let t=document.querySelector(".modal-confirm");t&&t.click()},50)),window.scrollTo(0,this.originalScrollPosition)}createTourUI(){this.tourOverlay=document.createElement("div"),this.tourOverlay.className="tour-overlay",this.tourOverlay.innerHTML=` + `;let n=document.querySelector(".container");n&&(n.style.display="none"),document.body.appendChild(r);let o=r.querySelector("#display-output"),s=R.get("div");s.style.display="grid",s.style.gap="20px",s.style.height="100%",s.style.gridTemplateColumns=`repeat(${t}, 1fr)`,s.style.gridTemplateRows=`repeat(${t}, 1fr)`;let a=this.getShuffledColors(e.length);e.forEach((l,d)=>{let p=R.get("div");p.style.display="flex",p.style.flexDirection="column",p.style.background="#2a2a2a",p.style.border=`3px solid ${a[d]}`,p.style.borderRadius="8px",p.style.padding="15px",p.style.boxSizing="border-box",p.style.minHeight="0",p.style.boxShadow=`0 0 10px ${a[d]}40`,p.classList.add("pod",`pod-color-${d%10}`);let u=R.get("h3"),E=document.getElementById("bracket-radio"),f=E&&E.checked;if(f){let b=this.calculateValidBracketRange(l);u.textContent=`Pod ${d+1} (Bracket: ${b})`}else{let b=J(l);u.textContent=`Pod ${d+1} (Power: ${b})`}u.style.fontSize="1.6rem",u.style.margin="0 0 15px 0",u.style.textAlign="center",u.style.color=a[d],u.style.fontWeight="bold",u.style.flexShrink="0",u.style.textShadow="1px 1px 2px rgba(0,0,0,0.8)",p.appendChild(u);let P=0;l.players.forEach(b=>{"players"in b?P+=b.players.length:P+=1});let g="";l.players.forEach(b=>{if("players"in b)b.players.forEach(L=>{let T=f&&L.bracketRange?`${L.name} (B: ${L.bracketRange})`:`${L.name} (P: ${L.powerRange})`;T.length>g.length&&(g=T)});else{let L=f&&b.bracketRange?`${b.name} (B: ${b.bracketRange})`:`${b.name} (P: ${b.powerRange})`;L.length>g.length&&(g=L)}});let v=R.get("ul");v.style.flexGrow="1",v.style.display="flex";let m=Math.ceil(Math.sqrt(P)),h=Math.ceil(P/m);v.style.display="grid",v.style.gridTemplateColumns=`repeat(${m}, 1fr)`,v.style.gridTemplateRows=`repeat(${h}, 1fr)`,v.style.gap="12px",v.style.margin="0",v.style.padding="0",v.style.listStyle="none",v.style.width="100%",v.style.height="100%",v.style.alignItems="stretch",v.style.justifyItems="stretch";let y=[];l.players.forEach(b=>{"players"in b?b.players.forEach(L=>y.push(L)):y.push(b)});let w=document.getElementById("bracket-radio"),M=w&&w.checked;y.forEach((b,L)=>{let T=R.get("li"),S=R.get("div");S.textContent=b.name,S.className="player-name";let I=R.get("div");if(M&&b.bracketRange){let $=this.getValidBracketsArrayForPod(l),G=we(b,$);I.innerHTML=`B: ${G}`}else{let $=Y(l),G=j(b,$);I.innerHTML=`P: ${G}`}I.className="player-power",T.appendChild(S),T.appendChild(I),T.style.display="flex",T.style.flexDirection="column",T.style.justifyContent="center",T.style.alignItems="center",T.style.backgroundColor="rgba(255, 255, 255, 0.12)",T.style.border="2px solid rgba(255, 255, 255, 0.2)",T.style.borderRadius="12px",T.style.padding="8px",T.style.boxSizing="border-box",T.style.textAlign="center",T.style.height="100%",S.style.color="#ffffff",S.style.fontWeight="bold",S.style.lineHeight="1.1",S.style.marginBottom="4px",S.style.wordBreak="break-word",S.style.hyphens="auto",S.style.flexGrow="1",S.style.display="flex",S.style.alignItems="center",S.style.justifyContent="center",I.style.color="#b0b0b0",I.style.fontWeight="500",I.style.lineHeight="1",I.style.opacity="0.9",T.dataset.podRef=d.toString(),T.classList.add("dynamic-font-item"),v.appendChild(T)}),p.appendChild(v),s.appendChild(p)}),o.appendChild(s),requestAnimationFrame(()=>{s.querySelectorAll(".pod").forEach((d,p)=>{let u=d.getBoundingClientRect(),E=u.width,f=u.height,P=0;e[p].players.forEach(m=>{"players"in m?P+=m.players.length:P+=1});let g=this.calculateFontSizeForPod(E,f,P);d.querySelectorAll(".dynamic-font-item").forEach(m=>{let h=m.querySelector(".player-name"),y=m.querySelector(".player-power");if(h&&(h.style.fontSize=g),y){let w=Math.round(parseInt(g)*.75);y.style.fontSize=`${w}px`}})})}),r.querySelector("#exit-display-btn").addEventListener("click",()=>this.exitDisplayMode()),this.handleKeyDown=l=>{l.key==="Escape"&&this.isDisplayMode&&this.exitDisplayMode()},document.addEventListener("keydown",this.handleKeyDown)}exitDisplayMode(){this.isDisplayMode=!1,document.body.classList.remove("display-mode");let e=document.querySelector(".container");e&&(e.style.display="");let t=document.querySelector(".display-mode-container");t&&t.remove(),this.handleKeyDown&&(document.removeEventListener("keydown",this.handleKeyDown),this.handleKeyDown=null)}getIsDisplayMode(){return this.isDisplayMode}};var oe=class{constructor(){this.currentStep=0;this.tourSteps=[];this.tourOverlay=null;this.tourHighlight=null;this.tourTooltip=null;this.isActive=!1;this.originalScrollPosition=0;this.handleTourKeydown=e=>{if(this.isActive)switch(e.key){case"Escape":e.preventDefault(),e.stopPropagation(),this.endTour().catch(console.error);break;case"ArrowRight":case"Enter":e.preventDefault(),e.stopPropagation(),this.currentStep>=this.tourSteps.length-1?this.endTour().catch(console.error):this.nextStep().catch(console.error);break;case"ArrowLeft":e.preventDefault(),e.stopPropagation(),this.previousStep().catch(console.error);break}};this.initializeTourSteps()}initializeTourSteps(){this.tourSteps=[{id:"welcome",title:"\u{1F3AF} Welcome to Commander Pod Generator!",content:"This interactive tour will guide you through all the features step by step. You can exit at any time by pressing Escape or clicking the \u2715 Exit Tour button.",target:".container",position:"bottom",action:"none"},{id:"settings-button",title:"\u2699\uFE0F Settings Button",content:"This gear icon opens the settings panel where you can configure your ranking system (Power Level vs Bracket), manage players, and access help resources. Click it to access all configuration options.",target:"#settings-toggle",position:"bottom",action:"none"},{id:"ranking-system",title:"\u2699\uFE0F Choose Your Ranking System",content:"First, choose between Power Level (1-10 scale) or Bracket (1,2,3,4,cEDH) system. Power Level gives more granular control, while Brackets are simpler and tournament-friendly.",target:"fieldset:first-of-type",position:"bottom",action:"none",beforeStep:()=>this.openSettingsForTour(),afterStep:()=>this.closeSettingsAfterTour()},{id:"add-players",title:"\u{1F465} Adding Players",content:'Player names are entered here. The "Add Player" button and keyboard shortcut Ctrl+Enter are available for quickly adding more players when you use the app.',target:".player-row:first-child .player-name",position:"right",action:"type",actionData:"Alice",beforeStep:()=>this.ensurePlayerRows(1)},{id:"power-levels",title:"\u26A1 Setting Power Levels",content:'This button opens the power level selector. Individual levels or ranges can be selected, and typing shortcuts like "7-8" are supported for quick range selection.',target:".player-row:first-child .power-selector-btn",position:"left",action:"click",beforeStep:()=>this.ensurePowerMode()},{id:"power-selection",title:"\u{1F3AF} Power Level Selection",content:`Multiple power levels can be selected for each player. The quick range buttons (6-7, 7-8, 8-9) make common selections easy. We'll now select "7-8" for a medium power deck.`,target:".player-row:first-child .power-selector-dropdown",position:"right",action:"none",beforeStep:()=>{let e=document.querySelector(".player-row:first-child .power-selector-btn");e&&e.click(),setTimeout(()=>{let t=document.querySelector('.player-row:first-child .range-btn[data-range="7-8"]');t&&t.click()},200)}},{id:"add-more-players",title:"\u{1F680} Quick Player Addition",content:`The "Add 4 Players" button enables bulk addition, and Ctrl+Enter can be pressed repeatedly for individual players. We'll add more players for our demonstration.`,target:"#bulk-add-btn",position:"bottom",action:"click"},{id:"fill-players",title:"\u{1F4DD} Complete Player Information",content:"The remaining players will be filled with names and power levels. The tour will automatically provide example data to demonstrate the features.",target:".player-row:nth-child(2) .player-name",position:"right",action:"none",beforeStep:()=>this.fillExamplePlayers()},{id:"groups",title:"\u{1F46B} Creating Groups",content:'This dropdown allows grouping players who want to play together. "Start a New Group" creates a group, then other players can "Join Group" to join them.',target:".player-row:first-child .group-select",position:"left",action:"none"},{id:"group-demo",title:"\u{1F465} Group Creation Demo",content:"Now we'll create a group! Alice and Henry will be grouped together to demonstrate how the system works with compatible power levels.",target:".player-row:first-child .group-select",position:"left",action:"none",beforeStep:()=>this.createGroupDemo()},{id:"tolerance",title:"\u{1F39A}\uFE0F Power Level Tolerance",content:'In Power Level mode, tolerance can be adjusted. "No Leniency" requires exact matches, while "Regular" and "Super" leniency allow \xB10.5 and \xB11.0 differences respectively.',target:"fieldset:nth-of-type(2)",position:"top",action:"none",beforeStep:()=>{this.ensurePowerMode(),this.openSettingsForTour()},afterStep:()=>this.closeSettingsAfterTour()},{id:"pod-size-preference",title:"\u{1F4CF} Pod Size Preference",content:'Pod size preference determines how pods are organized. "Balanced" allows 3-5 player pods for flexibility, while "Avoid Large Pods" prefers smaller 3-4 player pods for more intimate games.',target:"fieldset:nth-of-type(3)",position:"top",action:"none",beforeStep:()=>this.openSettingsForTour(),afterStep:()=>this.closeSettingsAfterTour()},{id:"generate",title:"\u{1F3B2} Generate Pods",content:"Once all players have names and power levels, this button generates balanced pods. The algorithm creates 3-4 player pods with similar power levels.",target:"#generate-pods-btn",position:"top",action:"click"},{id:"results",title:"\u{1F3C6} Pod Results",content:"Here are the generated pods! Players are grouped by compatible power levels. Players can be moved between pods using drag and drop if needed.",target:"#output-section",position:"top",action:"none"},{id:"unassigned-players",title:"\u26A0\uFE0F Unassigned Players",content:`If players can't be balanced into pods (due to power level mismatches or odd numbers), they'll appear as "unassigned." They can be manually dragged into existing pods.`,target:"#output-section",position:"top",action:"none"},{id:"drag-drop",title:"\u{1F5B1}\uFE0F Drag and Drop",content:"Pods can be reorganized by dragging players between them. This is useful for manual adjustments or accommodating player preferences after initial pod generation.",target:"#output-section",position:"top",action:"none"},{id:"display-mode",title:"\u{1F4FA} Display Mode",content:"This button enters Display Mode - a clean, full-screen view perfect for showing pods to players on a projector or large screen.",target:"#display-mode-btn",position:"bottom",action:"click"},{id:"display-features",title:"\u{1F3A8} Display Mode Features",content:"In Display Mode, pod titles show power level ranges, player names are clearly displayed, and automatic font scaling ensures readability. All editing controls are hidden for a clean presentation view.",target:".display-mode-container",position:"top",action:"none"},{id:"exit-display",title:"\u{1F6AA} Exit Display Mode",content:"This button exits Display Mode and returns to the main interface where changes can be made.",target:"#exit-display-btn",position:"bottom",action:"click"},{id:"reset",title:"\u{1F504} Reset and Undo",content:"The Reset All button clears everything. It includes a smart confirmation system and an undo feature that lasts 30 seconds - so experimentation is safe!",target:"#reset-all-btn",position:"top",action:"none"},{id:"keyboard-shortcuts",title:"\u2328\uFE0F Keyboard Shortcuts",content:'Pro tip: Ctrl+Enter adds players quickly, power ranges like "7-8" can be typed in selector buttons, and Escape closes any dropdown. The help contains the full list of shortcuts!',target:"#help-btn",position:"left",action:"none"},{id:"support-donation",title:"\u{1F49D} Support This Project",content:"If you find this tool helpful for organizing your Commander games, please consider supporting its development! Your donations help keep this tool free, ad-free, and continuously improved for the entire Magic: The Gathering community. Every contribution, no matter how small, is greatly appreciated!",target:'div[id*="kofi-widget-overlay"], [class*="floatingchat-donate"], img[class*="kofiImg"]',position:"top",action:"none"},{id:"complete",title:"\u{1F389} Tour Complete!",content:"Congratulations! You now know all the main features. The Help button contains detailed information about keyboard shortcuts and advanced features. Happy pod organizing!",target:"#help-btn",position:"left",action:"none"}]}async startTour(){this.isActive||(this.isActive=!0,this.currentStep=0,this.originalScrollPosition=window.scrollY,this.createTourUI(),await this.showStep(0),this.setupTourEventListeners())}async endTour(){if(!this.isActive)return;this.isActive=!1,this.tourOverlay&&this.tourOverlay.classList.add("tour-ending"),this.tourHighlight&&this.tourHighlight.classList.add("tour-ending"),this.tourTooltip&&this.tourTooltip.classList.add("tour-ending");let e=document.querySelector(".tour-progress");if(e&&e.classList.add("tour-ending"),this.removeEventListeners(),document.body.classList.contains("display-mode")){let r=document.getElementById("exit-display-btn");r&&(r.click(),await this.waitForCondition(()=>!document.body.classList.contains("display-mode"),2e3))}setTimeout(()=>{this.removeTourUI(),this.cleanupRemainingElements()},50);let t=document.getElementById("reset-all-btn");t&&(t.click(),setTimeout(async()=>{let r=document.querySelector(".modal-confirm");r&&r.click()},50)),window.scrollTo(0,this.originalScrollPosition)}async forceEndTour(){if(this.isActive=!1,document.body.classList.contains("display-mode")){let t=document.getElementById("exit-display-btn");t&&(t.click(),await this.waitForCondition(()=>!document.body.classList.contains("display-mode"),2e3))}this.removeTourUI(),this.cleanupRemainingElements();let e=document.getElementById("reset-all-btn");e&&(e.click(),setTimeout(async()=>{let t=document.querySelector(".modal-confirm");t&&t.click()},50)),window.scrollTo(0,this.originalScrollPosition)}createTourUI(){this.tourOverlay=document.createElement("div"),this.tourOverlay.className="tour-overlay",this.tourOverlay.innerHTML=`