");
const teamElement = soccerTactics.querySelector("Team");
const posElements = Array.from(soccerTactics.querySelectorAll("Pos"));
const subElements = Array.from(soccerTactics.querySelectorAll("Sub"));
const ruleElements = Array.from(soccerTactics.querySelectorAll("TacticRule"));
const data = {
initialCoords: [],
alt1Coords: [],
alt2Coords: [],
teamSettings: {},
substitutes: [],
tacticRules: [],
originalPlayerIDs: new Set(),
description: ''
};
data.teamSettings = {
passingStyle: getAttr(teamElement, 'tactics', 'shortpass'),
mentality: getAttr(teamElement, 'playstyle', 'normal'),
aggression: getAttr(teamElement, 'aggression', 'normal'),
captainPID: getAttr(teamElement, 'captain', '0')
};
if (data.teamSettings.captainPID !== '0') data.originalPlayerIDs.add(data.teamSettings.captainPID);
posElements.forEach(el => {
const pid = getAttr(el, 'pid');
const posType = getAttr(el, 'pos');
if (!pid) return;
data.originalPlayerIDs.add(pid);
if (posType === 'normal' || posType === 'goalie') {
const x = parseInt(getAttr(el, 'x', 0));
const y = parseInt(getAttr(el, 'y', 0));
const x1 = parseInt(getAttr(el, 'x1', x));
const y1 = parseInt(getAttr(el, 'y1', y));
const x2 = parseInt(getAttr(el, 'x2', x1));
const y2 = parseInt(getAttr(el, 'y2', y1));
data.initialCoords.push({
pid: pid,
pos: posType,
x: x,
y: y
});
data.alt1Coords.push({
pid: pid,
pos: posType,
x: x1,
y: y1
});
data.alt2Coords.push({
pid: pid,
pos: posType,
x: x2,
y: y2
});
}
});
subElements.forEach(el => {
const pid = getAttr(el, 'pid');
const posType = getAttr(el, 'pos');
const x = parseInt(getAttr(el, 'x', 0));
const y = parseInt(getAttr(el, 'y', 0));
if (pid) {
data.originalPlayerIDs.add(pid);
data.substitutes.push({
pid: pid,
pos: posType,
x: x,
y: y
});
}
});
ruleElements.forEach(el => {
const rule = {};
for (const attr of el.attributes) {
rule[attr.name] = attr.value;
if (attr.name === 'out_player' && attr.value !== 'no_change' && attr.value !== '0') data.originalPlayerIDs.add(attr.value);
if (attr.name === 'in_player_id' && attr.value !== 'NULL' && attr.value !== '0') data.originalPlayerIDs.add(attr.value);
}
data.tacticRules.push(rule);
});
data.originalPlayerIDs = Array.from(data.originalPlayerIDs);
return data;
}
function generateCompleteTacticXml(tacticData, playerMapping) {
let xml = `\n\n`;
const mappedCaptain = playerMapping[tacticData.teamSettings.captainPID] || '0';
xml += `\t\n`;
const playerCoords = {};
tacticData.initialCoords.forEach(p => {
if (!playerCoords[p.pid]) {
playerCoords[p.pid] = {
pos: p.pos
};
playerCoords[p.pid].initial = {
x: p.x,
y: p.y
};
}
});
tacticData.alt1Coords.forEach(p => {
if (!playerCoords[p.pid]) return;
playerCoords[p.pid].alt1 = {
x: p.x,
y: p.y
};
});
tacticData.alt2Coords.forEach(p => {
if (!playerCoords[p.pid]) return;
playerCoords[p.pid].alt2 = {
x: p.x,
y: p.y
};
});
for (const originalPid in playerCoords) {
const mappedPid = playerMapping[originalPid];
if (!mappedPid) continue;
const playerData = playerCoords[originalPid];
const initial = playerData.initial || {
x: 0,
y: 0
};
const alt1 = playerData.alt1 || initial;
const alt2 = playerData.alt2 || alt1;
xml += `\t\n`;
}
tacticData.substitutes.forEach(s => {
const mappedPid = playerMapping[s.pid];
if (mappedPid) xml += `\t\n`;
});
tacticData.tacticRules.forEach(rule => {
const mappedOutPlayer = (rule.out_player && rule.out_player !== 'no_change') ? (playerMapping[rule.out_player] || 'no_change') : 'no_change';
const mappedInPlayer = (rule.in_player_id && rule.in_player_id !== 'NULL') ? (playerMapping[rule.in_player_id] || 'NULL') : 'NULL';
let includeRule = true;
if (rule.out_player && rule.out_player !== 'no_change' && mappedOutPlayer === 'no_change') includeRule = false;
if (rule.in_player_id && rule.in_player_id !== 'NULL' && mappedInPlayer === 'NULL') includeRule = false;
if (includeRule) {
xml += '\t\n';
}
});
xml += '';
return xml;
}
async function saveCompleteTactic() {
const exportButton = document.getElementById('export_button');
const importExportWindow = document.getElementById('importExportTacticsWindow');
const playerInfoWindow = document.getElementById('playerInfoWindow');
const importExportData = document.getElementById('importExportData');
if (!exportButton || !importExportWindow || !playerInfoWindow || !importExportData) return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, 'Could not find required MZ UI elements for export.');
const windowHidden = importExportWindow.style.display === 'none';
if (windowHidden) {
const toggleButton = document.getElementById('import_export_button');
if (toggleButton) toggleButton.click();
else return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, 'Could not find button to toggle XML view.');
}
importExportData.value = '';
exportButton.click();
await new Promise(r => setTimeout(r, 200));
const xmlString = importExportData.value;
if (!xmlString) {
if (windowHidden) document.getElementById('close_button')?.click();
return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, 'Export did not produce XML.');
}
let savedData;
try {
savedData = parseCompleteTacticXml(xmlString);
} catch (error) {
console.error("XML Parse Error:", error);
if (windowHidden) document.getElementById('close_button')?.click();
return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.errorXmlExportParse);
}
const result = await showAlert({
title: USERSCRIPT_STRINGS.completeTacticNamePrompt,
input: 'text',
inputValue: '',
placeholder: USERSCRIPT_STRINGS.completeTacticNamePlaceholder,
inputValidator: (v) => {
if (!v) return USERSCRIPT_STRINGS.noTacticNameProvidedError;
if (v.length > MAX_TACTIC_NAME_LENGTH) return USERSCRIPT_STRINGS.tacticNameMaxLengthError;
if (completeTactics.hasOwnProperty(v)) return USERSCRIPT_STRINGS.alreadyExistingTacticNameError;
return null;
},
descriptionInput: 'textarea',
descriptionValue: '',
descriptionPlaceholder: USERSCRIPT_STRINGS.descriptionPlaceholder,
descriptionValidator: (d) => {
if (d && d.length > MAX_DESCRIPTION_LENGTH) return USERSCRIPT_STRINGS.descriptionMaxLengthError;
return null;
},
showCancelButton: true,
confirmButtonText: USERSCRIPT_STRINGS.saveButton,
cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton,
});
if (!result.isConfirmed || !result.value) {
if (windowHidden) document.getElementById('close_button')?.click();
return;
}
const baseName = result.value;
const description = result.description || '';
const fullName = `${baseName} (${getFormattedDate()})`;
savedData.description = description;
completeTactics[fullName] = savedData;
saveCompleteTacticsData();
updateCompleteTacticsDropdown(fullName);
if (windowHidden) document.getElementById('close_button')?.click();
await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.completeTacticSaveSuccess.replace('{}', fullName));
}
async function loadCompleteTactic() {
const selectedName = selectedCompleteTacticName;
if (!selectedName || !completeTactics[selectedName]) return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noTacticSelectedError);
showLoadingOverlay();
const originalAlert = window.alert;
try {
const dataToLoad = completeTactics[selectedName];
const currentRoster = await fetchTeamRoster();
if (!currentRoster) throw new Error(USERSCRIPT_STRINGS.errorFetchingRoster);
const rosterSet = new Set(currentRoster);
const originalPids = dataToLoad.originalPlayerIDs || [];
const mapping = {};
const missingPids = [];
const mappedPids = new Set();
originalPids.forEach(pid => {
if (rosterSet.has(pid)) {
mapping[pid] = pid;
mappedPids.add(pid);
} else {
missingPids.push(pid);
}
});
const availablePids = currentRoster.filter(pid => !mappedPids.has(pid));
let replacementsFound = 0;
missingPids.forEach(missingPid => {
if (availablePids.length > 0) {
const randomIndex = Math.floor(Math.random() * availablePids.length);
const replacementPid = availablePids.splice(randomIndex, 1)[0];
mapping[missingPid] = replacementPid;
replacementsFound++;
} else {
mapping[missingPid] = null;
}
});
const assignedPids = new Set();
dataToLoad.initialCoords.forEach(p => {
if (mapping[p.pid]) assignedPids.add(mapping[p.pid]);
});
dataToLoad.substitutes.forEach(s => {
if (mapping[s.pid]) assignedPids.add(mapping[s.pid]);
});
if (assignedPids.size < MIN_PLAYERS_ON_PITCH) throw new Error(USERSCRIPT_STRINGS.errorInsufficientPlayers);
let xmlString;
try {
xmlString = generateCompleteTacticXml(dataToLoad, mapping);
} catch (error) {
console.error("XML Gen Error:", error);
throw new Error(USERSCRIPT_STRINGS.errorXmlGenerate);
}
let alertContent = null;
window.alert = (msg) => {
console.warn("Native alert captured:", msg);
alertContent = msg;
};
const importButton = document.getElementById('import_button');
const importExportWindow = document.getElementById('importExportTacticsWindow');
const importExportData = document.getElementById('importExportData');
if (!importButton || !importExportWindow || !importExportData) throw new Error('Could not find required MZ UI elements for import.');
const windowHidden = importExportWindow.style.display === 'none';
if (windowHidden) {
document.getElementById('import_export_button')?.click();
await new Promise(r => setTimeout(r, 50));
}
importExportData.value = xmlString;
importButton.click();
await new Promise(r => setTimeout(r, 300));
window.alert = originalAlert;
if (alertContent) throw new Error(USERSCRIPT_STRINGS.invalidXmlForImport + (alertContent.length < 100 ? ` MZ Message: ${alertContent}` : ''));
const observer = new MutationObserver((mutationsList, obs) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
const errorBox = document.getElementById('lightbox_tactics_rule_error');
if (errorBox && errorBox.style.display !== 'none') {
const okButton = errorBox.querySelector('#powerbox_confirm_ok_button');
if (okButton) {
okButton.click();
obs.disconnect();
break;
}
}
}
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
setTimeout(() => observer.disconnect(), 3000);
if (replacementsFound > 0) {
showAlert({
title: 'Warning',
text: USERSCRIPT_STRINGS.warningPlayersSubstituted,
type: 'info'
});
}
else showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.completeTacticLoadSuccess.replace('{}', selectedName));
} catch (error) {
console.error("Load Complete Tactic Error:", error);
showErrorMessage(USERSCRIPT_STRINGS.errorTitle, error.message || 'Unknown error during load.');
if (window.alert !== originalAlert) window.alert = originalAlert;
} finally {
hideLoadingOverlay();
}
}
async function deleteCompleteTactic() {
const selectedName = selectedCompleteTacticName;
if (!selectedName || !completeTactics[selectedName]) return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noTacticSelectedError);
const confirmation = await showAlert({
title: USERSCRIPT_STRINGS.confirmationTitle,
text: USERSCRIPT_STRINGS.deleteConfirmation.replace('{}', selectedName),
showCancelButton: true,
confirmButtonText: USERSCRIPT_STRINGS.deleteTacticConfirmButton,
cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton,
type: 'error'
});
if (!confirmation.isConfirmed) return;
delete completeTactics[selectedName];
selectedCompleteTacticName = null;
saveCompleteTacticsData();
updateCompleteTacticsDropdown();
await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.completeTacticDeleteSuccess.replace('{}', selectedName));
}
async function editCompleteTactic() {
const selectedName = selectedCompleteTacticName;
if (!selectedName || !completeTactics[selectedName]) {
return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noTacticSelectedError);
}
const originalTacticData = completeTactics[selectedName];
const originalDescription = originalTacticData.description || '';
const result = await showAlert({
title: USERSCRIPT_STRINGS.renameCompleteTacticPrompt,
input: 'text',
inputValue: selectedName,
placeholder: USERSCRIPT_STRINGS.completeTacticNamePlaceholder,
inputValidator: (v) => {
if (!v) return USERSCRIPT_STRINGS.noTacticNameProvidedError;
if (v.length > MAX_TACTIC_NAME_LENGTH) return USERSCRIPT_STRINGS.tacticNameMaxLengthError;
if (v !== selectedName && completeTactics.hasOwnProperty(v)) return USERSCRIPT_STRINGS.alreadyExistingTacticNameError;
return null;
},
descriptionInput: 'textarea',
descriptionValue: originalDescription,
descriptionPlaceholder: USERSCRIPT_STRINGS.descriptionPlaceholder,
descriptionValidator: (d) => {
if (d && d.length > MAX_DESCRIPTION_LENGTH) return USERSCRIPT_STRINGS.descriptionMaxLengthError;
return null;
},
showCancelButton: true,
confirmButtonText: USERSCRIPT_STRINGS.saveButton,
cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
});
if (!result.isConfirmed || !result.value) return;
const newName = result.value;
const newDescription = result.description || '';
if (newName === selectedName && newDescription === originalDescription) return;
const tacticData = completeTactics[selectedName];
tacticData.description = newDescription;
delete completeTactics[selectedName];
completeTactics[newName] = tacticData;
saveCompleteTacticsData();
selectedCompleteTacticName = newName;
updateCompleteTacticsDropdown(newName);
await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.completeTacticRenameSuccess.replace('{}', newName));
}
async function updateCompleteTactic() {
const selectedName = selectedCompleteTacticName;
if (!selectedName || !completeTactics[selectedName]) {
return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noTacticSelectedError);
}
const confirmation = await showAlert({
title: USERSCRIPT_STRINGS.confirmationTitle,
text: USERSCRIPT_STRINGS.updateCompleteTacticConfirmation.replace('{}', selectedName),
showCancelButton: true,
confirmButtonText: USERSCRIPT_STRINGS.updateConfirmButton,
cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
});
if (!confirmation.isConfirmed) return;
const originalAlert = window.alert;
try {
const exportButton = document.getElementById('export_button');
const importExportWindow = document.getElementById('importExportTacticsWindow');
const importExportData = document.getElementById('importExportData');
if (!exportButton || !importExportWindow || !importExportData) throw new Error('Could not find required MZ UI elements for export.');
const windowHidden = importExportWindow.style.display === 'none';
if (windowHidden) {
document.getElementById('import_export_button')?.click();
await new Promise(r => setTimeout(r, 50));
}
importExportData.value = '';
exportButton.click();
await new Promise(r => setTimeout(r, 200));
const xmlString = importExportData.value;
if (windowHidden) document.getElementById('close_button')?.click();
if (!xmlString) throw new Error('Export did not produce XML.');
let updatedData;
try {
updatedData = parseCompleteTacticXml(xmlString);
} catch (error) {
console.error("XML Parse Error on Update:", error);
throw new Error(USERSCRIPT_STRINGS.errorXmlExportParse);
}
updatedData.description = completeTactics[selectedName]?.description || '';
completeTactics[selectedName] = updatedData;
saveCompleteTacticsData();
updateCompleteTacticsDropdown(selectedName);
await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.completeTacticUpdateSuccess.replace('{}', selectedName));
} catch (error) {
console.error("Update Complete Tactic Error:", error);
showErrorMessage(USERSCRIPT_STRINGS.errorTitle, error.message || 'Unknown error during update.');
if (window.alert !== originalAlert) window.alert = originalAlert;
const importExportWindow = document.getElementById('importExportTacticsWindow');
if (importExportWindow && importExportWindow.style.display !== 'none') {
document.getElementById('close_button')?.click();
}
}
}
async function importCompleteTactics() {
try {
const result = await showAlert({
title: USERSCRIPT_STRINGS.importCompleteTacticsTitle,
input: 'text',
inputValue: '',
placeholder: USERSCRIPT_STRINGS.importCompleteTacticsPlaceholder,
showCancelButton: true,
confirmButtonText: USERSCRIPT_STRINGS.importButton,
cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
});
if (!result.isConfirmed || !result.value) return;
let importedData;
try {
importedData = JSON.parse(result.value);
} catch (e) {
await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.invalidCompleteImportError);
return;
}
if (typeof importedData !== 'object' || importedData === null || Array.isArray(importedData)) {
await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.invalidCompleteImportError);
return;
}
let addedCount = 0;
let updatedCount = 0;
for (const name in importedData) {
if (importedData.hasOwnProperty(name)) {
if (typeof importedData[name] === 'object' && importedData[name] !== null) {
if (!importedData[name].hasOwnProperty('description')) importedData[name].description = '';
if (!completeTactics.hasOwnProperty(name)) {
addedCount++;
} else {
updatedCount++;
}
completeTactics[name] = importedData[name];
} else {
console.warn(`MZTM: Skipping invalid tactic data during import for key: ${name}`);
}
}
}
saveCompleteTacticsData();
updateCompleteTacticsDropdown();
let message = USERSCRIPT_STRINGS.importCompleteTacticsAlert;
if (addedCount > 0 || updatedCount > 0) {
message += ` (${addedCount > 0 ? `${addedCount} new` : ''}${addedCount > 0 && updatedCount > 0 ? ', ' : ''}${updatedCount > 0 ? `${updatedCount} updated` : ''} items)`;
}
await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, message);
} catch (error) {
console.error('Import Complete Tactics Error:', error);
await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.invalidCompleteImportError + (error.message ? `: ${error.message}` : ''));
}
}
async function exportCompleteTactics() {
try {
const jsonString = JSON.stringify(completeTactics, null, 2);
if (navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(jsonString);
await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.exportCompleteTacticsAlert);
return;
} catch (clipError) {
console.warn('Clipboard write failed, fallback.', clipError);
}
}
const textArea = document.createElement('textarea');
textArea.value = jsonString;
textArea.style.width = '100%';
textArea.style.minHeight = '150px';
textArea.style.marginTop = '10px';
textArea.style.backgroundColor = 'rgba(0,0,0,0.2)';
textArea.style.color = 'var(--text-color)';
textArea.style.border = '1px solid rgba(255,255,255,0.1)';
textArea.style.borderRadius = '4px';
textArea.readOnly = true;
const container = document.createElement('div');
container.appendChild(document.createTextNode('Copy the JSON data:'));
container.appendChild(textArea);
await showAlert({
title: USERSCRIPT_STRINGS.exportCompleteTacticsTitle,
htmlContent: container,
confirmButtonText: 'Done'
});
textArea.select();
textArea.setSelectionRange(0, 99999);
} catch (error) {
console.error('Export Complete Tactics error:', error);
await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, 'Failed to export tactics.');
}
}
function createTacticPreviewElement() {
if (previewElement) return previewElement;
previewElement = document.createElement('div');
previewElement.id = 'mztm-tactic-preview';
previewElement.style.display = 'none';
previewElement.style.opacity = '0';
previewElement.addEventListener('mouseenter', () => {
if (previewHideTimeout) clearTimeout(previewHideTimeout);
});
previewElement.addEventListener('mouseleave', hideTacticPreview);
document.body.appendChild(previewElement);
return previewElement;
}
function updatePreviewPosition(event) {
if (!previewElement || previewElement.style.display === 'none') return;
const xOffset = 15;
const yOffset = 10;
let x = event.clientX + xOffset;
let y = event.clientY + yOffset;
const previewRect = previewElement.getBoundingClientRect();
const viewportWidth = window.innerWidth;
const viewportHeight = window.innerHeight;
if (x + previewRect.width > viewportWidth - 10) {
x = event.clientX - previewRect.width - xOffset;
}
if (y + previewRect.height > viewportHeight - 10) {
y = event.clientY - previewRect.height - yOffset;
}
if (x < 10) x = 10;
if (y < 10) y = 10;
previewElement.style.left = `${x}px`;
previewElement.style.top = `${y}px`;
}
function showTacticPreview(event, listItem) {
if (!listItem || listItem.classList.contains('mztm-custom-select-category') || listItem.classList.contains('mztm-custom-select-no-results')) {
hideTacticPreview();
return;
}
if (previewHideTimeout) clearTimeout(previewHideTimeout);
const tacticId = listItem.dataset.tacticId;
const tacticName = listItem.dataset.tacticName;
const description = listItem.dataset.description || '';
const formationString = listItem.dataset.formationString || 'N/A';
const isCompleteTactic = listItem.closest('#complete_tactics_selector_list');
if (!tacticId && !tacticName) {
hideTacticPreview();
return;
}
const previewDiv = createTacticPreviewElement();
previewDiv.innerHTML = `
${USERSCRIPT_STRINGS.previewFormationLabel} ${formationString}
${description ? `${description.replace(/\n/g, '
')}
` : 'No description available.
'}
`;
previewDiv.style.display = 'block';
requestAnimationFrame(() => {
updatePreviewPosition(event);
previewDiv.style.opacity = '1';
});
document.addEventListener('mousemove', updatePreviewPosition);
}
function hideTacticPreview() {
if (previewHideTimeout) clearTimeout(previewHideTimeout);
previewHideTimeout = setTimeout(() => {
if (previewElement) {
previewElement.style.opacity = '0';
setTimeout(() => {
if (previewElement && previewElement.style.opacity === '0') {
previewElement.style.display = 'none';
}
}, 200);
document.removeEventListener('mousemove', updatePreviewPosition);
}
previewHideTimeout = null;
}, 100);
}
function addPreviewListenersToList(listElement) {
if (!listElement) return;
listElement.addEventListener('mouseover', (event) => {
const listItem = event.target.closest('.mztm-custom-select-item');
if (listItem && !listItem.classList.contains('disabled')) {
showTacticPreview(event, listItem);
} else if (!listItem) {
hideTacticPreview();
}
});
listElement.addEventListener('mouseout', (event) => {
const listItem = event.target.closest('.mztm-custom-select-item');
if (listItem) {
const related = event.relatedTarget;
if (!listItem.contains(related) && related !== previewElement) {
hideTacticPreview();
}
} else if (!listElement.contains(event.relatedTarget) && (!previewElement || event.relatedTarget !== previewElement)) {
hideTacticPreview();
}
});
window.addEventListener('scroll', hideTacticPreview, true);
}
function closeAllCustomDropdowns(exceptElement = null) {
document.querySelectorAll('.mztm-custom-select-list-container.open').forEach(container => {
const wrapper = container.closest('.mztm-custom-select-wrapper');
if (wrapper !== exceptElement?.closest('.mztm-custom-select-wrapper')) {
container.classList.remove('open');
const trigger = wrapper?.querySelector('.mztm-custom-select-trigger');
trigger?.classList.remove('open');
}
});
currentOpenDropdown = exceptElement?.closest('.mztm-custom-select-wrapper') || null;
}
document.addEventListener('click', (event) => {
if (currentOpenDropdown && !currentOpenDropdown.contains(event.target)) {
closeAllCustomDropdowns();
}
});
function createCustomSelect(id, placeholderText) {
const wrapper = document.createElement('div');
wrapper.className = 'mztm-custom-select-wrapper';
wrapper.id = `${id}_wrapper`;
const trigger = document.createElement('div');
trigger.className = 'mztm-custom-select-trigger';
trigger.id = `${id}_trigger`;
trigger.tabIndex = 0;
const triggerText = document.createElement('span');
triggerText.className = 'mztm-custom-select-text mztm-custom-select-placeholder';
triggerText.textContent = placeholderText;
trigger.appendChild(triggerText);
const listContainer = document.createElement('div');
listContainer.className = 'mztm-custom-select-list-container';
listContainer.id = `${id}_list_container`;
const list = document.createElement('ul');
list.className = 'mztm-custom-select-list';
list.id = `${id}_list`;
listContainer.appendChild(list);
addPreviewListenersToList(list);
trigger.addEventListener('click', (e) => {
e.stopPropagation();
const isOpen = listContainer.classList.contains('open');
closeAllCustomDropdowns(wrapper);
if (!isOpen && !trigger.classList.contains('disabled')) {
listContainer.classList.add('open');
trigger.classList.add('open');
currentOpenDropdown = wrapper;
}
});
trigger.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
trigger.click();
}
});
list.addEventListener('click', (e) => {
const item = e.target.closest('.mztm-custom-select-item');
if (item && !item.classList.contains('disabled')) {
const value = item.dataset.value || item.dataset.tacticId || item.dataset.tacticName;
const text = item.textContent;
triggerText.textContent = text;
triggerText.classList.remove('mztm-custom-select-placeholder');
trigger.dataset.selectedValue = value;
if (id === 'tactics_selector') {
handleTacticSelection(value);
} else if (id === 'complete_tactics_selector') {
selectedCompleteTacticName = value;
}
closeAllCustomDropdowns();
const changeEvent = new Event('change', { bubbles: true });
trigger.dispatchEvent(changeEvent);
}
});
wrapper.appendChild(trigger);
wrapper.appendChild(listContainer);
return wrapper;
}
function createTacticsSelector() {
const container = document.createElement('div');
container.className = 'tactics-selector-section';
const controlsContainer = document.createElement('div');
controlsContainer.className = 'formations-controls-container';
const dropdownWrapper = createCustomSelect('tactics_selector', USERSCRIPT_STRINGS.tacticsDropdownMenuLabel);
const searchBox = document.createElement('input');
searchBox.type = 'text';
searchBox.className = 'tactics-search-box';
searchBox.placeholder = USERSCRIPT_STRINGS.searchPlaceholder;
searchBox.addEventListener('input', (e) => {
searchTerm = e.target.value.toLowerCase();
updateTacticsDropdown(selectedFormationTacticId);
});
const filterDropdownWrapper = document.createElement('div');
filterDropdownWrapper.className = 'category-filter-wrapper';
const filterSelect = document.createElement('select');
filterSelect.id = 'category_filter_selector';
filterSelect.addEventListener('change', (e) => {
currentFilter = e.target.value;
GM_setValue(CATEGORY_FILTER_STORAGE_KEY, currentFilter);
updateTacticsDropdown(selectedFormationTacticId);
});
const manageBtn = document.createElement('button');
manageBtn.id = 'manage_items_btn';
manageBtn.className = 'mzbtn manage-items-btn';
manageBtn.innerHTML = '⚙️';
manageBtn.title = USERSCRIPT_STRINGS.managementModalTitle;
manageBtn.addEventListener('click', showManagementModal);
filterDropdownWrapper.appendChild(filterSelect);
filterDropdownWrapper.appendChild(manageBtn);
appendChildren(controlsContainer, [dropdownWrapper, searchBox, filterDropdownWrapper]);
container.appendChild(controlsContainer);
return container;
}
function updateCategoryFilterDropdown() {
const filterSelect = document.getElementById('category_filter_selector');
if (!filterSelect) return;
filterSelect.innerHTML = '';
const usedCategoryIds = new Set(tactics.map(t => t.style || OTHER_CATEGORY_ID));
let categoriesToShow = [{
id: 'all',
name: USERSCRIPT_STRINGS.allTacticsFilter
}];
Object.values(categories)
.filter(cat => cat.id !== 'all' && (usedCategoryIds.has(cat.id) || Object.keys(DEFAULT_CATEGORIES).includes(cat.id) || cat.id === OTHER_CATEGORY_ID))
.sort((a, b) => {
if (a.id === OTHER_CATEGORY_ID) return 1;
if (b.id === OTHER_CATEGORY_ID) return -1;
return a.name.localeCompare(b.name);
})
.forEach(cat => categoriesToShow.push({ id: cat.id, name: getCategoryName(cat.id) }));
let foundCurrentFilter = false;
categoriesToShow.forEach(categoryInfo => {
const option = document.createElement('option');
option.value = categoryInfo.id;
option.textContent = categoryInfo.name;
filterSelect.appendChild(option);
if (categoryInfo.id === currentFilter) {
foundCurrentFilter = true;
}
});
if (foundCurrentFilter) {
filterSelect.value = currentFilter;
} else {
filterSelect.value = 'all';
currentFilter = 'all';
GM_setValue(CATEGORY_FILTER_STORAGE_KEY, currentFilter);
}
filterSelect.disabled = categoriesToShow.length <= 1;
}
function updateTacticsDropdown(currentSelectedId = null) {
const listElement = document.getElementById('tactics_selector_list');
const triggerElement = document.getElementById('tactics_selector_trigger');
const triggerTextElement = triggerElement?.querySelector('.mztm-custom-select-text');
const wrapper = document.getElementById('tactics_selector_wrapper');
const searchBox = document.querySelector('.tactics-search-box');
if (!listElement || !triggerElement || !triggerTextElement || !wrapper) return;
listElement.innerHTML = '';
if (searchTerm.length > 0) {
wrapper.classList.add('filtering');
searchBox?.classList.add('filtering');
} else {
wrapper.classList.remove('filtering');
searchBox?.classList.remove('filtering');
}
const filteredTactics = tactics.filter(t => {
const nameMatch = searchTerm === '' || t.name.toLowerCase().includes(searchTerm);
const categoryMatch = currentFilter === 'all' || (currentFilter === OTHER_CATEGORY_ID && (!t.style || t.style === OTHER_CATEGORY_ID)) || t.style === currentFilter;
return nameMatch && categoryMatch;
});
const groupedTactics = {};
Object.keys(categories).forEach(id => {
if (id !== 'all') groupedTactics[id] = [];
});
if (!groupedTactics[OTHER_CATEGORY_ID]) groupedTactics[OTHER_CATEGORY_ID] = [];
filteredTactics.forEach(t => {
const categoryId = t.style || OTHER_CATEGORY_ID;
if (!groupedTactics[categoryId]) {
if (!groupedTactics[OTHER_CATEGORY_ID]) groupedTactics[OTHER_CATEGORY_ID] = [];
groupedTactics[OTHER_CATEGORY_ID].push(t);
}
else groupedTactics[categoryId].push(t);
});
const categoryOrder = Object.keys(groupedTactics).filter(id => groupedTactics[id].length > 0).sort((a, b) => {
if (a === currentFilter) return -1;
if (b === currentFilter) return 1;
if (DEFAULT_CATEGORIES[a] && !DEFAULT_CATEGORIES[b]) return -1;
if (!DEFAULT_CATEGORIES[a] && DEFAULT_CATEGORIES[b]) return 1;
if (a === OTHER_CATEGORY_ID) return 1;
if (b === OTHER_CATEGORY_ID) return -1;
return (getCategoryName(a) || '').localeCompare(getCategoryName(b) || '');
});
let itemsAdded = 0;
categoryOrder.forEach(categoryId => {
if (groupedTactics[categoryId].length > 0) {
addTacticItemsGroup(listElement, groupedTactics[categoryId], getCategoryName(categoryId), categoryId);
itemsAdded += groupedTactics[categoryId].length;
}
});
if (itemsAdded === 0) {
const noResultsItem = document.createElement('li');
noResultsItem.className = 'mztm-custom-select-no-results';
noResultsItem.textContent = tactics.length === 0 ? USERSCRIPT_STRINGS.noTacticsSaved : USERSCRIPT_STRINGS.noTacticsFound;
listElement.appendChild(noResultsItem);
triggerElement.classList.add('disabled');
triggerTextElement.textContent = tactics.length === 0 ? USERSCRIPT_STRINGS.noTacticsSaved : USERSCRIPT_STRINGS.tacticsDropdownMenuLabel;
triggerTextElement.classList.add('mztm-custom-select-placeholder');
delete triggerElement.dataset.selectedValue;
selectedFormationTacticId = null;
} else {
triggerElement.classList.remove('disabled');
const currentSelection = tactics.find(t => t.id === currentSelectedId);
if (currentSelection) {
triggerTextElement.textContent = currentSelection.name;
triggerTextElement.classList.remove('mztm-custom-select-placeholder');
triggerElement.dataset.selectedValue = currentSelection.id;
selectedFormationTacticId = currentSelection.id;
} else {
triggerTextElement.textContent = USERSCRIPT_STRINGS.tacticsDropdownMenuLabel;
triggerTextElement.classList.add('mztm-custom-select-placeholder');
delete triggerElement.dataset.selectedValue;
selectedFormationTacticId = null;
}
}
}
function addTacticItemsGroup(listElement, tacticsList, groupLabel, categoryId) {
if (tacticsList.length === 0) return;
const categoryHeader = document.createElement('li');
categoryHeader.className = 'mztm-custom-select-category';
categoryHeader.textContent = groupLabel;
listElement.appendChild(categoryHeader);
tacticsList.sort((a, b) => a.name.localeCompare(b.name));
tacticsList.forEach(tactic => {
const item = document.createElement('li');
item.className = 'mztm-custom-select-item';
item.textContent = tactic.name;
item.dataset.tacticId = tactic.id;
item.dataset.value = tactic.id;
item.dataset.description = tactic.description || '';
item.dataset.style = tactic.style || OTHER_CATEGORY_ID;
item.dataset.formationString = formatFormationString(getFormation(tactic.coordinates));
listElement.appendChild(item);
});
}
function createCompleteTacticsSelector() {
const container = document.createElement('div');
container.className = 'tactics-selector-section';
const label = document.createElement('label');
label.textContent = '';
label.className = 'tactics-selector-label';
const dropdownWrapper = createCustomSelect('complete_tactics_selector', USERSCRIPT_STRINGS.completeTacticsDropdownMenuLabel);
container.appendChild(label);
container.appendChild(dropdownWrapper);
return container;
}
function updateCompleteTacticsDropdown(currentSelectedName = null) {
const listElement = document.getElementById('complete_tactics_selector_list');
const triggerElement = document.getElementById('complete_tactics_selector_trigger');
const triggerTextElement = triggerElement?.querySelector('.mztm-custom-select-text');
const wrapper = document.getElementById('complete_tactics_selector_wrapper');
if (!listElement || !triggerElement || !triggerTextElement || !wrapper) return;
listElement.innerHTML = '';
const names = Object.keys(completeTactics).sort((a, b) => a.localeCompare(b));
if (names.length === 0) {
const noResultsItem = document.createElement('li');
noResultsItem.className = 'mztm-custom-select-no-results';
noResultsItem.textContent = USERSCRIPT_STRINGS.noCompleteTacticsSaved;
listElement.appendChild(noResultsItem);
triggerElement.classList.add('disabled');
triggerTextElement.textContent = USERSCRIPT_STRINGS.noCompleteTacticsSaved;
triggerTextElement.classList.add('mztm-custom-select-placeholder');
delete triggerElement.dataset.selectedValue;
selectedCompleteTacticName = null;
} else {
triggerElement.classList.remove('disabled');
names.forEach(name => {
const tactic = completeTactics[name];
const item = document.createElement('li');
item.className = 'mztm-custom-select-item';
item.textContent = name;
item.dataset.tacticName = name;
item.dataset.value = name;
item.dataset.description = tactic.description || '';
item.dataset.formationString = formatFormationString(getFormationFromCompleteTactic(tactic));
listElement.appendChild(item);
});
const currentSelection = currentSelectedName && completeTactics[currentSelectedName] ? currentSelectedName : null;
if (currentSelection) {
triggerTextElement.textContent = currentSelection;
triggerTextElement.classList.remove('mztm-custom-select-placeholder');
triggerElement.dataset.selectedValue = currentSelection;
selectedCompleteTacticName = currentSelection;
} else {
triggerTextElement.textContent = USERSCRIPT_STRINGS.completeTacticsDropdownMenuLabel;
triggerTextElement.classList.add('mztm-custom-select-placeholder');
delete triggerElement.dataset.selectedValue;
selectedCompleteTacticName = null;
}
}
}
function createButton(id, text, clickHandler) {
const button = document.createElement('button');
setUpButton(button, id, text);
if (clickHandler) {
button.addEventListener('click', async (e) => {
e.stopPropagation();
try {
await clickHandler();
} catch (err) {
console.error('Button click failed:', err);
showErrorMessage('Action Failed', `${err.message || err}`);
}
});
}
return button;
}
async function checkVersion() {
const savedVersion = GM_getValue(VERSION_KEY, null);
if (!savedVersion || savedVersion !== SCRIPT_VERSION) {
await showWelcomeMessage();
GM_setValue(VERSION_KEY, SCRIPT_VERSION);
}
}
function createModeToggleSwitch() {
const label = document.createElement('label');
label.className = 'mode-toggle-switch';
const input = document.createElement('input');
input.type = 'checkbox';
input.id = 'view-mode-toggle';
input.addEventListener('change', (e) => setViewMode(e.target.checked ? 'complete' : 'normal'));
const slider = document.createElement('span');
slider.className = 'mode-toggle-slider';
label.appendChild(input);
label.appendChild(slider);
return label;
}
function createModeLabel(mode, isPrefix = false) {
const span = document.createElement('span');
span.className = 'mode-toggle-label';
span.textContent = isPrefix ? USERSCRIPT_STRINGS.modeLabel : (mode === 'normal' ? USERSCRIPT_STRINGS.normalModeLabel : USERSCRIPT_STRINGS.completeModeLabel);
span.id = `mode-label-${mode}`;
return span;
}
function setViewMode(mode) {
currentViewMode = mode;
GM_setValue(VIEW_MODE_KEY, mode);
const normalContent = document.getElementById('normal-tactics-content');
const completeContent = document.getElementById('complete-tactics-content');
const toggleInput = document.getElementById('view-mode-toggle');
const normalLabel = document.getElementById('mode-label-normal');
const completeLabel = document.getElementById('mode-label-complete');
const isNormal = mode === 'normal';
if (normalContent) normalContent.style.display = isNormal ? 'block' : 'none';
if (completeContent) completeContent.style.display = isNormal ? 'none' : 'block';
if (toggleInput) toggleInput.checked = !isNormal;
if (normalLabel) normalLabel.classList.toggle('active', isNormal);
if (completeLabel) completeLabel.classList.toggle('active', !isNormal);
}
function createMainContainer() {
const container = document.createElement('div');
container.id = 'mz_tactics_panel';
container.classList.add('mz-panel');
const header = document.createElement('div');
header.classList.add('mz-group-main-title');
const titleContainer = document.createElement('div');
titleContainer.className = 'mz-title-container';
const titleText = document.createElement('span');
titleText.textContent = USERSCRIPT_STRINGS.managerTitle;
titleText.classList.add('mz-main-title');
const versionText = document.createElement('span');
versionText.textContent = 'v' + DISPLAY_VERSION;
versionText.classList.add('mz-version-text');
const modeToggleContainer = document.createElement('div');
modeToggleContainer.className = 'mode-toggle-container';
const prefixLabel = createModeLabel('', true);
const modeLabelNormal = createModeLabel('normal');
const toggleSwitch = createModeToggleSwitch();
const modeLabelComplete = createModeLabel('complete');
appendChildren(modeToggleContainer, [prefixLabel, modeLabelNormal, toggleSwitch, modeLabelComplete]);
appendChildren(titleContainer, [titleText, versionText, modeToggleContainer]);
header.appendChild(titleContainer);
const toggleButton = createToggleButton();
header.appendChild(toggleButton);
container.appendChild(header);
const group = document.createElement('div');
group.classList.add('mz-group');
container.appendChild(group);
const normalContent = document.createElement('div');
normalContent.id = 'normal-tactics-content';
normalContent.className = 'section-content';
const tacticsSelectorSection = createTacticsSelector();
const normalButtonsSection = document.createElement('div');
normalButtonsSection.className = 'action-buttons-section';
const addCurrentBtn = createButton('add_current_tactic_btn', USERSCRIPT_STRINGS.addCurrentTactic, addNewTactic);
const addXmlBtn = createButton('add_xml_tactic_btn', USERSCRIPT_STRINGS.addWithXmlButton, addNewTacticWithXml);
const editBtn = createButton('edit_tactic_button', USERSCRIPT_STRINGS.renameButton, () => editTactic());
const updateBtn = createButton('update_tactic_button', USERSCRIPT_STRINGS.updateButton, updateTactic);
const deleteBtn = createButton('delete_tactic_button', USERSCRIPT_STRINGS.deleteButton, deleteTactic);
const importBtn = createButton('import_tactics_btn', USERSCRIPT_STRINGS.importButton, importTacticsJsonData);
const exportBtn = createButton('export_tactics_btn', USERSCRIPT_STRINGS.exportButton, exportTacticsJsonData);
const resetBtn = createButton('reset_tactics_btn', USERSCRIPT_STRINGS.resetButton, resetTactics);
const clearBtn = createButton('clear_tactics_btn', USERSCRIPT_STRINGS.clearButton, clearTactics);
const normalButtonsRow1 = document.createElement('div');
normalButtonsRow1.className = 'action-buttons-row';
appendChildren(normalButtonsRow1, [addCurrentBtn, addXmlBtn, editBtn, updateBtn, deleteBtn]);
const normalButtonsRow2 = document.createElement('div');
normalButtonsRow2.className = 'action-buttons-row';
appendChildren(normalButtonsRow2, [importBtn, exportBtn, resetBtn, clearBtn]);
appendChildren(normalButtonsSection, [normalButtonsRow1, normalButtonsRow2]);
appendChildren(normalContent, [tacticsSelectorSection, normalButtonsSection, createHiddenTriggerButton(), createCombinedInfoButton()]);
group.appendChild(normalContent);
const completeContent = document.createElement('div');
completeContent.id = 'complete-tactics-content';
completeContent.className = 'section-content';
completeContent.style.display = 'none';
const completeTacticsSelectorSection = createCompleteTacticsSelector();
const completeButtonsSection = document.createElement('div');
completeButtonsSection.className = 'action-buttons-section';
const completeButtonsRow1 = document.createElement('div');
completeButtonsRow1.className = 'action-buttons-row';
const saveCompleteBtn = createButton('save_complete_tactic_button', USERSCRIPT_STRINGS.saveCompleteTacticButton, saveCompleteTactic);
const loadCompleteBtn = createButton('load_complete_tactic_button', USERSCRIPT_STRINGS.loadCompleteTacticButton, loadCompleteTactic);
const renameCompleteBtn = createButton('rename_complete_tactic_button', USERSCRIPT_STRINGS.renameCompleteTacticButton, editCompleteTactic);
const updateCompleteBtn = createButton('update_complete_tactic_button', USERSCRIPT_STRINGS.updateCompleteTacticButton, updateCompleteTactic);
const deleteCompleteBtn = createButton('delete_complete_tactic_button', USERSCRIPT_STRINGS.deleteCompleteTacticButton, deleteCompleteTactic);
appendChildren(completeButtonsRow1, [saveCompleteBtn, loadCompleteBtn, renameCompleteBtn, updateCompleteBtn, deleteCompleteBtn]);
const completeButtonsRow2 = document.createElement('div');
completeButtonsRow2.className = 'action-buttons-row';
const importCompleteBtn = createButton('import_complete_tactics_btn', USERSCRIPT_STRINGS.importCompleteTacticsButton, importCompleteTactics);
const exportCompleteBtn = createButton('export_complete_tactics_btn', USERSCRIPT_STRINGS.exportCompleteTacticsButton, exportCompleteTactics);
appendChildren(completeButtonsRow2, [importCompleteBtn, exportCompleteBtn]);
appendChildren(completeButtonsSection, [completeButtonsRow1, completeButtonsRow2]);
appendChildren(completeContent, [completeTacticsSelectorSection, completeButtonsSection, createCombinedInfoButton()]);
group.appendChild(completeContent);
return container;
}
function createHiddenTriggerButton() {
const button = document.createElement('button');
button.id = 'hidden_trigger_button';
button.textContent = '';
button.style.cssText = 'position:absolute; opacity:0; pointer-events:none; width:0; height:0; padding:0; margin:0; border:0;';
button.addEventListener('click', function () {
const presetSelect = document.getElementById('tactics_preset');
if (presetSelect) {
presetSelect.value = '5-3-2';
presetSelect.dispatchEvent(new Event('change'));
}
});
return button;
}
function setUpButton(button, id, text) {
button.id = id;
button.classList.add('mzbtn');
button.textContent = text;
}
function createModalTabs(tabsConfig, modalBody) {
const tabsContainer = document.createElement('div');
tabsContainer.className = 'modal-tabs';
tabsConfig.forEach((tab, index) => {
const tabButton = document.createElement('button');
tabButton.className = 'modal-tab';
tabButton.textContent = tab.title;
tabButton.dataset.tabId = tab.id;
if (index === 0) tabButton.classList.add('active');
tabButton.addEventListener('click', () => {
modalBody.querySelectorAll('.modal-tab').forEach(t => t.classList.remove('active'));
modalBody.querySelectorAll('.management-modal-content, .modal-tab-content').forEach(c => c.classList.remove('active'));
tabButton.classList.add('active');
const content = modalBody.querySelector(`.management-modal-content[data-tab-id="${tab.id}"], .modal-tab-content[data-tab-id="${tab.id}"]`);
if (content) content.classList.add('active');
});
tabsContainer.appendChild(tabButton);
});
return tabsContainer;
}
function createTabbedModalContent(tabsConfig) {
const wrapper = document.createElement('div');
wrapper.className = 'modal-info-wrapper';
const tabs = createModalTabs(tabsConfig, wrapper);
wrapper.appendChild(tabs);
tabsConfig.forEach((tab, index) => {
const contentDiv = document.createElement('div');
contentDiv.className = 'modal-tab-content';
contentDiv.dataset.tabId = tab.id;
if (index === 0) contentDiv.classList.add('active');
const content = tab.contentGenerator();
contentDiv.appendChild(content);
wrapper.appendChild(contentDiv);
});
return wrapper;
}
function createAboutTabContent() {
const content = document.createElement('div');
const aboutSection = document.createElement('div');
const aboutTitle = document.createElement('h3');
aboutTitle.textContent = 'About';
const infoText = document.createElement('p');
infoText.id = 'info_modal_info_text';
infoText.innerHTML = USERSCRIPT_STRINGS.modalContentInfoText;
const feedbackText = document.createElement('p');
feedbackText.id = 'info_modal_feedback_text';
feedbackText.innerHTML = USERSCRIPT_STRINGS.modalContentFeedbackText;
appendChildren(aboutSection, [aboutTitle, infoText, feedbackText]);
content.appendChild(aboutSection);
const faqSection = document.createElement('div');
faqSection.className = 'faq-section';
const faqTitle = document.createElement('h3');
faqTitle.textContent = 'FAQ/Function Explanations';
faqSection.appendChild(faqTitle);
const formationItems = [
{ q: "Add Current
Button (Formations Mode)", a: "Saves the player positions currently visible on the pitch as a new formation. You'll be prompted for a name, category, and an optional description." },
{ q: "Add via XML
Button (Formations Mode)", a: "Allows pasting XML to add a new formation. Only player positions are saved from the XML. Prompted for name, category, and description." },
{ q: "Category Filter Dropdown & ⚙️
Button (Formations Mode)", a: "Use the dropdown to filter formations by category (your last selection is remembered). Click the gear icon (⚙️) to open the Management Modal (Formations & Categories)." },
{ q: "Edit
Button (Formations Mode)", a: "Allows renaming the selected formation, changing its assigned category, and editing its description via a popup." },
{ q: "Update Coords
Button (Formations Mode)", a: "Updates the coordinates of the selected formation to match the current player positions on the pitch (description and category remain unchanged)." },
{ q: "Delete
Button (Formations Mode)", a: "Permanently removes the selected formation from the storage." },
{ q: "Import
Button (Formations Mode)", a: "Imports multiple formations from a JSON text format. Merges with existing formations (updates name/category/description if ID matches)." },
{ q: "Export
Button (Formations Mode)", a: "Exports all saved formations (including descriptions) into a JSON text format (copied to clipboard)." },
{ q: "Reset
Button (Formations Mode)", a: "Deletes all saved formations and custom categories, restoring defaults. Also resets the saved category filter." },
{ q: "Clear
Button (Formations Mode)", a: "Deletes all saved formations. Also resets the saved category filter." },
{ q: "Management Modal (Gear Icon ⚙️)", a: "Opens a dedicated window to manage formations (edit name/description/category, delete) and categories (add, remove) in bulk." },
{ q: "Preview on Hover (Formations Mode)", a: "Hover your mouse over a formation name in the dropdown list to see its numerical formation (e.g., 4-4-2) and its description in a small pop-up." }
];
const tacticItems = [
{ q: "Save Current
Button (Tactics Mode)", a: "Exports the entire current tactic setup (positions, alts, rules, settings) using MZ's native export, parses it, prompts for a name and description, then saves it as a new complete tactic." },
{ q: "Load
Button (Tactics Mode)", a: "Loads a saved complete tactic using MZ's native import. Shows a spinner during load. Matches players or substitutes if needed. Updates everything on the pitch." },
{ q: "Rename
Button (Tactics Mode)", a: "Allows renaming the selected complete tactic and editing its description via a popup." },
{ q: "Update with Current
Button (Tactics Mode)", a: "Overwrites the selected complete tactic's positions, rules, and settings with the setup currently on the pitch (using native export). The existing description is kept." },
{ q: "Delete
Button (Tactics Mode)", a: "Permanently removes the selected complete tactic." },
{ q: "Import
Button (Tactics Mode)", a: "Imports multiple complete tactics from a JSON text format. Merges with existing tactics, overwriting any with the same name (including description)." },
{ q: "Export
Button (Tactics Mode)", a: "Exports all saved complete tactics (including descriptions) into a JSON text format (copied to clipboard)." },
{ q: "Preview on Hover (Tactics Mode)", a: "Hover your mouse over a tactic name in the dropdown list to see its numerical formation (e.g., 5-3-2, based on initial positions) and its description in a small pop-up." }
];
const combinedItems = [...formationItems, ...tacticItems].sort((a, b) => {
const modeA = a.q.includes("Formations Mode") || a.q.includes("Category Filter") || a.q.includes("Management Modal") ? 0 : (a.q.includes("Tactics Mode") ? 1 : 2);
const modeB = b.q.includes("Formations Mode") || b.q.includes("Category Filter") || b.q.includes("Management Modal") ? 0 : (b.q.includes("Tactics Mode") ? 1 : 2);
if (modeA !== modeB) return modeA - modeB;
return a.q.localeCompare(b.q);
});
combinedItems.forEach(item => {
const faqItemDiv = document.createElement('div');
faqItemDiv.className = 'faq-item';
const question = document.createElement('h4');
question.innerHTML = item.q;
const answer = document.createElement('p');
answer.textContent = item.a;
appendChildren(faqItemDiv, [question, answer]);
faqSection.appendChild(faqItemDiv);
});
content.appendChild(faqSection);
return content;
}
function createLinksTabContent() {
const content = document.createElement('div');
const linksSection = document.createElement('div');
const linksTitle = document.createElement('h3');
linksTitle.textContent = 'Useful Links';
const resourcesText = createUsefulContent();
const linksMap = new Map([
['gewlaht - BoooM', 'https://www.managerzone.com/?p=forum&sub=topic&topic_id=11415137&forum_id=49&sport=soccer'],
['taktikskola by honken91', 'https://www.managerzone.com/?p=forum&sub=topic&topic_id=12653892&forum_id=4&sport=soccer'],
['peto - mix de dibujos', 'https://www.managerzone.com/?p=forum&sub=topic&topic_id=12196312&forum_id=255&sport=soccer'],
['The Zone Chile', 'https://www.managerzone.com/thezone/paper.php?paper_id=18036&page=9&sport=soccer'],
['Tactics guide by lukasz87o/filipek4', 'https://www.managerzone.com/?p=forum&sub=topic&topic_id=12766444&forum_id=12&sport=soccer&share_sport=soccer'],
['MZExtension/van.mz.playerAdvanced by vanjoge', 'https://greasyfork.org/en/scripts/373382-van-mz-playeradvanced'],
['Mazyar Userscript', 'https://greasyfork.org/en/scripts/476290-mazyar'],
['Stats Xente Userscript', 'https://greasyfork.org/en/scripts/491442-stats-xente-script'],
['More userscripts', 'https://greasyfork.org/en/users/1088808-douglasdotv']
]);
const linksList = createLinksList(linksMap);
appendChildren(linksSection, [linksTitle, resourcesText, linksList]);
content.appendChild(linksSection);
return content;
}
function createCombinedInfoButton() {
const button = createButton('info_button', USERSCRIPT_STRINGS.infoButton, null);
button.classList.add('footer-actions');
button.style.background = 'transparent';
button.style.border = 'none';
button.style.boxShadow = 'none';
button.style.fontFamily = '"Quicksand", sans-serif';
button.style.color = 'gold';
button.addEventListener('click', (e) => {
e.stopPropagation();
const tabsConfig = [{
id: 'about',
title: 'About & FAQ',
contentGenerator: createAboutTabContent
}, {
id: 'links',
title: 'Useful Links',
contentGenerator: createLinksTabContent
}];
const modalContent = createTabbedModalContent(tabsConfig);
showAlert({
title: 'MZ Tactics Manager Info',
htmlContent: modalContent,
confirmButtonText: DEFAULT_MODAL_STRINGS.ok
});
});
return button;
}
function createUsefulContent() {
const p = document.createElement('p');
p.id = 'useful_content';
p.textContent = USERSCRIPT_STRINGS.usefulContent;
return p;
}
function createLinksList(linksMap) {
const list = document.createElement('ul');
linksMap.forEach((href, text) => {
const listItem = document.createElement('li');
const anchor = document.createElement('a');
anchor.href = href;
anchor.target = '_blank';
anchor.rel = 'noopener noreferrer';
anchor.textContent = text;
listItem.appendChild(anchor);
list.appendChild(listItem);
});
return list;
}
function createToggleButton() {
const button = document.createElement('button');
button.id = 'toggle_panel_btn';
button.innerHTML = '✕';
button.title = 'Hide panel';
return button;
}
function createCollapsedIcon() {
const icon = document.createElement('div');
icon.id = 'collapsed_icon';
icon.innerHTML = 'TM';
icon.title = 'Show MZ Tactics Manager';
collapsedIconElement = icon;
return icon;
}
async function initializeUsData() {
loadCategories();
currentFilter = GM_getValue(CATEGORY_FILTER_STORAGE_KEY, 'all');
const ids = await fetchTeamIdAndUsername();
if (!ids.teamId) {
console.warn("MZTM: Failed to get Team ID.");
}
tactics = [];
const rawTacticDataFromStorage = GM_getValue(FORMATIONS_STORAGE_KEY);
const oldRawTacticDataFromStorage = GM_getValue(OLD_FORMATIONS_STORAGE_KEY);
if (!rawTacticDataFromStorage && oldRawTacticDataFromStorage && oldRawTacticDataFromStorage.tactics && Array.isArray(oldRawTacticDataFromStorage.tactics)) {
console.log(`MZTM: Migrating tactics from old storage key '${OLD_FORMATIONS_STORAGE_KEY}' to '${FORMATIONS_STORAGE_KEY}'.`);
let migratedTactics = oldRawTacticDataFromStorage.tactics.filter(t => t && t.name && t.id && Array.isArray(t.coordinates));
migratedTactics.forEach(t => {
if (!t.hasOwnProperty('style')) t.style = OTHER_CATEGORY_ID;
if (!t.hasOwnProperty('description')) t.description = '';
});
tactics = migratedTactics;
await GM_setValue(FORMATIONS_STORAGE_KEY, { tactics: tactics });
await GM_deleteValue(OLD_FORMATIONS_STORAGE_KEY);
console.log(`MZTM: Migration complete. Deleted old key '${OLD_FORMATIONS_STORAGE_KEY}'.`);
} else if (!rawTacticDataFromStorage) {
console.log("MZTM: No existing formations data found. Loading initial default formations.");
await loadInitialTacticsAndCategories();
} else {
if (!rawTacticDataFromStorage.tactics || !Array.isArray(rawTacticDataFromStorage.tactics)) {
rawTacticDataFromStorage.tactics = [];
}
let loadedTactics = rawTacticDataFromStorage.tactics.filter(t => t && t.name && t.id && Array.isArray(t.coordinates));
let dataWasChangedDuringValidation = false;
loadedTactics.forEach(t => {
if (!t.hasOwnProperty('style')) {
t.style = OTHER_CATEGORY_ID;
dataWasChangedDuringValidation = true;
}
if (!t.hasOwnProperty('description')) {
t.description = '';
dataWasChangedDuringValidation = true;
}
});
if (dataWasChangedDuringValidation) {
await GM_setValue(FORMATIONS_STORAGE_KEY, { tactics: loadedTactics });
}
tactics = loadedTactics;
}
tactics.sort((a, b) => a.name.localeCompare(b.name));
loadCompleteTacticsData();
const storedCompleteTactics = GM_getValue(COMPLETE_TACTICS_STORAGE_KEY, {});
let completeTacticsChanged = false;
for (const name in storedCompleteTactics) {
if (storedCompleteTactics.hasOwnProperty(name)) {
if (storedCompleteTactics[name] && typeof storedCompleteTactics[name] === 'object' && !storedCompleteTactics[name].hasOwnProperty('description')) {
storedCompleteTactics[name].description = '';
completeTacticsChanged = true;
}
}
}
if (completeTacticsChanged) {
GM_setValue(COMPLETE_TACTICS_STORAGE_KEY, storedCompleteTactics);
}
completeTactics = storedCompleteTactics;
await checkVersion();
}
function setUpTacticsInterface(mainContainer) {
const toggleButton = mainContainer.querySelector('#toggle_panel_btn');
const collapsedIcon = collapsedIconElement || createCollapsedIcon();
let isCollapsed = GM_getValue(COLLAPSED_KEY, false);
const anchorButtonId = 'replace-player-btn';
const applyCollapseState = (instant = false) => {
const anchorButton = document.getElementById(anchorButtonId);
if (collapsedIcon && collapsedIcon.parentNode) {
collapsedIcon.parentNode.removeChild(collapsedIcon);
}
if (isCollapsed) {
if (instant) {
mainContainer.style.transition = 'none';
mainContainer.classList.add('collapsed');
void mainContainer.offsetHeight;
mainContainer.style.transition = '';
} else {
mainContainer.classList.add('collapsed');
}
toggleButton.innerHTML = '☰';
toggleButton.title = 'Show panel';
if (anchorButton) {
insertAfterElement(collapsedIcon, anchorButton);
collapsedIcon.classList.add('visible');
} else {
console.warn(`MZTM: Anchor button #${anchorButtonId} not found for collapsed icon.`);
collapsedIcon.classList.remove('visible');
}
} else {
mainContainer.classList.remove('collapsed');
toggleButton.innerHTML = '✕';
toggleButton.title = 'Hide panel';
collapsedIcon.classList.remove('visible');
}
};
applyCollapseState(true);
function togglePanel() {
isCollapsed = !isCollapsed;
GM_setValue(COLLAPSED_KEY, isCollapsed);
applyCollapseState();
}
toggleButton.addEventListener('click', (e) => {
e.stopPropagation();
togglePanel();
});
collapsedIcon.addEventListener('click', () => {
togglePanel();
});
}
async function initialize() {
const tacticsBox = document.getElementById('tactics_box');
if (!tacticsBox || !isFootball()) {
console.log("MZTM: Not on valid page or tactics box not found.");
return;
}
const cachedUserInfo = GM_getValue(USER_INFO_CACHE_KEY);
if (cachedUserInfo && typeof cachedUserInfo === 'object' && cachedUserInfo.teamId && cachedUserInfo.username && cachedUserInfo.timestamp) {
userInfoCache = cachedUserInfo;
if (Date.now() - userInfoCache.timestamp < USER_INFO_CACHE_DURATION_MS) {
teamId = userInfoCache.teamId;
username = userInfoCache.username;
}
}
const cachedRoster = GM_getValue(ROSTER_CACHE_KEY);
if (cachedRoster && typeof cachedRoster === 'object' && cachedRoster.data && cachedRoster.timestamp) {
rosterCache = cachedRoster;
}
try {
collapsedIconElement = createCollapsedIcon();
createTacticPreviewElement();
await initializeUsData();
const mainContainer = createMainContainer();
setUpTacticsInterface(mainContainer);
insertAfterElement(mainContainer, tacticsBox);
updateTacticsDropdown();
updateCategoryFilterDropdown();
updateCompleteTacticsDropdown();
const savedMode = GM_getValue(VIEW_MODE_KEY, 'normal');
setViewMode(savedMode);
} catch (error) {
console.error('MZTM Initialization Error:', error);
const errorDiv = document.createElement('div');
errorDiv.textContent = 'Error initializing MZ Tactics Manager. Check console for details.';
errorDiv.style.cssText = 'color:red; padding:10px; border:1px solid red; margin:10px;';
insertAfterElement(errorDiv, tacticsBox);
}
}
window.addEventListener('load', initialize);
})();