MZ Tactics Manager

Userscript to manage tactics in ManagerZone

安装此脚本
作者推荐脚本

您可能也喜欢ylOppTacticsPreview (Modified)

安装此脚本
  1. // ==UserScript==
  2. // @name MZ Tactics Manager
  3. // @namespace douglaskampl
  4. // @version 13.3.0
  5. // @description Userscript to manage tactics in ManagerZone
  6. // @author Douglas Vieira
  7. // @match https://www.managerzone.com/?p=tactics
  8. // @match https://www.managerzone.com/?p=national_teams&sub=tactics&type=*
  9. // @icon https://yt3.googleusercontent.com/ytc/AIdro_mDHaJkwjCgyINFM7cdUV2dWPPnL9Q58vUsrhOmRqkatg=s160-c-k-c0x00ffffff-no-rj
  10. // @grant GM_getValue
  11. // @grant GM_setValue
  12. // @grant GM_deleteValue
  13. // @grant GM_addStyle
  14. // @run-at document-idle
  15. // @license MIT
  16. // ==/UserScript==
  17.  
  18. (function () {
  19. 'use strict';
  20.  
  21. !function (r, t) { "object" == typeof exports && "undefined" != typeof module ? module.exports = t() : "function" == typeof define && define.amd ? define(t) : (r = "undefined" != typeof globalThis ? globalThis : r || self).jsSHA = t() }(this, (function () { "use strict"; var r = function (t, n) { return r = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (r, t) { r.__proto__ = t } || function (r, t) { for (var n in t) Object.prototype.hasOwnProperty.call(t, n) && (r[n] = t[n]) }, r(t, n) }; "function" == typeof SuppressedError && SuppressedError; var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", n = "ARRAYBUFFER not supported by this environment", i = "UINT8ARRAY not supported by this environment"; function e(r, t, n, i) { var e, o, u, s = t || [0], f = (n = n || 0) >>> 3, h = -1 === i ? 3 : 0; for (e = 0; e < r.length; e += 1)o = (u = e + f) >>> 2, s.length <= o && s.push(0), s[o] |= r[e] << 8 * (h + i * (u % 4)); return { value: s, binLen: 8 * r.length + n } } function o(r, o, u) { switch (o) { case "UTF8": case "UTF16BE": case "UTF16LE": break; default: throw new Error("encoding must be UTF8, UTF16BE, or UTF16LE") }switch (r) { case "HEX": return function (r, t, n) { return function (r, t, n, i) { var e, o, u, s; if (0 != r.length % 2) throw new Error("String of HEX type must be in byte increments"); var f = t || [0], h = (n = n || 0) >>> 3, a = -1 === i ? 3 : 0; for (e = 0; e < r.length; e += 2) { if (o = parseInt(r.substr(e, 2), 16), isNaN(o)) throw new Error("String of HEX type contains invalid characters"); for (u = (s = (e >>> 1) + h) >>> 2; f.length <= u;)f.push(0); f[u] |= o << 8 * (a + i * (s % 4)) } return { value: f, binLen: 4 * r.length + n } }(r, t, n, u) }; case "TEXT": return function (r, t, n) { return function (r, t, n, i, e) { var o, u, s, f, h, a, c, w, E = 0, v = n || [0], l = (i = i || 0) >>> 3; if ("UTF8" === t) for (c = -1 === e ? 3 : 0, s = 0; s < r.length; s += 1)for (u = [], 128 > (o = r.charCodeAt(s)) ? u.push(o) : 2048 > o ? (u.push(192 | o >>> 6), u.push(128 | 63 & o)) : 55296 > o || 57344 <= o ? u.push(224 | o >>> 12, 128 | o >>> 6 & 63, 128 | 63 & o) : (s += 1, o = 65536 + ((1023 & o) << 10 | 1023 & r.charCodeAt(s)), u.push(240 | o >>> 18, 128 | o >>> 12 & 63, 128 | o >>> 6 & 63, 128 | 63 & o)), f = 0; f < u.length; f += 1) { for (h = (a = E + l) >>> 2; v.length <= h;)v.push(0); v[h] |= u[f] << 8 * (c + e * (a % 4)), E += 1 } else for (c = -1 === e ? 2 : 0, w = "UTF16LE" === t && 1 !== e || "UTF16LE" !== t && 1 === e, s = 0; s < r.length; s += 1) { for (o = r.charCodeAt(s), !0 === w && (o = (f = 255 & o) << 8 | o >>> 8), h = (a = E + l) >>> 2; v.length <= h;)v.push(0); v[h] |= o << 8 * (c + e * (a % 4)), E += 2 } return { value: v, binLen: 8 * E + i } }(r, o, t, n, u) }; case "B64": return function (r, n, i) { return function (r, n, i, e) { var o, u, s, f, h, a, c = 0, w = n || [0], E = (i = i || 0) >>> 3, v = -1 === e ? 3 : 0, l = r.indexOf("="); if (-1 === r.search(/^[a-zA-Z0-9=+/]+$/)) throw new Error("Invalid character in base-64 string"); if (r = r.replace(/=/g, ""), -1 !== l && l < r.length) throw new Error("Invalid '=' found in base-64 string"); for (o = 0; o < r.length; o += 4) { for (f = r.substr(o, 4), s = 0, u = 0; u < f.length; u += 1)s |= t.indexOf(f.charAt(u)) << 18 - 6 * u; for (u = 0; u < f.length - 1; u += 1) { for (h = (a = c + E) >>> 2; w.length <= h;)w.push(0); w[h] |= (s >>> 16 - 8 * u & 255) << 8 * (v + e * (a % 4)), c += 1 } } return { value: w, binLen: 8 * c + i } }(r, n, i, u) }; case "BYTES": return function (r, t, n) { return function (r, t, n, i) { var e, o, u, s, f = t || [0], h = (n = n || 0) >>> 3, a = -1 === i ? 3 : 0; for (o = 0; o < r.length; o += 1)e = r.charCodeAt(o), u = (s = o + h) >>> 2, f.length <= u && f.push(0), f[u] |= e << 8 * (a + i * (s % 4)); return { value: f, binLen: 8 * r.length + n } }(r, t, n, u) }; case "ARRAYBUFFER": try { new ArrayBuffer(0) } catch (r) { throw new Error(n) } return function (r, t, n) { return function (r, t, n, i) { return e(new Uint8Array(r), t, n, i) }(r, t, n, u) }; case "UINT8ARRAY": try { new Uint8Array(0) } catch (r) { throw new Error(i) } return function (r, t, n) { return e(r, t, n, u) }; default: throw new Error("format must be HEX, TEXT, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY") } } function u(r, e, o, u) { switch (r) { case "HEX": return function (r) { return function (r, t, n, i) { var e, o, u = "0123456789abcdef", s = "", f = t / 8, h = -1 === n ? 3 : 0; for (e = 0; e < f; e += 1)o = r[e >>> 2] >>> 8 * (h + n * (e % 4)), s += u.charAt(o >>> 4 & 15) + u.charAt(15 & o); return i.outputUpper ? s.toUpperCase() : s }(r, e, o, u) }; case "B64": return function (r) { return function (r, n, i, e) { var o, u, s, f, h, a = "", c = n / 8, w = -1 === i ? 3 : 0; for (o = 0; o < c; o += 3)for (f = o + 1 < c ? r[o + 1 >>> 2] : 0, h = o + 2 < c ? r[o + 2 >>> 2] : 0, s = (r[o >>> 2] >>> 8 * (w + i * (o % 4)) & 255) << 16 | (f >>> 8 * (w + i * ((o + 1) % 4)) & 255) << 8 | h >>> 8 * (w + i * ((o + 2) % 4)) & 255, u = 0; u < 4; u += 1)a += 8 * o + 6 * u <= n ? t.charAt(s >>> 6 * (3 - u) & 63) : e.b64Pad; return a }(r, e, o, u) }; case "BYTES": return function (r) { return function (r, t, n) { var i, e, o = "", u = t / 8, s = -1 === n ? 3 : 0; for (i = 0; i < u; i += 1)e = r[i >>> 2] >>> 8 * (s + n * (i % 4)) & 255, o += String.fromCharCode(e); return o }(r, e, o) }; case "ARRAYBUFFER": try { new ArrayBuffer(0) } catch (r) { throw new Error(n) } return function (r) { return function (r, t, n) { var i, e = t / 8, o = new ArrayBuffer(e), u = new Uint8Array(o), s = -1 === n ? 3 : 0; for (i = 0; i < e; i += 1)u[i] = r[i >>> 2] >>> 8 * (s + n * (i % 4)) & 255; return o }(r, e, o) }; case "UINT8ARRAY": try { new Uint8Array(0) } catch (r) { throw new Error(i) } return function (r) { return function (r, t, n) { var i, e = t / 8, o = -1 === n ? 3 : 0, u = new Uint8Array(e); for (i = 0; i < e; i += 1)u[i] = r[i >>> 2] >>> 8 * (o + n * (i % 4)) & 255; return u }(r, e, o) }; default: throw new Error("format must be HEX, B64, BYTES, ARRAYBUFFER, or UINT8ARRAY") } } var s = [1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298], f = [3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428], h = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225]; function a(r) { var t = { outputUpper: !1, b64Pad: "=", outputLen: -1 }, n = r || {}, i = "Output length must be a multiple of 8"; if (t.outputUpper = n.outputUpper || !1, n.b64Pad && (t.b64Pad = n.b64Pad), n.outputLen) { if (n.outputLen % 8 != 0) throw new Error(i); t.outputLen = n.outputLen } else if (n.shakeLen) { if (n.shakeLen % 8 != 0) throw new Error(i); t.outputLen = n.shakeLen } if ("boolean" != typeof t.outputUpper) throw new Error("Invalid outputUpper formatting option"); if ("string" != typeof t.b64Pad) throw new Error("Invalid b64Pad formatting option"); return t } function c(r, t) { return r >>> t | r << 32 - t } function w(r, t) { return r >>> t } function E(r, t, n) { return r & t ^ ~r & n } function v(r, t, n) { return r & t ^ r & n ^ t & n } function l(r) { return c(r, 2) ^ c(r, 13) ^ c(r, 22) } function p(r, t) { var n = (65535 & r) + (65535 & t); return (65535 & (r >>> 16) + (t >>> 16) + (n >>> 16)) << 16 | 65535 & n } function A(r, t, n, i) { var e = (65535 & r) + (65535 & t) + (65535 & n) + (65535 & i); return (65535 & (r >>> 16) + (t >>> 16) + (n >>> 16) + (i >>> 16) + (e >>> 16)) << 16 | 65535 & e } function d(r, t, n, i, e) { var o = (65535 & r) + (65535 & t) + (65535 & n) + (65535 & i) + (65535 & e); return (65535 & (r >>> 16) + (t >>> 16) + (n >>> 16) + (i >>> 16) + (e >>> 16) + (o >>> 16)) << 16 | 65535 & o } function y(r) { return c(r, 7) ^ c(r, 18) ^ w(r, 3) } function U(r) { return c(r, 6) ^ c(r, 11) ^ c(r, 25) } function T(r) { return "SHA-224" == r ? f.slice() : h.slice() } function b(r, t) { var n, i, e, o, u, f, h, a, T, b, R, m, F = []; for (n = t[0], i = t[1], e = t[2], o = t[3], u = t[4], f = t[5], h = t[6], a = t[7], R = 0; R < 64; R += 1)F[R] = R < 16 ? r[R] : A(c(m = F[R - 2], 17) ^ c(m, 19) ^ w(m, 10), F[R - 7], y(F[R - 15]), F[R - 16]), T = d(a, U(u), E(u, f, h), s[R], F[R]), b = p(l(n), v(n, i, e)), a = h, h = f, f = u, u = p(o, T), o = e, e = i, i = n, n = p(T, b); return t[0] = p(n, t[0]), t[1] = p(i, t[1]), t[2] = p(e, t[2]), t[3] = p(o, t[3]), t[4] = p(u, t[4]), t[5] = p(f, t[5]), t[6] = p(h, t[6]), t[7] = p(a, t[7]), t } return function (t) { function n(r, n, i) { var e = this; if ("SHA-224" !== r && "SHA-256" !== r) throw new Error("Chosen SHA variant is not supported"); var u = i || {}; return (e = t.call(this, r, n, i) || this).t = e.i, e.o = !0, e.u = -1, e.h = o(e.v, e.l, e.u), e.p = b, e.A = function (r) { return r.slice() }, e.U = T, e.T = function (t, n, i, e) { return function (r, t, n, i, e) { for (var o, u = 15 + (t + 65 >>> 9 << 4), s = t + n; r.length <= u;)r.push(0); for (r[t >>> 5] |= 128 << 24 - t % 32, r[u] = 4294967295 & s, r[u - 1] = s / 4294967296 | 0, o = 0; o < r.length; o += 16)i = b(r.slice(o, o + 16), i); return "SHA-224" === e ? [i[0], i[1], i[2], i[3], i[4], i[5], i[6]] : i }(t, n, i, e, r) }, e.R = T(r), e.m = 512, e.F = "SHA-224" === r ? 224 : 256, e.g = !1, u.hmacKey && e.B(function (r, t, n, i) { var e = r + " must include a value and format"; if (!t) { if (!i) throw new Error(e); return i } if (void 0 === t.value || !t.format) throw new Error(e); return o(t.format, t.encoding || "UTF8", n)(t.value) }("hmacKey", u.hmacKey, e.u)), e } return function (t, n) { if ("function" != typeof n && null !== n) throw new TypeError("Class extends value " + String(n) + " is not a constructor or null"); function i() { this.constructor = t } r(t, n), t.prototype = null === n ? Object.create(n) : (i.prototype = n.prototype, new i) }(n, t), n }(function () { function r(r, t, n) { var i = n || {}; if (this.v = t, this.l = i.encoding || "UTF8", this.numRounds = i.numRounds || 1, isNaN(this.numRounds) || this.numRounds !== parseInt(this.numRounds, 10) || 1 > this.numRounds) throw new Error("numRounds must a integer >= 1"); this.S = r, this.H = [], this.Y = 0, this.C = !1, this.I = 0, this.L = !1, this.N = [], this.X = [] } return r.prototype.update = function (r) { var t, n = 0, i = this.m >>> 5, e = this.h(r, this.H, this.Y), o = e.binLen, u = e.value, s = o >>> 5; for (t = 0; t < s; t += i)n + this.m <= o && (this.R = this.p(u.slice(t, t + i), this.R), n += this.m); return this.I += n, this.H = u.slice(n >>> 5), this.Y = o % this.m, this.C = !0, this }, r.prototype.getHash = function (r, t) { var n, i, e = this.F, o = a(t); if (this.g) { if (-1 === o.outputLen) throw new Error("Output length must be specified in options"); e = o.outputLen } var s = u(r, e, this.u, o); if (this.L && this.t) return s(this.t(o)); for (i = this.T(this.H.slice(), this.Y, this.I, this.A(this.R), e), n = 1; n < this.numRounds; n += 1)this.g && e % 32 != 0 && (i[i.length - 1] &= 16777215 >>> 24 - e % 32), i = this.T(i, e, 0, this.U(this.S), e); return s(i) }, r.prototype.setHMACKey = function (r, t, n) { if (!this.o) throw new Error("Variant does not support HMAC"); if (this.C) throw new Error("Cannot set MAC key after calling update"); var i = o(t, (n || {}).encoding || "UTF8", this.u); this.B(i(r)) }, r.prototype.B = function (r) { var t, n = this.m >>> 3, i = n / 4 - 1; if (1 !== this.numRounds) throw new Error("Cannot set numRounds with MAC"); if (this.L) throw new Error("MAC key already set"); for (n < r.binLen / 8 && (r.value = this.T(r.value, r.binLen, 0, this.U(this.S), this.F)); r.value.length <= i;)r.value.push(0); for (t = 0; t <= i; t += 1)this.N[t] = 909522486 ^ r.value[t], this.X[t] = 1549556828 ^ r.value[t]; this.R = this.p(this.N, this.R), this.I = this.m, this.L = !0 }, r.prototype.getHMAC = function (r, t) { var n = a(t); return u(r, this.F, this.u, n)(this.i()) }, r.prototype.i = function () { var r; if (!this.L) throw new Error("Cannot call getHMAC without first setting MAC key"); var t = this.T(this.H.slice(), this.Y, this.I, this.A(this.R), this.F); return r = this.p(this.X, this.U(this.S)), r = this.T(t, this.F, this.m, r, this.F) }, r }()) }));
  22.  
  23. const wakkanai = `@import url('https://api.fontshare.com/v2/css?f[]=satoshi@400,500,700&f[]=general-sans@400,500&display=swap');:root{--bg-color:#111827;--text-color:#F9FAFB;--primary-accent-color:#B163FF;--secondary-text-color:#94A3B8;--shadow-color-dark:rgba(0,0,0,0.25);--shadow-color-light:rgba(255,255,255,0.03);--style-accent-teal:#14B8A6;--style-accent-green:#22C55E;--style-accent-orange:#F97316;--style-accent-gray:#6B7280;--success-color:#22C55E;--error-color:#EF4444;--info-color:#3B82F6;--warning-color:#F59E0B;--border-color:rgba(148,163,184,0.1);--border-color-hover:rgba(148,163,184,0.2);--border-color-focus:var(--primary-accent-color);--input-bg-color:rgba(255,255,255,0.04);--input-bg-color-hover:rgba(255,255,255,0.06);--input-bg-color-focus:rgba(255,255,255,0.07);--button-secondary-bg:rgba(255,255,255,0.05);--button-secondary-bg-hover:rgba(255,255,255,0.08);--button-secondary-bg-active:rgba(0,0,0,0.05);--border-radius:8px;--shadow-base:3px 3px 8px var(--shadow-color-dark),-2px -2px 4px var(--shadow-color-light);--shadow-inset:inset 2px 2px 4px var(--shadow-color-dark),inset -2px -2px 4px var(--shadow-color-light);--shadow-concave:4px 4px 8px var(--shadow-color-dark),-4px -4px 8px var(--shadow-color-light),inset 1px 1px 2px var(--shadow-color-light),inset -1px -1px 2px var(--shadow-color-dark);}#mz_tactics_panel{font-family:"Satoshi",-apple-system,sans-serif;background-color:var(--bg-color);border-radius:12px;padding:16px 16px 4px 16px;margin:8px;box-shadow:var(--shadow-base);border:1px solid var(--border-color);transition:max-height 0.4s ease-out,padding 0.4s ease-out,margin 0.4s ease-out,opacity 0.3s ease-out;max-height:1000px;opacity:1;color:var(--text-color);overflow:visible;}#mz_tactics_panel.collapsed{max-height:0 !important;padding-top:0 !important;padding-bottom:0 !important;margin-top:0 !important;margin-bottom:0 !important;opacity:0 !important;border:none !important;overflow:hidden !important;}.mz-group{background-color:rgba(0,0,0,0.1);border-radius:var(--border-radius);padding:12px;margin:8px 0;box-shadow:none;border:1px solid var(--border-color);position:relative;transition:max-height 0.3s ease-out,padding 0.3s ease-out,margin 0.3s ease-out;overflow:visible;}.mz-group-main-title{display:flex;justify-content:space-between;align-items:center;color:var(--text-color);font-size:18px;font-weight:500;margin:-4px 0 12px 0;padding-bottom:8px;border-bottom:1px solid var(--border-color);}.mz-title-container{display:flex;align-items:center;gap:8px;flex-grow:1;flex-wrap:nowrap;min-width:0;}.mz-main-title{font-family:"Satoshi",sans-serif;font-size:20px;font-weight:700;margin:0;padding:0;letter-spacing:0.2px;white-space:nowrap;background:linear-gradient(to right,var(--primary-accent-color),#A78BFA);-webkit-background-clip:text;background-clip:text;color:transparent;}.mz-version-text{color:var(--primary-accent-color);opacity:0.7;font-size:0.9em;font-weight:400;margin-right:10px;white-space:nowrap;}.mz-divider{width:50px;height:1px;background:var(--border-color);margin:10px auto 0;opacity:0.5;}#toggle_panel_btn{background:transparent;border:none;color:var(--secondary-text-color);cursor:pointer;padding:8px;width:32px;height:32px;border-radius:50%;margin-left:auto;font-size:18px;transition:all 0.3s ease;display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;}#toggle_panel_btn:hover{background:rgba(255,255,255,0.05);color:var(--text-color);}#collapsed_icon{display:none;width:20px;height:18px;border-radius:50%;background:#1F2937;color:var(--secondary-text-color);font-size:9px;font-weight:bold;text-align:center;line-height:18px;cursor:pointer;transition:transform 0.3s ease,box-shadow 0.3s ease,opacity 0.3s ease;box-shadow:var(--shadow-base);border:1px solid var(--border-color);margin-left:8px;vertical-align:middle;flex-shrink:0;opacity:0;transform:scale(0.8);}#collapsed_icon.visible{display:inline-block;opacity:1;transform:scale(1);}#collapsed_icon:hover{transform:scale(1.1);box-shadow:0 0 10px rgba(139,92,246,0.3);color:var(--text-color);}#mz_tactics_panel .mzbtn{display:inline-flex;align-items:center;justify-content:center;padding:8px 14px;margin:4px;font-family:"Satoshi",sans-serif;font-size:13px;font-weight:500;color:var(--text-color);background:var(--button-secondary-bg);border:1px solid var(--border-color);border-radius:var(--border-radius);cursor:pointer;transition:all 0.2s ease;min-height:36px;box-shadow:0 1px 2px rgba(0,0,0,0.1);}#mz_tactics_panel .mzbtn:hover:not(:disabled){background:var(--button-secondary-bg-hover);border-color:var(--border-color-hover);transform:translateY(-1px);box-shadow:0 3px 6px rgba(0,0,0,0.15);}#mz_tactics_panel .mzbtn:active:not(:disabled){background:var(--button-secondary-bg-active);transform:translateY(0);box-shadow:inset 0 1px 2px rgba(0,0,0,0.2);}#mz_tactics_panel .mzbtn:disabled{opacity:0.5;cursor:not-allowed;}#mz_tactics_panel select{font-family:"Satoshi",sans-serif;font-size:14px;color:var(--text-color);padding:7px 13px;border:1px solid var(--border-color);border-radius:var(--border-radius);background-color:var(--input-bg-color);cursor:pointer;margin:0;transition:all 0.2s ease;-webkit-appearance:none;-moz-appearance:none;appearance:none;background-image:url("data:image/svg+xml;utf8,<svg fill='%2394A3B8' height='24' viewBox='0 0 24 24' width='24' xmlns='http://www.w3.org/2000/svg'><path d='M7 10l5 5 5-5z'/></svg>");background-repeat:no-repeat;background-position:right 10px top 50%;padding-right:30px;height:36px;box-sizing:border-box;}#mz_tactics_panel select:hover:not(:disabled){background:var(--input-bg-color-hover);border-color:var(--border-color-hover);}#mz_tactics_panel select:focus{outline:none;border-color:var(--border-color-focus);box-shadow:0 0 0 2px rgba(139,92,246,0.3);background:var(--input-bg-color-focus);}#mz_tactics_panel select option{background-color:#1F2937;color:var(--text-color);padding:5px 10px;}#mz_tactics_panel select:disabled{opacity:0.5;cursor:not-allowed;}.tactics-selector-section{margin-bottom:12px;}.tactics-selector-label{display:block;margin-bottom:5px;color:var(--secondary-text-color);font-size:12px;}.modal-info-wrapper{width:100%;max-width:550px;}.modal-tabs{display:flex;border-bottom:1px solid var(--border-color);margin-bottom:15px;}.modal-tab{padding:10px 15px;cursor:pointer;border:none;background:none;color:var(--secondary-text-color);opacity:0.8;border-bottom:2px solid transparent;transition:all 0.3s ease;font-family:"Satoshi",sans-serif;font-size:14px;font-weight:500;}.modal-tab:hover{opacity:1;color:var(--text-color);background-color:rgba(255,255,255,0.03);}.modal-tab.active{opacity:1;color:var(--primary-accent-color);border-bottom-color:var(--primary-accent-color);font-weight:600;}.modal-tab-content{display:none;padding:5px;max-height:40vh;overflow-y:auto;overflow-x:hidden;scrollbar-width:thin;scrollbar-color:var(--primary-accent-color) rgba(255,255,255,0.05);}#mz_tactics_panel .mztm-custom-select-list-container{background-color:#1F2937;}#mz_tactics_panel #category-selector option{background-color:#1F2937;}.modal-tab-content::-webkit-scrollbar{width:6px;}.modal-tab-content::-webkit-scrollbar-track{background:rgba(255,255,255,0.05);border-radius:3px;}.modal-tab-content::-webkit-scrollbar-thumb{background-color:var(--primary-accent-color);border-radius:3px;}.modal-tab-content.active{display:block;animation:fadeIn 0.5s ease;}.modal-tab-content[data-tab-id="links"] a{color:var(--info-color);}.faq-section h3{color:var(--primary-accent-color);margin-top:20px;margin-bottom:15px;font-size:16px;border-bottom:1px solid var(--border-color);padding-bottom:5px;}.faq-item{margin-bottom:15px;}.faq-item h4{font-weight:600;margin-bottom:5px;color:var(--text-color);font-size:14px;}.faq-item p{font-size:13px;line-height:1.5;color:var(--secondary-text-color);margin:0;}.faq-item code{background-color:var(--input-bg-color);padding:2px 5px;border-radius:4px;font-size:0.9em;color:var(--primary-accent-color);border:1px solid var(--border-color);}.info-modal-content a{color:var(--primary-accent-color);text-decoration:none;transition:color 0.3s ease;}.info-modal-content a:hover{color:var(--primary-accent-color);opacity:0.8;text-decoration:underline;}.info-modal-content ul{list-style:none;padding:0;}.info-modal-content ul li{margin:12px 0;padding:8px 12px;border-radius:var(--border-radius);background:var(--input-bg-color);border:1px solid var(--border-color);transition:all 0.3s ease;}.info-modal-content ul li:hover{background:var(--input-bg-color-hover);}#mz-modal-overlay{position:fixed;top:0;left:0;right:0;bottom:0;background-color:rgba(17,24,39,0.8);backdrop-filter:blur(4px);display:flex;align-items:center;justify-content:center;z-index:10000;opacity:0;transition:opacity 0.3s ease;}#mz-modal-container{background:var(--bg-color);border-radius:12px;padding:24px;box-shadow:0 10px 25px rgba(0,0,0,0.3);border:1px solid var(--border-color);max-width:550px;width:90%;transform:scale(0.9);transition:transform 0.3s ease;color:var(--text-color);font-family:"Satoshi",-apple-system,sans-serif;}#mz-modal-container.management-modal{max-width:700px;width:95%;}#mz-modal-overlay.active{opacity:1;}#mz-modal-overlay.active #mz-modal-container{transform:scale(1);}#mz-modal-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;border-bottom:none;padding-bottom:0;}#mz-modal-title{font-size:20px;font-weight:500;margin:0;}#mz-modal-close{background:transparent;border:none;color:var(--secondary-text-color);font-size:22px;cursor:pointer;transition:all 0.3s ease;padding:0;width:36px;height:36px;display:flex;align-items:center;justify-content:center;border-radius:50%;}#mz-modal-close:hover{background:rgba(255,255,255,0.05);color:var(--error-color);}#mz-modal-content{margin-bottom:24px;white-space:pre-line;line-height:1.5;color:var(--secondary-text-color);}#mz-modal-input{width:calc(100% - 32px);background:var(--input-bg-color);border:1px solid var(--border-color);color:var(--text-color);padding:14px 16px;border-radius:var(--border-radius);font-family:"Satoshi",sans-serif;font-size:15px;margin-bottom:20px;transition:all 0.3s ease;box-sizing:border-box;}#mz-modal-input:focus{outline:none;border-color:var(--border-color-focus);box-shadow:0 0 0 2px rgba(139,92,246,0.3);background:var(--input-bg-color-focus);}.mz-modal-label{display:block;margin-bottom:8px;font-size:14px;color:var(--text-color);opacity:0.9;margin-top:10px;}#mz-modal-description{width:calc(100% - 0);background:var(--input-bg-color);border:1px solid var(--border-color);color:var(--text-color);padding:12px 16px;border-radius:var(--border-radius);font-family:"Satoshi",sans-serif;font-size:14px;margin-bottom:20px;transition:all 0.3s ease;box-sizing:border-box;resize:vertical;min-height:60px;}#mz-modal-description:focus{outline:none;border-color:var(--border-color-focus);box-shadow:0 0 0 2px rgba(139,92,246,0.3);background:var(--input-bg-color-focus);}#mz-modal-buttons{display:flex;justify-content:flex-start;gap:12px;margin-top:15px;}.mz-modal-btn{display:inline-flex;align-items:center;justify-content:center;padding:10px 18px;font-family:"Satoshi",sans-serif;font-size:15px;font-weight:500;color:var(--text-color);background:var(--button-secondary-bg);border:1px solid var(--border-color);border-radius:var(--border-radius);cursor:pointer;transition:all 0.2s ease;min-width:90px;box-shadow:0 1px 2px rgba(0,0,0,0.1);}.mz-modal-btn:hover{background:var(--button-secondary-bg-hover);border-color:var(--border-color-hover);transform:translateY(-1px);box-shadow:0 3px 6px rgba(0,0,0,0.15);}.mz-modal-btn:active{background:var(--button-secondary-bg-active);transform:translateY(0);box-shadow:inset 0 1px 2px rgba(0,0,0,0.2);}.mz-modal-btn.primary{background:var(--primary-accent-color);color:#ffffff;font-weight:500;border:none;}.mz-modal-btn.primary:hover{background-color:#7C3AED;}.mz-modal-btn.cancel{background:transparent;color:var(--secondary-text-color);border:1px solid var(--border-color);}.mz-modal-btn.cancel:hover{background:rgba(255,255,255,0.03);color:var(--text-color);border-color:var(--border-color-hover);}.mz-modal-icon{display:inline-flex;align-items:center;justify-content:center;width:36px;height:36px;border-radius:50%;margin-right:14px;font-weight:bold;font-size:1.2em;}.mz-modal-icon.success{color:var(--success-color);background:rgba(34,197,94,0.1);}.mz-modal-icon.error{color:var(--error-color);background:rgba(239,68,68,0.1);}.mz-modal-icon.info{color:var(--info-color);background:rgba(59,130,246,0.1);}.mz-modal-title-with-icon{display:flex;align-items:center;}.formations-controls-container{display:flex;flex-wrap:nowrap;gap:8px;margin-top:0;align-items:center;}.tactics-search-box{width:140px !important;padding:8px 12px;margin-bottom:0 !important;border:1px solid var(--border-color);border-radius:var(--border-radius);background-color:var(--input-bg-color);color:var(--text-color);font-family:"Satoshi",sans-serif;font-size:14px;box-sizing:border-box;height:36px;transition:all 0.2s ease;position:relative;flex-shrink:0;}.tactics-search-box:focus{outline:none;border-color:var(--border-color-focus);box-shadow:0 0 0 2px rgba(139,92,246,0.3);background:var(--input-bg-color-focus);}.tactics-search-box.filtering{border-bottom:2px solid var(--primary-accent-color);animation:pulse-border 1.5s infinite;}@keyframes pulse-border{0%{border-color:var(--primary-accent-color);}50%{border-color:transparent;}100%{border-color:var(--primary-accent-color);}}.category-filter-wrapper{display:flex;align-items:center;gap:4px;flex-shrink:0;}#category_filter_selector{min-width:140px;flex-grow:0;}#manage_items_btn{padding:4px 8px;min-width:auto;height:36px;font-size:14px;line-height:1;flex-shrink:0;color:var(--secondary-text-color);}#manage_items_btn:hover{color:var(--text-color);}.mztm-custom-select-wrapper{position:relative;flex:1;min-width:180px;flex-grow:1;flex-shrink:1;}.mztm-custom-select-trigger{display:flex;align-items:center;justify-content:space-between;font-family:"Satoshi",sans-serif;font-size:14px;color:var(--text-color);padding:8px 14px;border:1px solid var(--border-color);border-radius:var(--border-radius);background-color:var(--input-bg-color);cursor:pointer;margin:0;transition:all 0.2s ease;height:36px;box-sizing:border-box;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;}.mztm-custom-select-trigger:hover:not(.disabled){background:var(--input-bg-color-hover);border-color:var(--border-color-hover);}.mztm-custom-select-trigger.open{border-color:var(--border-color-focus);box-shadow:0 0 0 2px rgba(139,92,246,0.3);border-bottom-left-radius:0;border-bottom-right-radius:0;background:var(--input-bg-color-focus);}.mztm-custom-select-trigger.disabled{opacity:0.5;cursor:not-allowed;}.mztm-custom-select-trigger::after{content:'';border:solid var(--secondary-text-color);border-width:0 2px 2px 0;display:inline-block;padding:3px;transform:rotate(45deg);-webkit-transform:rotate(45deg);margin-left:10px;flex-shrink:0;transition:border-color 0.2s ease;}.mztm-custom-select-trigger:hover:not(.disabled)::after{border-color:var(--text-color);}.mztm-custom-select-trigger.open::after{transform:rotate(-135deg);-webkit-transform:rotate(-135deg);margin-top:3px;}.mztm-custom-select-placeholder{color:var(--secondary-text-color);font-style:italic;}.mztm-custom-select-list-container{position:absolute;top:100%;left:0;right:0;background-color:#1F2937;border:1px solid var(--border-color-focus);border-top:none;border-radius:0 0 8px 8px;z-index:1001;max-height:250px;overflow-y:auto;box-shadow:0 5px 10px rgba(0,0,0,0.2);display:none;scrollbar-width:thin;scrollbar-color:var(--primary-accent-color) rgba(255,255,255,0.05);}.mztm-custom-select-list-container.open{display:block;animation:fadeIn 0.2s ease-out;}.mztm-custom-select-list-container::-webkit-scrollbar{width:6px;}.mztm-custom-select-list-container::-webkit-scrollbar-track{background:rgba(255,255,255,0.05);border-radius:3px;}.mztm-custom-select-list-container::-webkit-scrollbar-thumb{background-color:var(--primary-accent-color);border-radius:3px;}.mztm-custom-select-list{list-style:none;padding:0;margin:0;}.mztm-custom-select-category{color:var(--primary-accent-color);font-size:11px;font-weight:600;padding:6px 12px;background:rgba(0,0,0,0.2);margin-top:2px;border-top:1px solid var(--border-color);border-bottom:1px solid var(--border-color);cursor:default;text-transform:uppercase;letter-spacing:0.5px;}.mztm-custom-select-item{padding:8px 12px;cursor:pointer;transition:background-color 0.15s ease,color 0.15s ease;font-size:14px;color:var(--text-color);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}.mztm-custom-select-item:hover,.mztm-custom-select-item.highlighted{background-color:var(--primary-accent-color);color:#ffffff;}.mztm-custom-select-item.disabled{opacity:0.5;cursor:default;background-color:transparent !important;color:var(--secondary-text-color) !important;}.mztm-custom-select-item.hidden{display:none;}.mztm-custom-select-no-results{padding:10px 12px;color:var(--secondary-text-color);font-style:italic;cursor:default;}.tactics-style-indicator{display:inline-block;width:8px;height:8px;border-radius:50%;margin-right:6px;}.tactics-style-indicator.accent-teal{background-color:var(--style-accent-teal);}.tactics-style-indicator.accent-green{background-color:var(--style-accent-green);}.tactics-style-indicator.accent-orange{background-color:var(--style-accent-orange);}.tactics-style-indicator.accent-gray{background-color:var(--style-accent-gray);}#category-selector{width:75%;padding:10px 12px;border:1px solid var(--border-color);border-radius:var(--border-radius);background-color:var(--input-bg-color);color:var(--text-color);font-family:"Satoshi",sans-serif;font-size:13px;box-sizing:border-box;}#category-selector option{padding:8px;background-color:#1F2937;}.category-selection-container{margin-bottom:10px;}.category-selection-label{display:block;margin-bottom:5px;font-size:14px;color:var(--text-color);opacity:0.9;}.new-category-input-container{margin-top:10px;display:none;}.new-category-input-container.visible{display:block;}#new-category-input{width:100%;padding:10px 12px;border:1px solid var(--border-color);border-radius:var(--border-radius);background-color:var(--input-bg-color);color:var(--text-color);font-family:"Satoshi",sans-serif;font-size:14px;box-sizing:border-box;}#new-category-input:focus{outline:none;border-color:var(--border-color-focus);box-shadow:0 0 0 2px rgba(139,92,246,0.3);background:var(--input-bg-color-focus);}@keyframes fadeIn{from{opacity:0;transform:translateY(-5px);}to{opacity:1;transform:translateY(0);}}@keyframes shake{0%,100%{transform:translateX(0);}25%{transform:translateX(-2px);}50%{transform:translateX(0);}75%{transform:translateX(2px);}}.mztm-custom-select-wrapper.filtering .mztm-custom-select-trigger{border-color:var(--primary-accent-color);animation:pulse-border 1.5s infinite;}.action-buttons-section{display:flex;flex-direction:column;flex-wrap:nowrap;margin-top:10px;gap:4px;}.action-buttons-row{display:flex;flex-wrap:wrap;gap:6px;width:100%;}.footer-actions{position:absolute;bottom:10px;right:16px;background:transparent !important;border:none !important;box-shadow:none !important;font-family:"General Sans",sans-serif !important;color:gold !important;opacity:0.8;transition:opacity 0.2s ease;}.footer-actions:hover{opacity:1;transform:none !important;}#manage_action_dropdown_menu{max-height:200px;overflow-y:auto;overflow-x:hidden;}#loading-overlay{position:fixed;top:0;left:0;width:100%;height:100%;background-color:rgba(17,24,39,0.7);backdrop-filter:blur(3px);display:flex;justify-content:center;align-items:center;z-index:10001;opacity:0;transition:opacity 0.3s ease;pointer-events:none;}#loading-overlay.visible{opacity:1;pointer-events:auto;}#loading-spinner{border:4px solid rgba(255,255,255,0.1);border-left-color:var(--primary-accent-color);border-radius:50%;width:40px;height:40px;animation:spin 1s linear infinite;}@keyframes spin{to{transform:rotate(360deg);}}.mode-toggle-container{display:flex;align-items:center;margin:0 10px 0 30px;white-space:nowrap;}.mode-toggle-switch{position:relative;display:inline-block;width:44px;height:22px;margin:0 10px;vertical-align:middle;}.mode-toggle-switch input{opacity:0;width:0;height:0;}.mode-toggle-slider{position:absolute;cursor:pointer;top:0;left:0;right:0;bottom:0;background-color:#4B5563;transition:0.4s;border-radius:22px;border:1px solid var(--border-color);}.mode-toggle-slider:before{position:absolute;content:"";height:16px;width:16px;left:3px;bottom:2px;background-color:white;transition:0.4s;border-radius:50%;}.mode-toggle-switch input:checked + .mode-toggle-slider{background-color:var(--primary-accent-color);}.mode-toggle-switch input:checked + .mode-toggle-slider:before{transform:translateX(22px);}.mode-toggle-label{font-size:12px;vertical-align:middle;color:var(--secondary-text-color);opacity:0.8;transition:opacity 0.2s ease,color 0.2s ease;}.mode-toggle-label.active{opacity:1;color:var(--text-color);font-weight:500;}.section-content{position:relative;padding-bottom:2px;overflow:visible;}.management-modal-wrapper{width:100%;}.management-modal-content{display:none;padding:5px;max-height:50vh;overflow-y:auto;overflow-x:hidden;scrollbar-width:thin;scrollbar-color:var(--primary-accent-color) rgba(255,255,255,0.05);}.management-modal-content::-webkit-scrollbar{width:8px;}.management-modal-content::-webkit-scrollbar-track{background:rgba(255,255,255,0.05);border-radius:4px;}.management-modal-content::-webkit-scrollbar-thumb{background-color:var(--primary-accent-color);border-radius:4px;}.management-modal-content.active{display:block;animation:fadeIn 0.5s ease;}.formation-management-list,.category-management-list{list-style:none;padding:0;margin:10px 0 0 0;}.formation-management-list li,.category-management-list li{display:flex;justify-content:space-between;align-items:center;padding:10px 5px;border-bottom:1px solid var(--border-color);transition:background-color 0.2s ease;}.formation-management-list li:last-child,.category-management-list li:last-child{border-bottom:none;}.item-name-container{flex-grow:1;margin-right:10px;display:flex;align-items:center;min-width:0;}.item-name{flex-grow:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text-color);}.item-name-input{flex-grow:1;background:var(--input-bg-color-hover);border:1px solid var(--border-color-hover);color:var(--text-color);padding:4px 8px;border-radius:4px;font-family:"Satoshi",sans-serif;font-size:14px;margin-right:5px;}.item-name-input:focus{outline:none;border-color:var(--border-color-focus);box-shadow:0 0 0 2px rgba(139,92,246,0.3);}.item-controls{display:flex;align-items:center;gap:8px;flex-shrink:0;}.item-category-select{padding:4px 8px !important;height:30px !important;font-size:12px !important;min-width:120px;background-position:right 5px top 50%;padding-right:25px !important;flex-shrink:0;background-color:var(--input-bg-color);border-color:var(--border-color);color:var(--secondary-text-color);}.item-category-select:hover{background-color:var(--input-bg-color-hover);border-color:var(--border-color-hover);color:var(--text-color);}.item-action-btn{background:transparent;border:none;color:var(--secondary-text-color);opacity:0.7;cursor:pointer;font-size:16px;padding:4px;transition:opacity 0.2s ease,color 0.2s ease;line-height:1;}.item-action-btn:hover{opacity:1;color:var(--text-color);}.save-name-btn{color:var(--success-color);}.cancel-name-btn{color:var(--error-color);}.delete-item-btn{color:var(--error-color);}.delete-item-btn:hover{color:var(--error-color);}.add-category-section{display:flex;gap:8px;padding:10px 5px;border-bottom:1px solid var(--border-color);margin-bottom:10px;}.add-category-input{flex-grow:1;background:var(--input-bg-color);border:1px solid var(--border-color);color:var(--text-color);padding:8px 12px;border-radius:var(--border-radius);font-family:"Satoshi",sans-serif;font-size:14px;}.add-category-input:focus{outline:none;border-color:var(--border-color-focus);box-shadow:0 0 0 2px rgba(139,92,246,0.3);background:var(--input-bg-color-focus);}.add-category-btn{padding:8px 15px !important;font-size:14px !important;min-width:auto !important;background:var(--primary-accent-color) !important;color:white !important;border:none !important;}.add-category-btn:hover{background:#7C3AED !important;transform:none !important;box-shadow:none !important;}.category-management-list li span{flex-grow:1;margin-right:10px;color:var(--text-color);}.category-remove-btn{background-color:rgba(239,68,68,0.1) !important;border:1px solid rgba(239,68,68,0.3) !important;color:var(--error-color) !important;padding:5px 10px !important;min-width:auto !important;font-size:13px !important;}.category-remove-btn:hover{background-color:rgba(239,68,68,0.2) !important;border-color:rgba(239,68,68,0.5) !important;color:#FECACA !important;transform:none !important;box-shadow:none !important;}.no-items-message,.no-custom-categories-message{padding:15px;text-align:center;color:var(--secondary-text-color);}#mztm-tactic-preview{position:fixed;z-index:10002;background-color:#1F2937;color:var(--text-color);border:1px solid var(--border-color-hover);border-radius:var(--border-radius);padding:10px 15px;font-family:"Satoshi",sans-serif;font-size:13px;box-shadow:0 4px 12px rgba(0,0,0,0.2);max-width:250px;pointer-events:none;line-height:1.5;opacity:0;transition:opacity 0.2s ease-in-out;white-space:normal;display:none;}.mztm-preview-formation{margin-bottom:8px;padding-bottom:6px;border-bottom:1px solid var(--border-color);font-size:14px;}.mztm-preview-formation strong{color:var(--primary-accent-color);font-weight:500;}.mztm-preview-desc{max-height:150px;overflow-y:auto;word-wrap:break-word;scrollbar-width:thin;color:var(--secondary-text-color);scrollbar-color:var(--primary-accent-color) rgba(255,255,255,0.05);}.mztm-preview-desc::-webkit-scrollbar{width:4px;}.mztm-preview-desc::-webkit-scrollbar-track{background:rgba(255,255,255,0.05);border-radius:2px;}.mztm-preview-desc::-webkit-scrollbar-thumb{background-color:var(--primary-accent-color);border-radius:2px;}.mztm-preview-no-desc{color:var(--secondary-text-color);opacity:0.7;font-style:italic;}`;
  24. GM_addStyle(wakkanai);
  25.  
  26. const OUTFIELD_PLAYERS_SELECTOR = '.fieldpos.fieldpos-ok.ui-draggable:not(.substitute):not(.goalkeeper):not(.substitute.goalkeeper), .fieldpos.fieldpos-collision.ui-draggable:not(.substitute):not(.goalkeeper):not(.substitute.goalkeeper)';
  27. const GOALKEEPER_SELECTOR = '.fieldpos.fieldpos-ok.goalkeeper.ui-draggable';
  28. const FORMATION_TEXT_SELECTOR = '#formation_text';
  29. const TACTIC_SLOT_SELECTOR = '.ui-state-default.ui-corner-top.ui-tabs-selected.ui-state-active.invalid';
  30. const MIN_PLAYERS_ON_PITCH = 11;
  31. const MAX_TACTIC_NAME_LENGTH = 50;
  32. const MAX_CATEGORY_NAME_LENGTH = 30;
  33. const MAX_DESCRIPTION_LENGTH = 250;
  34. const SCRIPT_VERSION = '13.3.0';
  35. const DISPLAY_VERSION = '13.3';
  36. const SCRIPT_NAME = 'MZ Tactics Manager';
  37. const VERSION_KEY = 'mz_tactics_version';
  38. const COLLAPSED_KEY = 'mz_tactics_collapsed';
  39. const VIEW_MODE_KEY = 'mztm_view_mode';
  40. const CATEGORIES_STORAGE_KEY = 'mz_tactics_categories';
  41. const FORMATIONS_STORAGE_KEY = 'mztm_formations';
  42. const OLD_FORMATIONS_STORAGE_KEY = 'ls_tactics';
  43. const COMPLETE_TACTICS_STORAGE_KEY = 'mztm_complete_tactics';
  44. const ROSTER_CACHE_KEY = 'mztm_roster_cache';
  45. const USER_INFO_CACHE_KEY = 'mztm_user_info_cache';
  46. const CATEGORY_FILTER_STORAGE_KEY = 'mztm_last_category_filter';
  47. const ROSTER_CACHE_DURATION_MS = 3600000;
  48. const USER_INFO_CACHE_DURATION_MS = 86400000;
  49. const DEFAULT_CATEGORIES = {
  50. 'short_passing': {
  51. id: 'short_passing',
  52. name: 'Short Passing',
  53. color: '#54a0ff'
  54. },
  55. 'wing_play': {
  56. id: 'wing_play',
  57. name: 'Wing Play',
  58. color: '#5dd39e'
  59. }
  60. };
  61. const NEW_CATEGORY_ID = 'new_category';
  62. const OTHER_CATEGORY_ID = 'other';
  63. const USERSCRIPT_STRINGS = {
  64. addButton: 'Add',
  65. addCurrentTactic: 'Add Current',
  66. addWithXmlButton: 'Add via XML',
  67. manageButton: 'Manage',
  68. deleteButton: 'Delete',
  69. renameButton: 'Edit',
  70. updateButton: 'Update Coords',
  71. clearButton: 'Clear',
  72. resetButton: 'Reset',
  73. importButton: 'Import',
  74. exportButton: 'Export',
  75. infoButton: 'FAQ',
  76. saveButton: 'Save',
  77. tacticNamePrompt: 'Please enter a name and a category',
  78. addAlert: 'Formation {} added successfully.',
  79. deleteAlert: 'Item {} deleted successfully.',
  80. renameAlert: 'Item {} successfully edited.',
  81. updateAlert: 'Formation {} updated successfully.',
  82. clearAlert: 'Formations cleared successfully.',
  83. resetAlert: 'Default formations reset successfully.',
  84. importAlert: 'Formations imported successfully.',
  85. exportAlert: 'Formations JSON copied to clipboard.',
  86. deleteConfirmation: 'Do you really want to delete {}?',
  87. updateConfirmation: 'Do you really want to update {} coords?',
  88. clearConfirmation: 'Do you really want to clear all saved formations?',
  89. resetConfirmation: 'Reset to default formations? This will remove all your custom formations.',
  90. invalidTacticError: 'Invalid formation. Ensure 11 players are on the pitch.',
  91. noTacticNameProvidedError: 'No name provided.',
  92. alreadyExistingTacticNameError: 'Name already exists.',
  93. tacticNameMaxLengthError: `Name is too long (max ${MAX_TACTIC_NAME_LENGTH} chars).`,
  94. noTacticSelectedError: 'No item selected.',
  95. duplicateTacticError: 'This formation already exists.',
  96. duplicateTacticErrorWithName: 'This formation already exists (name: {}).',
  97. noChangesMadeError: 'No changes detected in player positions.',
  98. invalidImportError: 'Invalid import data. Please provide valid JSON.',
  99. modalContentInfoText: 'MZ Tactics Manager by douglaskampl.',
  100. modalContentFeedbackText: 'For feedback or suggestions, contact via GB/Chat.',
  101. usefulContent: '',
  102. tacticsDropdownMenuLabel: 'Select a Formation',
  103. completeTacticsDropdownMenuLabel: 'Select a Tactic',
  104. errorTitle: 'Error',
  105. doneTitle: 'Success',
  106. confirmationTitle: 'Confirmation',
  107. deleteTacticConfirmButton: 'Delete',
  108. cancelConfirmButton: 'Cancel',
  109. updateConfirmButton: 'Update',
  110. clearTacticsConfirmButton: 'Clear',
  111. resetTacticsConfirmButton: 'Reset',
  112. addConfirmButton: 'Add',
  113. xmlValidationError: 'Invalid XML format',
  114. xmlParsingError: 'Error parsing XML',
  115. xmlPlaceholder: 'Paste Formation XML here',
  116. tacticNamePlaceholder: 'Formation name',
  117. managerTitle: SCRIPT_NAME,
  118. searchPlaceholder: 'Search...',
  119. allTacticsFilter: 'All',
  120. noTacticsFound: 'No formations found',
  121. welcomeMessage: `Script updated to v${DISPLAY_VERSION}.\n\nChange in this version:\n Internalized script dependencies to resolve issues that some users reported.\n\nEnjoy!`,
  122. welcomeGotIt: 'Got it!',
  123. removeCategoryConfirmation: 'Remove category "{}"? (All formations in this category will be moved to "Other").',
  124. removeCategoryAlert: 'Category "{}" removed successfully.',
  125. removeCategoryButton: 'Remove',
  126. completeTacticsTitle: 'Tactics Management',
  127. saveCompleteTacticButton: 'Save Current',
  128. loadCompleteTacticButton: 'Load',
  129. deleteCompleteTacticButton: 'Delete',
  130. renameCompleteTacticButton: 'Rename',
  131. updateCompleteTacticButton: 'Update with Current',
  132. importCompleteTacticsButton: 'Import',
  133. exportCompleteTacticsButton: 'Export',
  134. completeTacticNamePrompt: 'Please enter a name for the tactic',
  135. renameCompleteTacticPrompt: 'Enter a new name for the tactic:',
  136. updateCompleteTacticConfirmation: 'Overwrite tactic "{}" with the current setup (positions, rules, settings) from the pitch?',
  137. completeTacticSaveSuccess: 'Tactic {} saved successfully.',
  138. completeTacticLoadSuccess: 'Tactic {} loaded successfully.',
  139. completeTacticDeleteSuccess: 'Tactic {} deleted successfully.',
  140. completeTacticRenameSuccess: 'Tactic renamed to {} successfully.',
  141. completeTacticUpdateSuccess: 'Tactic {} updated successfully.',
  142. importCompleteTacticsTitle: 'Import Tactics (JSON)',
  143. exportCompleteTacticsTitle: 'Export Tactics (JSON)',
  144. importCompleteTacticsPlaceholder: 'Paste Tactics JSON here',
  145. importCompleteTacticsAlert: 'Tactics imported successfully.',
  146. exportCompleteTacticsAlert: 'Tactics JSON copied to clipboard.',
  147. invalidCompleteImportError: 'Invalid import data. Please provide valid JSON (object map).',
  148. errorFetchingRoster: 'Error fetching team roster. Cannot load Tactic.',
  149. errorInsufficientPlayers: 'Not enough available players in roster to fill required positions.',
  150. errorXmlExportParse: 'Error parsing XML from native export.',
  151. errorXmlGenerate: 'Error generating XML for import.',
  152. errorImportFailed: 'Native import failed. Check XML validity or player availability.',
  153. warningPlayersSubstituted: 'Warning: roster mismatch. Some were players replaced at random. Tactic updated!',
  154. invalidXmlForImport: 'MZ rejected the generated XML. It might be invalid or player assignments failed.',
  155. completeTacticNamePlaceholder: 'Tactic name',
  156. normalModeLabel: 'Formations',
  157. completeModeLabel: 'Tactics',
  158. modeLabel: '',
  159. manageCategoriesTitle: 'Manage Categories',
  160. noCustomCategories: 'No custom categories to manage.',
  161. manageCategoriesDoneButton: 'Done',
  162. managementModalTitle: 'Manage Formations & Categories',
  163. formationsTabTitle: 'Formations',
  164. categoriesTabTitle: 'Categories',
  165. addCategoryPlaceholder: 'New category name...',
  166. addCategoryButton: '+ Add',
  167. categoryNameMaxLengthError: `Category name too long (max ${MAX_CATEGORY_NAME_LENGTH} chars).`,
  168. saveChangesButton: 'Save Changes',
  169. changesSavedSuccess: 'Changes saved successfully.',
  170. noChangesToSave: 'No changes to save.',
  171. descriptionLabel: 'Description (optional):',
  172. descriptionPlaceholder: `Enter a short description (max ${MAX_DESCRIPTION_LENGTH} chars)...`,
  173. descriptionMaxLengthError: `Description too long (max ${MAX_DESCRIPTION_LENGTH} chars).`,
  174. previewFormationLabel: 'Formation:',
  175. xmlRequiredError: 'Please paste the XML data first.',
  176. invalidXmlFormatError: 'The provided text does not appear to be valid XML.',
  177. noTacticsSaved: 'No formations saved',
  178. noCompleteTacticsSaved: 'No tactics saved'
  179. };
  180. const DEFAULT_MODAL_STRINGS = {
  181. ok: 'OK',
  182. cancel: 'Cancel',
  183. error: 'Error',
  184. close: '×'
  185. };
  186.  
  187. let tactics = [];
  188. let completeTactics = {};
  189. let currentFilter = 'all';
  190. let searchTerm = '';
  191. let categories = {};
  192. let rosterCache = { data: null, timestamp: 0, teamId: null };
  193. let userInfoCache = { teamId: null, username: null, timestamp: 0 };
  194. let teamId = null;
  195. let username = null;
  196. let loadingOverlay = null;
  197. let currentViewMode = 'normal';
  198. let collapsedIconElement = null;
  199. let previewElement = null;
  200. let previewHideTimeout = null;
  201. let currentOpenDropdown = null;
  202. let selectedFormationTacticId = null;
  203. let selectedCompleteTacticName = null;
  204.  
  205. function createModalIcon(type) {
  206. if (!type) return null;
  207. const i = document.createElement('div');
  208. i.classList.add('mz-modal-icon');
  209. if (type === 'success') {
  210. i.classList.add('success');
  211. i.innerHTML = '✓';
  212. } else if (type === 'error') {
  213. i.classList.add('error');
  214. i.innerHTML = '✗';
  215. } else if (type === 'info') {
  216. i.classList.add('info');
  217. i.innerHTML = 'ℹ';
  218. }
  219. return i;
  220. }
  221.  
  222. function validateModalInput(inputElement, validatorFn, errorElementId) {
  223. if (!validatorFn || !inputElement || !inputElement.parentNode) return null;
  224. const validationError = validatorFn(inputElement.value);
  225. const existingError = document.getElementById(errorElementId);
  226. if (existingError) existingError.remove();
  227. if (!validationError) return null;
  228. const errorContainer = document.createElement('div');
  229. errorContainer.id = errorElementId;
  230. errorContainer.style.color = '#ff6b6b';
  231. errorContainer.style.marginTop = inputElement.tagName === 'TEXTAREA' ? '5px' : '-10px';
  232. errorContainer.style.marginBottom = '10px';
  233. errorContainer.style.fontSize = '13px';
  234. errorContainer.textContent = validationError;
  235. inputElement.parentNode.insertBefore(errorContainer, inputElement.nextSibling);
  236. return validationError;
  237. }
  238.  
  239.  
  240. function closeModal(overlayElement, callback) {
  241. if (!overlayElement) return;
  242. overlayElement.classList.remove('active');
  243. setTimeout(() => {
  244. if (overlayElement && overlayElement.parentNode === document.body) document.body.removeChild(overlayElement);
  245. if (callback) callback();
  246. }, 300);
  247. }
  248.  
  249. function handleAlertConfirm(options, inputElement, descElement, categorySelect, newCategoryInput, overlayElement, resolve) {
  250. if (options.input === 'text' && options.inputValidator && inputElement) {
  251. const validationError = validateModalInput(inputElement, options.inputValidator, 'mz-modal-input-error');
  252. if (validationError) return;
  253. }
  254. if (options.descriptionInput === 'textarea' && options.descriptionValidator && descElement) {
  255. const descValidationError = validateModalInput(descElement, options.descriptionValidator, 'mz-modal-desc-error');
  256. if (descValidationError) return;
  257. }
  258.  
  259. let selectedCategoryId = null;
  260. let newCategoryName = null;
  261. if (categorySelect) {
  262. selectedCategoryId = categorySelect.value;
  263. if (selectedCategoryId === NEW_CATEGORY_ID && newCategoryInput) {
  264. newCategoryName = newCategoryInput.value.trim();
  265. const categoryErrorElement = document.getElementById('new-category-error');
  266. if (categoryErrorElement) categoryErrorElement.remove();
  267. if (!newCategoryName) {
  268. const errorText = document.createElement('div');
  269. errorText.style.color = '#ff6b6b';
  270. errorText.style.marginTop = '5px';
  271. errorText.style.fontSize = '13px';
  272. errorText.textContent = 'Category name cannot be empty.';
  273. errorText.id = 'new-category-error';
  274. newCategoryInput.parentNode.appendChild(errorText);
  275. return;
  276. }
  277. const existingCategory = Object.values(categories).find(cat => cat.name.toLowerCase() === newCategoryName.toLowerCase());
  278. if (existingCategory) {
  279. const errorText = document.createElement('div');
  280. errorText.style.color = '#ff6b6b';
  281. errorText.style.marginTop = '5px';
  282. errorText.style.fontSize = '13px';
  283. errorText.textContent = 'Category name already exists.';
  284. errorText.id = 'new-category-error';
  285. newCategoryInput.parentNode.appendChild(errorText);
  286. return;
  287. }
  288. }
  289. }
  290. closeModal(overlayElement, () => {
  291. let result = {
  292. isConfirmed: true
  293. };
  294. if (options.input === 'text') {
  295. result.value = inputElement ? inputElement.value : null;
  296. }
  297. if (options.descriptionInput === 'textarea') {
  298. result.description = descElement ? descElement.value : null;
  299. }
  300. if (categorySelect) {
  301. if (selectedCategoryId === NEW_CATEGORY_ID && newCategoryName) {
  302. const newCategoryId = generateCategoryId(newCategoryName);
  303. const newCategory = {
  304. id: newCategoryId,
  305. name: newCategoryName,
  306. color: generateCategoryColor(newCategoryName)
  307. };
  308. result.category = newCategory;
  309. addCategory(newCategory);
  310. } else {
  311. result.category = categories[selectedCategoryId] || categories[OTHER_CATEGORY_ID] || {
  312. id: OTHER_CATEGORY_ID,
  313. name: 'Other',
  314. color: '#8395a7'
  315. };
  316. }
  317. }
  318. resolve(result);
  319. });
  320. }
  321.  
  322. function handleAlertCancel(overlayElement, resolve) {
  323. closeModal(overlayElement, () => {
  324. resolve({
  325. isConfirmed: false,
  326. value: null,
  327. description: null
  328. });
  329. });
  330. }
  331.  
  332. function setUpKeyboardHandler(confirmHandler, cancelHandler, inputElement, descElement) {
  333. return function (event) {
  334. if (event.key === 'Escape') {
  335. cancelHandler();
  336. } else if (event.key === 'Enter') {
  337. const activeEl = document.activeElement;
  338. if (!(activeEl === descElement && descElement?.tagName === 'TEXTAREA') && !(activeEl === inputElement && inputElement?.tagName === 'TEXTAREA')) {
  339. confirmHandler();
  340. } else if (activeEl === inputElement && inputElement?.tagName === 'INPUT') {
  341. confirmHandler();
  342. }
  343. }
  344. };
  345. }
  346.  
  347. function showAlert(options) {
  348. return new Promise((resolve) => {
  349. const overlay = document.createElement('div');
  350. overlay.id = 'mz-modal-overlay';
  351. const container = document.createElement('div');
  352. container.id = 'mz-modal-container';
  353. if (options.modalClass) container.classList.add(options.modalClass);
  354. const header = document.createElement('div');
  355. header.id = 'mz-modal-header';
  356. const titleContainer = document.createElement('div');
  357. titleContainer.classList.add('mz-modal-title-with-icon');
  358. const icon = createModalIcon(options.type);
  359. if (icon) titleContainer.appendChild(icon);
  360. const title = document.createElement('h2');
  361. title.id = 'mz-modal-title';
  362. title.textContent = options.title || '';
  363. titleContainer.appendChild(title);
  364. header.appendChild(titleContainer);
  365. const closeButton = document.createElement('button');
  366. closeButton.id = 'mz-modal-close';
  367. closeButton.innerHTML = DEFAULT_MODAL_STRINGS.close;
  368. header.appendChild(closeButton);
  369. const content = document.createElement('div');
  370. content.id = 'mz-modal-content';
  371. if (options.htmlContent) {
  372. content.appendChild(options.htmlContent);
  373. } else if (options.text) {
  374. const textNode = document.createTextNode(options.text);
  375. content.appendChild(textNode);
  376. }
  377. let inputElem = null,
  378. descElem = null,
  379. descLabel = null,
  380. categorySelectElem = null,
  381. newCategoryInputElem = null,
  382. categoryContainer = null;
  383.  
  384. if (options.input === 'text') {
  385. inputElem = document.createElement('input');
  386. inputElem.id = 'mz-modal-input';
  387. inputElem.type = 'text';
  388. inputElem.value = options.inputValue || '';
  389. inputElem.placeholder = options.placeholder || '';
  390. }
  391.  
  392. if (options.descriptionInput === 'textarea') {
  393. descLabel = document.createElement('label');
  394. descLabel.className = 'mz-modal-label';
  395. descLabel.textContent = options.descriptionLabel || USERSCRIPT_STRINGS.descriptionLabel;
  396. descLabel.htmlFor = 'mz-modal-description';
  397. descElem = document.createElement('textarea');
  398. descElem.id = 'mz-modal-description';
  399. descElem.value = options.descriptionValue || '';
  400. descElem.placeholder = options.descriptionPlaceholder || USERSCRIPT_STRINGS.descriptionPlaceholder;
  401. descElem.rows = 3;
  402. }
  403.  
  404. if (options.showCategorySelector) {
  405. categoryContainer = document.createElement('div');
  406. categoryContainer.className = 'category-selection-container';
  407. const categoryLabel = document.createElement('label');
  408. categoryLabel.className = 'category-selection-label';
  409. categoryLabel.textContent = 'Category:';
  410. categoryContainer.appendChild(categoryLabel);
  411. categorySelectElem = document.createElement('select');
  412. categorySelectElem.id = 'category-selector';
  413. const usedCategoryIds = new Set(tactics.map(t => t.style).filter(Boolean));
  414. if (options.currentCategory) usedCategoryIds.add(options.currentCategory);
  415. const availableCategories = Object.values(categories).filter(cat => DEFAULT_CATEGORIES[cat.id] || cat.id === OTHER_CATEGORY_ID || usedCategoryIds.has(cat.id));
  416. availableCategories.sort((a, b) => {
  417. if (a.id === OTHER_CATEGORY_ID) return 1;
  418. if (b.id === OTHER_CATEGORY_ID) return -1;
  419. return a.name.localeCompare(b.name);
  420. });
  421. availableCategories.forEach(cat => {
  422. if (cat.id !== OTHER_CATEGORY_ID) {
  423. const opt = document.createElement('option');
  424. opt.value = cat.id;
  425. opt.textContent = cat.name;
  426. categorySelectElem.appendChild(opt);
  427. }
  428. });
  429. const otherOption = document.createElement('option');
  430. otherOption.value = OTHER_CATEGORY_ID;
  431. otherOption.textContent = getCategoryName(OTHER_CATEGORY_ID);
  432. categorySelectElem.appendChild(otherOption);
  433. const addNewOption = document.createElement('option');
  434. addNewOption.value = NEW_CATEGORY_ID;
  435. addNewOption.textContent = '+ New category';
  436. categorySelectElem.appendChild(addNewOption);
  437. categorySelectElem.value = (options.currentCategory && categories[options.currentCategory]) ? options.currentCategory : OTHER_CATEGORY_ID;
  438. const newCategoryContainer = document.createElement('div');
  439. newCategoryContainer.className = 'new-category-input-container';
  440. newCategoryInputElem = document.createElement('input');
  441. newCategoryInputElem.id = 'new-category-input';
  442. newCategoryInputElem.type = 'text';
  443. newCategoryInputElem.placeholder = 'New category name';
  444. newCategoryContainer.appendChild(newCategoryInputElem);
  445. categorySelectElem.addEventListener('change', function () {
  446. const isNew = this.value === NEW_CATEGORY_ID;
  447. newCategoryContainer.classList.toggle('visible', isNew);
  448. if (isNew) newCategoryInputElem.focus();
  449. const categoryError = document.getElementById('new-category-error');
  450. if (categoryError) categoryError.remove();
  451. });
  452. categoryContainer.appendChild(categorySelectElem);
  453. categoryContainer.appendChild(newCategoryContainer);
  454. }
  455. const buttons = document.createElement('div');
  456. buttons.id = 'mz-modal-buttons';
  457. const confirmHandler = () => handleAlertConfirm(options, inputElem, descElem, categorySelectElem, newCategoryInputElem, overlay, resolve);
  458. const cancelHandler = () => handleAlertCancel(overlay, resolve);
  459. const confirmButton = document.createElement('button');
  460. confirmButton.classList.add('mz-modal-btn', 'primary');
  461. confirmButton.textContent = options.confirmButtonText || DEFAULT_MODAL_STRINGS.ok;
  462. confirmButton.addEventListener('click', confirmHandler);
  463. buttons.appendChild(confirmButton);
  464. if (options.showCancelButton) {
  465. const cancelButton = document.createElement('button');
  466. cancelButton.classList.add('mz-modal-btn', 'cancel');
  467. cancelButton.textContent = options.cancelButtonText || DEFAULT_MODAL_STRINGS.cancel;
  468. cancelButton.addEventListener('click', cancelHandler);
  469. buttons.appendChild(cancelButton);
  470. }
  471. closeButton.addEventListener('click', cancelHandler);
  472. const keyboardHandler = setUpKeyboardHandler(confirmHandler, cancelHandler, inputElem, descElem);
  473. document.addEventListener('keydown', keyboardHandler);
  474.  
  475. container.appendChild(header);
  476. container.appendChild(content);
  477. if (inputElem) {
  478. container.appendChild(inputElem);
  479. }
  480. if (descLabel && descElem) {
  481. container.appendChild(descLabel);
  482. container.appendChild(descElem);
  483. }
  484. if (categoryContainer) {
  485. container.appendChild(categoryContainer);
  486. }
  487. container.appendChild(buttons);
  488.  
  489. overlay.appendChild(container);
  490. document.body.appendChild(overlay);
  491. setTimeout(() => {
  492. overlay.classList.add('active');
  493. if (inputElem) inputElem.focus();
  494. else if (descElem) descElem.focus();
  495. if (categorySelectElem && categorySelectElem.value === NEW_CATEGORY_ID) newCategoryInputElem.focus();
  496. }, 10);
  497. overlay.addEventListener('transitionend', () => {
  498. if (!overlay.classList.contains('active')) document.removeEventListener('keydown', keyboardHandler);
  499. });
  500. });
  501. }
  502.  
  503. function showSuccessMessage(title, text) {
  504. return showAlert({
  505. title: title || USERSCRIPT_STRINGS.doneTitle,
  506. text: text,
  507. type: 'success'
  508. });
  509. }
  510.  
  511. function showErrorMessage(title, text) {
  512. return showAlert({
  513. title: title || USERSCRIPT_STRINGS.errorTitle,
  514. text: text,
  515. type: 'error'
  516. });
  517. }
  518.  
  519. function showWelcomeMessage() {
  520. return showAlert({
  521. title: 'Hello',
  522. text: USERSCRIPT_STRINGS.welcomeMessage,
  523. confirmButtonText: USERSCRIPT_STRINGS.welcomeGotIt
  524. });
  525. }
  526.  
  527. function showLoadingOverlay() {
  528. if (!loadingOverlay) {
  529. loadingOverlay = document.createElement('div');
  530. loadingOverlay.id = 'loading-overlay';
  531. const spinner = document.createElement('div');
  532. spinner.id = 'loading-spinner';
  533. loadingOverlay.appendChild(spinner);
  534. document.body.appendChild(loadingOverlay);
  535. }
  536. setTimeout(() => loadingOverlay.classList.add('visible'), 10);
  537. }
  538.  
  539. function hideLoadingOverlay() {
  540. if (loadingOverlay) loadingOverlay.classList.remove('visible');
  541. }
  542.  
  543. function isFootball() {
  544. return !!document.querySelector('div#tactics_box.soccer.clearfix');
  545. }
  546.  
  547. function sha256Hash(s) {
  548. const shaObj = new jsSHA('SHA-256', 'TEXT');
  549. shaObj.update(s);
  550. return shaObj.getHash('HEX');
  551. }
  552.  
  553. function insertAfterElement(newNode, referenceNode) {
  554. if (referenceNode && referenceNode.parentNode) {
  555. referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
  556. } else {
  557. console.warn("MZTM: Reference node for insertion not found or has no parent.");
  558. }
  559. }
  560.  
  561. function appendChildren(parent, children) {
  562. children.forEach((child) => {
  563. if (child) parent.appendChild(child);
  564. });
  565. }
  566.  
  567. function getFormattedDate() {
  568. const now = new Date();
  569. const year = now.getFullYear();
  570. const month = (now.getMonth() + 1).toString().padStart(2, '0');
  571. const day = now.getDate().toString().padStart(2, '0');
  572. return `${year}-${month}-${day}`;
  573. }
  574.  
  575. async function fetchTacticsFromGMStorage() {
  576. return GM_getValue(FORMATIONS_STORAGE_KEY, {
  577. tactics: []
  578. });
  579. }
  580.  
  581. function storeTacticsInGMStorage(data) {
  582. GM_setValue(FORMATIONS_STORAGE_KEY, data);
  583. }
  584.  
  585. async function validateDuplicateTactic(id) {
  586. const data = await GM_getValue(FORMATIONS_STORAGE_KEY) || { tactics: [] };
  587. const duplicateTactic = data.tactics.find(t => t.id === id);
  588. return duplicateTactic ? duplicateTactic.name : null;
  589. }
  590.  
  591. async function saveTacticToStorage(tactic) {
  592. const data = await GM_getValue(FORMATIONS_STORAGE_KEY) || {
  593. tactics: []
  594. };
  595. data.tactics.push(tactic);
  596. await GM_setValue(FORMATIONS_STORAGE_KEY, data);
  597. }
  598.  
  599. async function validateDuplicateTacticWithUpdatedCoord(newId, currentTactic, data) {
  600. if (newId === currentTactic.id) return { status: 'unchanged', name: null };
  601. const duplicateTactic = data.tactics.find(t => t.id === newId);
  602. if (duplicateTactic) return { status: 'duplicate', name: duplicateTactic.name };
  603. return { status: 'unique', name: null };
  604. }
  605.  
  606. function loadCompleteTacticsData() {
  607. completeTactics = GM_getValue(COMPLETE_TACTICS_STORAGE_KEY, {});
  608. updateCompleteTacticsDropdown();
  609. }
  610.  
  611. function saveCompleteTacticsData() {
  612. GM_setValue(COMPLETE_TACTICS_STORAGE_KEY, completeTactics);
  613. }
  614.  
  615. async function fetchTeamIdAndUsername(forceRefresh = false) {
  616. const now = Date.now();
  617. const cachedInfo = GM_getValue(USER_INFO_CACHE_KEY);
  618. if (!forceRefresh && cachedInfo && cachedInfo.teamId && cachedInfo.username && (now - cachedInfo.timestamp < USER_INFO_CACHE_DURATION_MS)) {
  619. teamId = cachedInfo.teamId;
  620. username = cachedInfo.username;
  621. return {
  622. teamId,
  623. username
  624. };
  625. }
  626. try {
  627. const usernameElement = document.getElementById('header-username');
  628. if (!usernameElement) throw new Error('No username element found');
  629. const currentUsername = usernameElement.textContent.trim();
  630. const url = `/xml/manager_data.php?sport_id=1&username=${encodeURIComponent(currentUsername)}`;
  631. const response = await fetch(url);
  632. if (!response.ok) throw new Error(`HTTP error ${response.status}`);
  633. const xmlString = await response.text();
  634. const parser = new DOMParser();
  635. const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
  636. const teamElement = xmlDoc.querySelector('Team[sport="soccer"]');
  637. if (!teamElement) throw new Error('No soccer team data found in XML');
  638. const currentTeamId = teamElement.getAttribute('teamId');
  639. if (!currentTeamId) throw new Error('No team ID found in XML');
  640. teamId = currentTeamId;
  641. username = currentUsername;
  642. const newUserInfo = {
  643. teamId: teamId,
  644. username: username,
  645. timestamp: now
  646. };
  647. GM_setValue(USER_INFO_CACHE_KEY, newUserInfo);
  648. return {
  649. teamId,
  650. username
  651. };
  652. } catch (error) {
  653. console.error('Error fetching Team ID and Username:', error);
  654. showErrorMessage(USERSCRIPT_STRINGS.errorTitle, 'Could not fetch team info. Some features might be limited.');
  655. return {
  656. teamId: null,
  657. username: null
  658. };
  659. }
  660. }
  661.  
  662. async function fetchTeamRoster(forceRefresh = false) {
  663. const now = Date.now();
  664. if (!teamId) {
  665. const ids = await fetchTeamIdAndUsername();
  666. if (!ids.teamId) {
  667. console.error("MZTM: Cannot fetch roster without Team ID.");
  668. return null;
  669. }
  670. }
  671. const cachedRoster = GM_getValue(ROSTER_CACHE_KEY);
  672. const isCacheValid = !forceRefresh && cachedRoster && cachedRoster.data && cachedRoster.teamId === teamId && (now - cachedRoster.timestamp < ROSTER_CACHE_DURATION_MS);
  673. if (isCacheValid) {
  674. return cachedRoster.data;
  675. }
  676. try {
  677. const url = `/xml/team_playerlist.php?sport_id=1&team_id=${teamId}`;
  678. const response = await fetch(url);
  679. if (!response.ok) throw new Error(`HTTP error ${response.status}`);
  680. const xmlString = await response.text();
  681. const parser = new DOMParser();
  682. const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
  683. const playerElements = Array.from(xmlDoc.querySelectorAll('TeamPlayers Player'));
  684. const roster = playerElements.map(p => p.getAttribute('id')).filter(id => id);
  685. if (roster.length === 0) {
  686. console.warn("MZTM: Fetched roster is empty for team", teamId);
  687. }
  688. rosterCache = {
  689. data: roster,
  690. timestamp: now,
  691. teamId: teamId
  692. };
  693. GM_setValue(ROSTER_CACHE_KEY, rosterCache);
  694. return roster;
  695. } catch (error) {
  696. console.error('Error fetching team roster:', error);
  697. showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.errorFetchingRoster);
  698. return null;
  699. }
  700. }
  701.  
  702. function generateUniqueId(coordinates) {
  703. coordinates.sort((a, b) => {
  704. if (a[1] !== b[1]) return a[1] - b[1];
  705. else return a[0] - b[0];
  706. });
  707. const coordString = coordinates.map(coord => `${coord[0]},${coord[1]}`).join(';');
  708. return sha256Hash(coordString);
  709. }
  710.  
  711. function handleTacticSelection(tacticId) {
  712. selectedFormationTacticId = tacticId;
  713. if (!tacticId) return;
  714. const outfieldPlayers = Array.from(document.querySelectorAll(OUTFIELD_PLAYERS_SELECTOR));
  715. const selectedTactic = tactics.find(td => td.id === tacticId);
  716. if (selectedTactic) {
  717. if (outfieldPlayers.length < MIN_PLAYERS_ON_PITCH - 1) {
  718. const hiddenTrigger = document.getElementById('hidden_trigger_button');
  719. if (hiddenTrigger) hiddenTrigger.click();
  720. setTimeout(() => rearrangePlayers(selectedTactic.coordinates), 100);
  721. } else {
  722. rearrangePlayers(selectedTactic.coordinates);
  723. }
  724. }
  725. }
  726.  
  727. function rearrangePlayers(coordinates) {
  728. const outfieldPlayers = Array.from(document.querySelectorAll(OUTFIELD_PLAYERS_SELECTOR));
  729. findBestPositions(outfieldPlayers, coordinates);
  730. for (let i = 0; i < outfieldPlayers.length; ++i) {
  731. if (coordinates[i]) {
  732. outfieldPlayers[i].style.left = coordinates[i][0] + 'px';
  733. outfieldPlayers[i].style.top = coordinates[i][1] + 'px';
  734. removeCollision(outfieldPlayers[i]);
  735. }
  736. }
  737. removeTacticSlotInvalidStatus();
  738. updateFormationTextDisplay(getFormation(coordinates));
  739. }
  740.  
  741. function findBestPositions(players, coordinates) {
  742. players.sort((a, b) => parseInt(a.style.top) - parseInt(b.style.top));
  743. coordinates.sort((a, b) => a[1] - b[1]);
  744. }
  745.  
  746. function removeCollision(playerElement) {
  747. if (playerElement.classList.contains('fieldpos-collision')) {
  748. playerElement.classList.remove('fieldpos-collision');
  749. playerElement.classList.add('fieldpos-ok');
  750. }
  751. }
  752.  
  753. function removeTacticSlotInvalidStatus() {
  754. const slot = document.querySelector(TACTIC_SLOT_SELECTOR);
  755. if (slot) slot.classList.remove('invalid');
  756. }
  757.  
  758. function updateFormationTextDisplay(formation) {
  759. const formationTextElement = document.querySelector(FORMATION_TEXT_SELECTOR);
  760. if (formationTextElement) {
  761. const defs = formationTextElement.querySelector('.defs'),
  762. mids = formationTextElement.querySelector('.mids'),
  763. atts = formationTextElement.querySelector('.atts');
  764. if (defs) defs.textContent = formation.defenders;
  765. if (mids) mids.textContent = formation.midfielders;
  766. if (atts) atts.textContent = formation.strikers;
  767. }
  768. }
  769.  
  770. function getFormation(coordinates) {
  771. let strikers = 0,
  772. midfielders = 0,
  773. defenders = 0;
  774. for (const coord of coordinates) {
  775. const y = coord[1];
  776. if (y < 103) strikers++;
  777. else if (y <= 204) midfielders++;
  778. else defenders++;
  779. }
  780. return {
  781. strikers,
  782. midfielders,
  783. defenders
  784. };
  785. }
  786.  
  787. function getFormationFromCompleteTactic(tacticData) {
  788. let strikers = 0,
  789. midfielders = 0,
  790. defenders = 0;
  791. const outfieldCoords = tacticData.initialCoords.filter(p => p.pos === 'normal');
  792. for (const coord of outfieldCoords) {
  793. const y = coord.y;
  794. const effectiveY = y - 9;
  795. if (effectiveY < 103) strikers++;
  796. else if (effectiveY <= 204) midfielders++;
  797. else defenders++;
  798. }
  799. if (strikers + midfielders + defenders !== 10) {
  800. console.warn("MZTM: Calculated formation from complete tactic doesn't sum to 10 outfield players.");
  801. }
  802. return {
  803. strikers,
  804. midfielders,
  805. defenders
  806. };
  807. }
  808.  
  809. function formatFormationString(formationObj) {
  810. if (!formationObj || typeof formationObj.defenders === 'undefined') return 'N/A';
  811. return `${formationObj.defenders}-${formationObj.midfielders}-${formationObj.strikers}`;
  812. }
  813.  
  814. function validateTacticPlayerCount(outfieldPlayers) {
  815. const isGoalkeeperPresent = document.querySelector(GOALKEEPER_SELECTOR);
  816. outfieldPlayers = outfieldPlayers.filter(p => !p.classList.contains('fieldpos-collision'));
  817. if (outfieldPlayers.length < MIN_PLAYERS_ON_PITCH - 1 || !isGoalkeeperPresent) {
  818. showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.invalidTacticError);
  819. return false;
  820. }
  821. return true;
  822. }
  823.  
  824. function generateCategoryId(name) {
  825. return sha256Hash(name.toLowerCase()).substring(0, 10);
  826. }
  827.  
  828. function generateCategoryColor(name) {
  829. const hash = sha256Hash(name);
  830. const hue = parseInt(hash.substring(0, 6), 16) % 360;
  831. const saturation = 50 + (parseInt(hash.substring(6, 8), 16) % 30);
  832. const lightness = 55 + (parseInt(hash.substring(8, 10), 16) % 15);
  833. return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
  834. }
  835.  
  836. function addCategory(category) {
  837. categories[category.id] = category;
  838. saveCategories();
  839. }
  840.  
  841. function saveCategories() {
  842. GM_setValue(CATEGORIES_STORAGE_KEY, categories);
  843. }
  844.  
  845. function loadCategories() {
  846. const storedCategories = GM_getValue(CATEGORIES_STORAGE_KEY);
  847. if (storedCategories && typeof storedCategories === 'object') {
  848. categories = storedCategories;
  849. if (!categories.short_passing) {
  850. categories.short_passing = DEFAULT_CATEGORIES.short_passing;
  851. }
  852. if (!categories.wing_play) {
  853. categories.wing_play = DEFAULT_CATEGORIES.wing_play;
  854. }
  855. } else {
  856. categories = {
  857. ...DEFAULT_CATEGORIES
  858. };
  859. saveCategories();
  860. }
  861. if (!categories[OTHER_CATEGORY_ID]) {
  862. categories[OTHER_CATEGORY_ID] = {
  863. id: OTHER_CATEGORY_ID,
  864. name: 'Other',
  865. color: '#8395a7'
  866. };
  867. }
  868. }
  869.  
  870. function loadCategoryColor(categoryId) {
  871. if (categories[categoryId]) return categories[categoryId].color;
  872. else if (categoryId === 'short_passing') return DEFAULT_CATEGORIES.short_passing.color;
  873. else if (categoryId === 'wing_play') return DEFAULT_CATEGORIES.wing_play.color;
  874. else if (categoryId === OTHER_CATEGORY_ID || !categoryId) return '#8395a7';
  875. else return '#8395a7';
  876. }
  877.  
  878. function getCategoryName(categoryId) {
  879. if (categories[categoryId]) return categories[categoryId].name;
  880. else if (categoryId === 'short_passing') return 'Short Passing';
  881. else if (categoryId === 'wing_play') return 'Wing Play';
  882. else if (categoryId === OTHER_CATEGORY_ID || !categoryId) return 'Other';
  883. else return categoryId || 'Uncategorized';
  884. }
  885.  
  886. async function removeCategory(categoryId, sourceModalElement = null) {
  887. if (!categoryId || categoryId === 'all' || categoryId === OTHER_CATEGORY_ID || DEFAULT_CATEGORIES[categoryId]) {
  888. console.error("Cannot remove this category:", categoryId);
  889. return false;
  890. }
  891.  
  892. const categoryName = getCategoryName(categoryId);
  893. const confirmation = await showAlert({
  894. title: USERSCRIPT_STRINGS.confirmationTitle,
  895. text: USERSCRIPT_STRINGS.removeCategoryConfirmation.replace('{}', categoryName),
  896. showCancelButton: true,
  897. confirmButtonText: USERSCRIPT_STRINGS.removeCategoryButton,
  898. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton,
  899. type: 'error'
  900. });
  901.  
  902. if (!confirmation.isConfirmed) return false;
  903.  
  904. const data = await GM_getValue(FORMATIONS_STORAGE_KEY, { tactics: [] });
  905. let updated = false;
  906. data.tactics = data.tactics.map(t => {
  907. if (t.style === categoryId) {
  908. t.style = OTHER_CATEGORY_ID;
  909. updated = true;
  910. }
  911. return t;
  912. });
  913. tactics = tactics.map(t => {
  914. if (t.style === categoryId) t.style = OTHER_CATEGORY_ID;
  915. return t;
  916. });
  917.  
  918. if (updated) await GM_setValue(FORMATIONS_STORAGE_KEY, data);
  919.  
  920. delete categories[categoryId];
  921. saveCategories();
  922.  
  923. if (currentFilter === categoryId) {
  924. currentFilter = 'all';
  925. GM_setValue(CATEGORY_FILTER_STORAGE_KEY, currentFilter);
  926. }
  927.  
  928. updateTacticsDropdown();
  929. updateCategoryFilterDropdown();
  930.  
  931. if (sourceModalElement) {
  932. const categoryItem = sourceModalElement.querySelector(`li[data-category-id="${categoryId}"]`);
  933. if (categoryItem) {
  934. categoryItem.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
  935. categoryItem.style.opacity = '0';
  936. categoryItem.style.transform = 'translateX(-20px)';
  937. setTimeout(() => categoryItem.remove(), 300);
  938. }
  939. }
  940.  
  941. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.removeCategoryAlert.replace('{}', categoryName));
  942. return true;
  943. }
  944.  
  945. async function showManagementModal() {
  946. const modalContent = createManagementModalContent();
  947. await showAlert({
  948. title: USERSCRIPT_STRINGS.managementModalTitle,
  949. htmlContent: modalContent,
  950. confirmButtonText: USERSCRIPT_STRINGS.manageCategoriesDoneButton,
  951. showCancelButton: false,
  952. modalClass: 'management-modal'
  953. });
  954. updateCategoryFilterDropdown();
  955. updateTacticsDropdown();
  956. }
  957.  
  958. function createManagementModalContent() {
  959. const wrapper = document.createElement('div');
  960. wrapper.className = 'management-modal-wrapper';
  961.  
  962. const tabsConfig = [
  963. { id: 'formations', title: USERSCRIPT_STRINGS.formationsTabTitle, contentGenerator: createFormationsManagementTab },
  964. { id: 'categories', title: USERSCRIPT_STRINGS.categoriesTabTitle, contentGenerator: createCategoriesManagementTab }
  965. ];
  966.  
  967. const tabsContainer = createModalTabs(tabsConfig, wrapper);
  968. wrapper.appendChild(tabsContainer);
  969.  
  970. tabsConfig.forEach((tab, index) => {
  971. const contentDiv = document.createElement('div');
  972. contentDiv.className = 'management-modal-content';
  973. contentDiv.dataset.tabId = tab.id;
  974. if (index === 0) contentDiv.classList.add('active');
  975. tab.contentGenerator(contentDiv);
  976. wrapper.appendChild(contentDiv);
  977. });
  978.  
  979. wrapper.addEventListener('click', handleManagementModalClick);
  980. wrapper.addEventListener('change', handleManagementModalChange);
  981. wrapper.addEventListener('keydown', handleManagementModalKeydown);
  982.  
  983. return wrapper;
  984. }
  985.  
  986. function createFormationsManagementTab(container) {
  987. container.innerHTML = '';
  988. const list = document.createElement('ul');
  989. list.className = 'formation-management-list';
  990.  
  991. const sortedTactics = [...tactics].sort((a, b) => a.name.localeCompare(b.name));
  992.  
  993. if (sortedTactics.length === 0) {
  994. const message = document.createElement('p');
  995. message.textContent = 'No formations saved yet.';
  996. message.className = 'no-items-message';
  997. list.appendChild(message);
  998. } else {
  999. sortedTactics.forEach(tactic => {
  1000. list.appendChild(createFormationManagementItem(tactic));
  1001. });
  1002. }
  1003. container.appendChild(list);
  1004. }
  1005.  
  1006. function createFormationManagementItem(tactic) {
  1007. const listItem = document.createElement('li');
  1008. listItem.dataset.tacticId = tactic.id;
  1009.  
  1010. const nameContainer = document.createElement('div');
  1011. nameContainer.className = 'item-name-container';
  1012. const nameSpan = document.createElement('span');
  1013. nameSpan.className = 'item-name';
  1014. nameSpan.textContent = tactic.name;
  1015. nameContainer.appendChild(nameSpan);
  1016.  
  1017. const controlsContainer = document.createElement('div');
  1018. controlsContainer.className = 'item-controls';
  1019.  
  1020. const categorySelect = document.createElement('select');
  1021. categorySelect.className = 'item-category-select';
  1022. populateCategorySelect(categorySelect, tactic.style);
  1023.  
  1024. const editBtn = document.createElement('button');
  1025. editBtn.className = 'item-action-btn edit-name-btn';
  1026. editBtn.innerHTML = '✏️';
  1027. editBtn.title = 'Edit name & description';
  1028.  
  1029. const deleteBtn = document.createElement('button');
  1030. deleteBtn.className = 'item-action-btn delete-item-btn';
  1031. deleteBtn.innerHTML = '🗑️';
  1032. deleteBtn.title = 'Delete formation';
  1033.  
  1034. appendChildren(controlsContainer, [categorySelect, editBtn, deleteBtn]);
  1035. appendChildren(listItem, [nameContainer, controlsContainer]);
  1036.  
  1037. return listItem;
  1038. }
  1039.  
  1040. function populateCategorySelect(selectElement, currentCategoryId) {
  1041. selectElement.innerHTML = '';
  1042. const availableCategories = Object.values(categories)
  1043. .sort((a, b) => {
  1044. if (a.id === OTHER_CATEGORY_ID) return 1;
  1045. if (b.id === OTHER_CATEGORY_ID) return -1;
  1046. return a.name.localeCompare(b.name);
  1047. });
  1048.  
  1049. availableCategories.forEach(cat => {
  1050. const option = document.createElement('option');
  1051. option.value = cat.id;
  1052. option.textContent = cat.name;
  1053. if (cat.id === (currentCategoryId || OTHER_CATEGORY_ID)) {
  1054. option.selected = true;
  1055. }
  1056. selectElement.appendChild(option);
  1057. });
  1058. }
  1059.  
  1060. function createCategoriesManagementTab(container) {
  1061. container.innerHTML = '';
  1062.  
  1063. const addCategorySection = document.createElement('div');
  1064. addCategorySection.className = 'add-category-section';
  1065. const newCategoryInput = document.createElement('input');
  1066. newCategoryInput.type = 'text';
  1067. newCategoryInput.placeholder = USERSCRIPT_STRINGS.addCategoryPlaceholder;
  1068. newCategoryInput.className = 'add-category-input';
  1069. const addCategoryBtn = document.createElement('button');
  1070. addCategoryBtn.className = 'mz-modal-btn add-category-btn';
  1071. addCategoryBtn.textContent = USERSCRIPT_STRINGS.addCategoryButton;
  1072. appendChildren(addCategorySection, [newCategoryInput, addCategoryBtn]);
  1073. container.appendChild(addCategorySection);
  1074.  
  1075. const list = document.createElement('ul');
  1076. list.className = 'category-management-list';
  1077.  
  1078. const customCategories = Object.values(categories)
  1079. .filter(cat => cat.id !== OTHER_CATEGORY_ID && !DEFAULT_CATEGORIES[cat.id])
  1080. .sort((a, b) => a.name.localeCompare(b.name));
  1081.  
  1082. const noCatMsg = document.createElement('p');
  1083. noCatMsg.textContent = USERSCRIPT_STRINGS.noCustomCategories;
  1084. noCatMsg.className = 'no-custom-categories-message';
  1085. noCatMsg.style.display = customCategories.length === 0 ? 'block' : 'none';
  1086. list.appendChild(noCatMsg);
  1087.  
  1088. customCategories.forEach(cat => {
  1089. list.appendChild(createCategoryManagementItem(cat));
  1090. });
  1091.  
  1092. container.appendChild(list);
  1093. }
  1094.  
  1095. function createCategoryManagementItem(category) {
  1096. const listItem = document.createElement('li');
  1097. listItem.dataset.categoryId = category.id;
  1098.  
  1099. const nameSpan = document.createElement('span');
  1100. nameSpan.textContent = category.name;
  1101. nameSpan.style.flexGrow = '1';
  1102. nameSpan.style.marginRight = '10px';
  1103.  
  1104. const removeBtn = document.createElement('button');
  1105. removeBtn.textContent = 'Remove';
  1106. removeBtn.className = 'mz-modal-btn category-remove-btn';
  1107. removeBtn.title = `Remove category "${category.name}"`;
  1108.  
  1109. listItem.appendChild(nameSpan);
  1110. listItem.appendChild(removeBtn);
  1111. return listItem;
  1112. }
  1113.  
  1114. function handleManagementModalClick(event) {
  1115. const target = event.target;
  1116. const listItem = target.closest('li');
  1117.  
  1118. if (target.classList.contains('edit-name-btn') && listItem) {
  1119. handleEditFormationInModal(listItem);
  1120. } else if (target.classList.contains('delete-item-btn') && listItem) {
  1121. handleDeleteFormationInModal(listItem);
  1122. } else if (target.classList.contains('add-category-btn')) {
  1123. handleAddNewCategoryInModal(target.closest('.add-category-section'));
  1124. } else if (target.classList.contains('category-remove-btn') && listItem) {
  1125. handleDeleteCategoryInModal(listItem);
  1126. }
  1127. }
  1128.  
  1129. function handleManagementModalChange(event) {
  1130. const target = event.target;
  1131. if (target.classList.contains('item-category-select')) {
  1132. const listItem = target.closest('li');
  1133. const tacticId = listItem?.dataset.tacticId;
  1134. const newCategoryId = target.value;
  1135. if (tacticId && newCategoryId) {
  1136. updateFormationCategory(tacticId, newCategoryId);
  1137. }
  1138. }
  1139. }
  1140.  
  1141. function handleManagementModalKeydown(event) {
  1142. if (event.key === 'Enter' && !event.shiftKey) {
  1143. const target = event.target;
  1144. if (target.classList.contains('add-category-input')) {
  1145. handleAddNewCategoryInModal(target.closest('.add-category-section'));
  1146. event.preventDefault();
  1147. }
  1148. }
  1149. }
  1150.  
  1151. async function handleEditFormationInModal(listItem) {
  1152. const tacticId = listItem.dataset.tacticId;
  1153. const tactic = tactics.find(t => t.id === tacticId);
  1154. if (!tactic) return;
  1155.  
  1156. await editTactic(tactic.id, listItem);
  1157. }
  1158.  
  1159. async function handleDeleteFormationInModal(listItem) {
  1160. const tacticId = listItem.dataset.tacticId;
  1161. const tactic = tactics.find(t => t.id === tacticId);
  1162. if (!tactic) return;
  1163.  
  1164. const confirmation = await showAlert({
  1165. title: USERSCRIPT_STRINGS.confirmationTitle,
  1166. text: USERSCRIPT_STRINGS.deleteConfirmation.replace('{}', tactic.name),
  1167. showCancelButton: true,
  1168. confirmButtonText: USERSCRIPT_STRINGS.deleteTacticConfirmButton,
  1169. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton,
  1170. type: 'error'
  1171. });
  1172.  
  1173. if (!confirmation.isConfirmed) return;
  1174.  
  1175. const deletedCategoryId = tactic.style;
  1176. const data = await GM_getValue(FORMATIONS_STORAGE_KEY) || { tactics: [] };
  1177. data.tactics = data.tactics.filter(t => t.id !== tacticId);
  1178. await GM_setValue(FORMATIONS_STORAGE_KEY, data);
  1179. tactics = tactics.filter(t => t.id !== tacticId);
  1180.  
  1181. listItem.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
  1182. listItem.style.opacity = '0';
  1183. listItem.style.transform = 'translateX(-20px)';
  1184. setTimeout(() => {
  1185. listItem.remove();
  1186. const list = document.querySelector('.formation-management-list');
  1187. if (list && !list.querySelector('li')) {
  1188. const message = document.createElement('p');
  1189. message.textContent = 'No formations saved yet.';
  1190. message.className = 'no-items-message';
  1191. list.appendChild(message);
  1192. }
  1193. }, 300);
  1194.  
  1195. const categoryStillUsed = tactics.some(t => t.style === deletedCategoryId);
  1196. if (!categoryStillUsed && deletedCategoryId && !DEFAULT_CATEGORIES[deletedCategoryId] && deletedCategoryId !== OTHER_CATEGORY_ID) {
  1197. delete categories[deletedCategoryId];
  1198. saveCategories();
  1199. if (currentFilter === deletedCategoryId) {
  1200. currentFilter = 'all';
  1201. GM_setValue(CATEGORY_FILTER_STORAGE_KEY, currentFilter);
  1202. }
  1203. const catTab = document.querySelector('.management-modal-content[data-tab-id="categories"]');
  1204. if (catTab) createCategoriesManagementTab(catTab);
  1205. }
  1206.  
  1207. updateTacticsDropdown();
  1208. updateCategoryFilterDropdown();
  1209. }
  1210.  
  1211. async function updateFormationCategory(tacticId, newCategoryId) {
  1212. const tacticIndex = tactics.findIndex(t => t.id === tacticId);
  1213. if (tacticIndex === -1) return;
  1214.  
  1215. const originalCategoryId = tactics[tacticIndex].style;
  1216. if (originalCategoryId === newCategoryId) return;
  1217.  
  1218. tactics[tacticIndex].style = newCategoryId;
  1219. const data = await GM_getValue(FORMATIONS_STORAGE_KEY, { tactics: [] });
  1220. const dataIndex = data.tactics.findIndex(t => t.id === tacticId);
  1221. if (dataIndex !== -1) {
  1222. data.tactics[dataIndex].style = newCategoryId;
  1223. await GM_setValue(FORMATIONS_STORAGE_KEY, data);
  1224.  
  1225. const originalCategoryStillUsed = tactics.some(t => t.style === originalCategoryId);
  1226. if (!originalCategoryStillUsed && originalCategoryId && !DEFAULT_CATEGORIES[originalCategoryId] && originalCategoryId !== OTHER_CATEGORY_ID) {
  1227. delete categories[originalCategoryId];
  1228. saveCategories();
  1229. if (currentFilter === originalCategoryId) {
  1230. currentFilter = 'all';
  1231. GM_setValue(CATEGORY_FILTER_STORAGE_KEY, currentFilter);
  1232. }
  1233. const catTab = document.querySelector('.management-modal-content[data-tab-id="categories"]');
  1234. if (catTab) createCategoriesManagementTab(catTab);
  1235. }
  1236.  
  1237. updateTacticsDropdown();
  1238. updateCategoryFilterDropdown();
  1239. } else {
  1240. showErrorMessage(USERSCRIPT_STRINGS.errorTitle, "Failed to update category in storage.");
  1241. tactics[tacticIndex].style = originalCategoryId;
  1242. const selectElement = document.querySelector(`li[data-tactic-id="${tacticId}"] .item-category-select`);
  1243. if (selectElement) selectElement.value = originalCategoryId || OTHER_CATEGORY_ID;
  1244. }
  1245. }
  1246.  
  1247. async function handleAddNewCategoryInModal(addSection) {
  1248. const input = addSection.querySelector('.add-category-input');
  1249. const list = addSection.nextElementSibling;
  1250. if (!input || !list) return;
  1251.  
  1252. const name = input.value.trim();
  1253. if (!name) {
  1254. showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noTacticNameProvidedError.replace("name", "category name"));
  1255. input.focus();
  1256. return;
  1257. }
  1258. if (name.length > MAX_CATEGORY_NAME_LENGTH) {
  1259. showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.categoryNameMaxLengthError);
  1260. input.focus();
  1261. return;
  1262. }
  1263. const existingCategory = Object.values(categories).find(cat => cat.name.toLowerCase() === name.toLowerCase());
  1264. if (existingCategory) {
  1265. showErrorMessage(USERSCRIPT_STRINGS.errorTitle, "Category name already exists.");
  1266. input.focus();
  1267. return;
  1268. }
  1269.  
  1270. const newCategoryId = generateCategoryId(name);
  1271. const newCategory = {
  1272. id: newCategoryId,
  1273. name: name,
  1274. color: generateCategoryColor(name)
  1275. };
  1276.  
  1277. addCategory(newCategory);
  1278. input.value = '';
  1279.  
  1280. const noCatMsg = list.querySelector('.no-custom-categories-message');
  1281. if (noCatMsg) noCatMsg.style.display = 'none';
  1282.  
  1283. const newItem = createCategoryManagementItem(newCategory);
  1284. list.appendChild(newItem);
  1285. newItem.style.opacity = '0';
  1286. newItem.style.transform = 'translateY(-10px)';
  1287. setTimeout(() => {
  1288. newItem.style.transition = 'opacity 0.3s ease, transform 0.3s ease';
  1289. newItem.style.opacity = '1';
  1290. newItem.style.transform = 'translateY(0)';
  1291. }, 10);
  1292.  
  1293. updateCategoryFilterDropdown();
  1294. document.querySelectorAll('.item-category-select').forEach(select => {
  1295. const currentTacticId = select.closest('li')?.dataset.tacticId;
  1296. const currentTactic = tactics.find(t => t.id === currentTacticId);
  1297. populateCategorySelect(select, currentTactic?.style);
  1298. });
  1299. }
  1300.  
  1301. async function handleDeleteCategoryInModal(listItem) {
  1302. const categoryId = listItem.dataset.categoryId;
  1303. const categoryName = getCategoryName(categoryId);
  1304. if (!categoryId || !categoryName) return;
  1305.  
  1306. const success = await removeCategory(categoryId, listItem.closest('.management-modal-content'));
  1307. if (success) {
  1308. document.querySelectorAll('.item-category-select').forEach(select => {
  1309. const currentTacticId = select.closest('li')?.dataset.tacticId;
  1310. const currentTactic = tactics.find(t => t.id === currentTacticId);
  1311. populateCategorySelect(select, currentTactic?.style);
  1312. });
  1313. const formationsTab = document.querySelector('.management-modal-content[data-tab-id="formations"]');
  1314. if (formationsTab) createFormationsManagementTab(formationsTab);
  1315. }
  1316. }
  1317.  
  1318. async function addNewTactic() {
  1319. const outfieldPlayers = Array.from(document.querySelectorAll(OUTFIELD_PLAYERS_SELECTOR));
  1320. const coordinates = outfieldPlayers.map(p => [parseInt(p.style.left), parseInt(p.style.top)]);
  1321. if (!validateTacticPlayerCount(outfieldPlayers)) return;
  1322. const id = generateUniqueId(coordinates);
  1323. const duplicateName = await validateDuplicateTactic(id);
  1324. if (duplicateName) {
  1325. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.duplicateTacticErrorWithName.replace('{}', duplicateName));
  1326. return;
  1327. }
  1328. const result = await showAlert({
  1329. title: USERSCRIPT_STRINGS.tacticNamePrompt,
  1330. input: 'text',
  1331. inputValue: '',
  1332. placeholder: USERSCRIPT_STRINGS.tacticNamePlaceholder,
  1333. inputValidator: (v) => {
  1334. if (!v) return USERSCRIPT_STRINGS.noTacticNameProvidedError;
  1335. if (v.length > MAX_TACTIC_NAME_LENGTH) return USERSCRIPT_STRINGS.tacticNameMaxLengthError;
  1336. if (tactics.some(t => t.name === v)) return USERSCRIPT_STRINGS.alreadyExistingTacticNameError;
  1337. return null;
  1338. },
  1339. descriptionInput: 'textarea',
  1340. descriptionValue: '',
  1341. descriptionPlaceholder: USERSCRIPT_STRINGS.descriptionPlaceholder,
  1342. descriptionValidator: (d) => {
  1343. if (d && d.length > MAX_DESCRIPTION_LENGTH) return USERSCRIPT_STRINGS.descriptionMaxLengthError;
  1344. return null;
  1345. },
  1346. showCategorySelector: true,
  1347. showCancelButton: true,
  1348. confirmButtonText: USERSCRIPT_STRINGS.saveButton,
  1349. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
  1350. });
  1351. if (!result.isConfirmed || !result.value) return;
  1352. const name = result.value;
  1353. const description = result.description || '';
  1354. const categoryId = result.category.id;
  1355. const tactic = {
  1356. name: name,
  1357. description: description,
  1358. coordinates: coordinates,
  1359. id: id,
  1360. style: categoryId
  1361. };
  1362. await saveTacticToStorage(tactic);
  1363. tactics.push(tactic);
  1364. tactics.sort((a, b) => a.name.localeCompare(b.name));
  1365. updateTacticsDropdown(id);
  1366. updateCategoryFilterDropdown();
  1367. handleTacticSelection(tactic.id);
  1368. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.addAlert.replace('{}', tactic.name));
  1369. }
  1370.  
  1371. async function addNewTacticWithXml() {
  1372. const xmlResult = await showAlert({
  1373. title: USERSCRIPT_STRINGS.xmlPlaceholder,
  1374. input: 'text',
  1375. inputValue: '',
  1376. placeholder: USERSCRIPT_STRINGS.xmlPlaceholder,
  1377. showCancelButton: true,
  1378. confirmButtonText: USERSCRIPT_STRINGS.addConfirmButton,
  1379. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
  1380. });
  1381.  
  1382. if (!xmlResult.isConfirmed) return;
  1383. const xml = xmlResult.value;
  1384.  
  1385. if (!xml) {
  1386. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.xmlRequiredError);
  1387. return;
  1388. }
  1389. if (!xml.trim().startsWith('<') || !xml.trim().endsWith('>')) {
  1390. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.invalidXmlFormatError);
  1391. return;
  1392. }
  1393.  
  1394. const nameResult = await showAlert({
  1395. title: USERSCRIPT_STRINGS.tacticNamePrompt,
  1396. input: 'text',
  1397. inputValue: '',
  1398. placeholder: USERSCRIPT_STRINGS.tacticNamePlaceholder,
  1399. inputValidator: (v) => {
  1400. if (!v) return USERSCRIPT_STRINGS.noTacticNameProvidedError;
  1401. if (v.length > MAX_TACTIC_NAME_LENGTH) return USERSCRIPT_STRINGS.tacticNameMaxLengthError;
  1402. if (tactics.some(t => t.name === v)) return USERSCRIPT_STRINGS.alreadyExistingTacticNameError;
  1403. return null;
  1404. },
  1405. descriptionInput: 'textarea',
  1406. descriptionValue: '',
  1407. descriptionPlaceholder: USERSCRIPT_STRINGS.descriptionPlaceholder,
  1408. descriptionValidator: (d) => {
  1409. if (d && d.length > MAX_DESCRIPTION_LENGTH) return USERSCRIPT_STRINGS.descriptionMaxLengthError;
  1410. return null;
  1411. },
  1412. showCategorySelector: true,
  1413. showCancelButton: true,
  1414. confirmButtonText: USERSCRIPT_STRINGS.saveButton,
  1415. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
  1416. });
  1417. if (!nameResult.isConfirmed || !nameResult.value) return;
  1418. const name = nameResult.value;
  1419. const description = nameResult.description || '';
  1420. const categoryId = nameResult.category.id;
  1421. try {
  1422. const newTactic = await convertXmlToSimpleFormationJson(xml, name);
  1423. const id = generateUniqueId(newTactic.coordinates);
  1424. const duplicateName = await validateDuplicateTactic(id);
  1425. if (duplicateName) {
  1426. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.duplicateTacticErrorWithName.replace('{}', duplicateName));
  1427. return;
  1428. }
  1429. newTactic.id = id;
  1430. newTactic.style = categoryId;
  1431. newTactic.description = description;
  1432. await saveTacticToStorage(newTactic);
  1433. tactics.push(newTactic);
  1434. tactics.sort((a, b) => a.name.localeCompare(b.name));
  1435. updateTacticsDropdown(id);
  1436. updateCategoryFilterDropdown();
  1437. handleTacticSelection(newTactic.id);
  1438. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.addAlert.replace('{}', newTactic.name));
  1439. } catch (error) {
  1440. console.error('XMLError:', error);
  1441. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.xmlParsingError + (error.message ? `: ${error.message}` : ''));
  1442. }
  1443. }
  1444.  
  1445. async function deleteTactic() {
  1446. const selectedTactic = tactics.find(t => t.id === selectedFormationTacticId);
  1447. if (!selectedTactic) {
  1448. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noTacticSelectedError);
  1449. return;
  1450. }
  1451. const confirmation = await showAlert({
  1452. title: USERSCRIPT_STRINGS.confirmationTitle,
  1453. text: USERSCRIPT_STRINGS.deleteConfirmation.replace('{}', selectedTactic.name),
  1454. showCancelButton: true,
  1455. confirmButtonText: USERSCRIPT_STRINGS.deleteTacticConfirmButton,
  1456. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
  1457. });
  1458. if (!confirmation.isConfirmed) return;
  1459. const deletedCategoryId = selectedTactic.style;
  1460. const data = await GM_getValue(FORMATIONS_STORAGE_KEY) || {
  1461. tactics: []
  1462. };
  1463. data.tactics = data.tactics.filter(t => t.id !== selectedTactic.id);
  1464. await GM_setValue(FORMATIONS_STORAGE_KEY, data);
  1465. tactics = tactics.filter(t => t.id !== selectedTactic.id);
  1466. selectedFormationTacticId = null;
  1467. const categoryStillUsed = tactics.some(t => t.style === deletedCategoryId);
  1468. if (!categoryStillUsed && deletedCategoryId && !DEFAULT_CATEGORIES[deletedCategoryId] && deletedCategoryId !== OTHER_CATEGORY_ID) {
  1469. delete categories[deletedCategoryId];
  1470. saveCategories();
  1471. if (currentFilter === deletedCategoryId) {
  1472. currentFilter = 'all';
  1473. GM_setValue(CATEGORY_FILTER_STORAGE_KEY, currentFilter);
  1474. }
  1475. }
  1476. updateTacticsDropdown();
  1477. updateCategoryFilterDropdown();
  1478. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.deleteAlert.replace('{}', selectedTactic.name));
  1479. }
  1480.  
  1481. async function editTactic(tacticIdToEdit = null, sourceListItem = null) {
  1482. const idToUse = tacticIdToEdit || selectedFormationTacticId;
  1483. const selectedTactic = tactics.find(t => t.id === idToUse);
  1484.  
  1485. if (!selectedTactic) {
  1486. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noTacticSelectedError);
  1487. return;
  1488. }
  1489.  
  1490. const originalName = selectedTactic.name;
  1491. const originalCategory = selectedTactic.style;
  1492. const originalDescription = selectedTactic.description || '';
  1493.  
  1494. const result = await showAlert({
  1495. title: 'Edit Formation',
  1496. input: 'text',
  1497. inputValue: originalName,
  1498. placeholder: USERSCRIPT_STRINGS.tacticNamePlaceholder,
  1499. inputValidator: (v) => {
  1500. if (!v) return USERSCRIPT_STRINGS.noTacticNameProvidedError;
  1501. if (v.length > MAX_TACTIC_NAME_LENGTH) return USERSCRIPT_STRINGS.tacticNameMaxLengthError;
  1502. if (v !== originalName && tactics.some(t => t.name === v)) return USERSCRIPT_STRINGS.alreadyExistingTacticNameError;
  1503. return null;
  1504. },
  1505. descriptionInput: 'textarea',
  1506. descriptionValue: originalDescription,
  1507. descriptionPlaceholder: USERSCRIPT_STRINGS.descriptionPlaceholder,
  1508. descriptionValidator: (d) => {
  1509. if (d && d.length > MAX_DESCRIPTION_LENGTH) return USERSCRIPT_STRINGS.descriptionMaxLengthError;
  1510. return null;
  1511. },
  1512. showCategorySelector: true,
  1513. currentCategory: selectedTactic.style,
  1514. showCancelButton: true,
  1515. confirmButtonText: USERSCRIPT_STRINGS.saveButton,
  1516. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
  1517. });
  1518.  
  1519. if (!result.isConfirmed) return;
  1520.  
  1521. const newName = result.value || originalName;
  1522. const newDescription = result.description || '';
  1523. const newCategory = result.category?.id || originalCategory;
  1524.  
  1525. if (newName === originalName && newCategory === originalCategory && newDescription === originalDescription) {
  1526. return;
  1527. }
  1528.  
  1529. const categoryChanged = originalCategory !== newCategory;
  1530. const data = await GM_getValue(FORMATIONS_STORAGE_KEY) || {
  1531. tactics: []
  1532. };
  1533.  
  1534. let updatedInStorage = false;
  1535. data.tactics = data.tactics.map(t => {
  1536. if (t.id === selectedTactic.id) {
  1537. t.name = newName;
  1538. t.style = newCategory;
  1539. t.description = newDescription;
  1540. updatedInStorage = true;
  1541. }
  1542. return t;
  1543. });
  1544.  
  1545. if (!updatedInStorage) {
  1546. console.error("MZTM: Failed to find tactic in storage for update.", selectedTactic.id);
  1547. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, "Failed to update tactic in storage.");
  1548. return;
  1549. }
  1550.  
  1551. await GM_setValue(FORMATIONS_STORAGE_KEY, data);
  1552.  
  1553. const tacticIndex = tactics.findIndex(t => t.id === selectedTactic.id);
  1554. if (tacticIndex !== -1) {
  1555. tactics[tacticIndex].name = newName;
  1556. tactics[tacticIndex].style = newCategory;
  1557. tactics[tacticIndex].description = newDescription;
  1558. } else {
  1559. console.error("MZTM: Failed to find tactic in memory for update.", selectedTactic.id);
  1560. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, "Internal error updating tactic data.");
  1561. await initializeScriptData();
  1562. updateTacticsDropdown();
  1563. updateCategoryFilterDropdown();
  1564. return;
  1565. }
  1566.  
  1567. if (categoryChanged) {
  1568. const originalCategoryStillUsed = tactics.some(t => t.style === originalCategory);
  1569. if (!originalCategoryStillUsed && originalCategory && !DEFAULT_CATEGORIES[originalCategory] && originalCategory !== OTHER_CATEGORY_ID) {
  1570. delete categories[originalCategory];
  1571. saveCategories();
  1572. if (currentFilter === originalCategory) {
  1573. currentFilter = 'all';
  1574. GM_setValue(CATEGORY_FILTER_STORAGE_KEY, currentFilter);
  1575. }
  1576. }
  1577. }
  1578.  
  1579. tactics.sort((a, b) => a.name.localeCompare(b.name));
  1580. updateTacticsDropdown(selectedTactic.id);
  1581. updateCategoryFilterDropdown();
  1582.  
  1583. if (sourceListItem) {
  1584. const nameSpan = sourceListItem.querySelector('.item-name');
  1585. if (nameSpan) nameSpan.textContent = newName;
  1586. const categorySelect = sourceListItem.querySelector('.item-category-select');
  1587. if (categorySelect) categorySelect.value = newCategory;
  1588. }
  1589.  
  1590. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.renameAlert.replace('{}', newName));
  1591. }
  1592.  
  1593. async function updateTactic() {
  1594. const outfieldPlayers = Array.from(document.querySelectorAll(OUTFIELD_PLAYERS_SELECTOR));
  1595. const selectedTactic = tactics.find(t => t.id === selectedFormationTacticId);
  1596. if (!selectedTactic) {
  1597. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noTacticSelectedError);
  1598. return;
  1599. }
  1600. if (!validateTacticPlayerCount(outfieldPlayers)) return;
  1601. const updatedCoordinates = outfieldPlayers.map(p => [parseInt(p.style.left), parseInt(p.style.top)]);
  1602. const newId = generateUniqueId(updatedCoordinates);
  1603. const data = await GM_getValue(FORMATIONS_STORAGE_KEY) || {
  1604. tactics: []
  1605. };
  1606. const validationResult = await validateDuplicateTacticWithUpdatedCoord(newId, selectedTactic, data);
  1607. if (validationResult.status === 'unchanged') {
  1608. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noChangesMadeError);
  1609. return;
  1610. } else if (validationResult.status === 'duplicate') {
  1611. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.duplicateTacticErrorWithName.replace('{}', validationResult.name));
  1612. return;
  1613. }
  1614. const confirmation = await showAlert({
  1615. title: USERSCRIPT_STRINGS.confirmationTitle,
  1616. text: USERSCRIPT_STRINGS.updateConfirmation.replace('{}', selectedTactic.name),
  1617. showCancelButton: true,
  1618. confirmButtonText: USERSCRIPT_STRINGS.updateConfirmButton,
  1619. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
  1620. });
  1621. if (!confirmation.isConfirmed) return;
  1622. for (const tactic of data.tactics) {
  1623. if (tactic.id === selectedTactic.id) {
  1624. tactic.coordinates = updatedCoordinates;
  1625. tactic.id = newId;
  1626. }
  1627. }
  1628. const memoryTactic = tactics.find(t => t.id === selectedTactic.id);
  1629. if (memoryTactic) {
  1630. memoryTactic.coordinates = updatedCoordinates;
  1631. memoryTactic.id = newId;
  1632. }
  1633. await GM_setValue(FORMATIONS_STORAGE_KEY, data);
  1634. selectedFormationTacticId = newId;
  1635. updateTacticsDropdown(newId);
  1636. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.updateAlert.replace('{}', selectedTactic.name));
  1637. }
  1638.  
  1639. async function clearTactics() {
  1640. const confirmation = await showAlert({
  1641. title: USERSCRIPT_STRINGS.confirmationTitle,
  1642. text: USERSCRIPT_STRINGS.clearConfirmation,
  1643. showCancelButton: true,
  1644. confirmButtonText: USERSCRIPT_STRINGS.clearTacticsConfirmButton,
  1645. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton,
  1646. type: 'error'
  1647. });
  1648. if (!confirmation.isConfirmed) return;
  1649. await GM_deleteValue(FORMATIONS_STORAGE_KEY);
  1650. await GM_deleteValue(OLD_FORMATIONS_STORAGE_KEY);
  1651. tactics = [];
  1652. selectedFormationTacticId = null;
  1653. currentFilter = 'all';
  1654. GM_setValue(CATEGORY_FILTER_STORAGE_KEY, currentFilter);
  1655. loadCategories();
  1656. updateTacticsDropdown();
  1657. updateCategoryFilterDropdown();
  1658. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.clearAlert);
  1659. }
  1660.  
  1661. async function resetTactics() {
  1662. const confirmation = await showAlert({
  1663. title: USERSCRIPT_STRINGS.confirmationTitle,
  1664. text: USERSCRIPT_STRINGS.resetConfirmation,
  1665. showCancelButton: true,
  1666. confirmButtonText: USERSCRIPT_STRINGS.resetTacticsConfirmButton,
  1667. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton,
  1668. type: 'error'
  1669. });
  1670. if (!confirmation.isConfirmed) return;
  1671. await GM_deleteValue(FORMATIONS_STORAGE_KEY);
  1672. await GM_deleteValue(OLD_FORMATIONS_STORAGE_KEY);
  1673. await GM_deleteValue(CATEGORIES_STORAGE_KEY);
  1674. await GM_deleteValue(CATEGORY_FILTER_STORAGE_KEY);
  1675. tactics = [];
  1676. selectedFormationTacticId = null;
  1677. currentFilter = 'all';
  1678. loadCategories();
  1679. updateTacticsDropdown();
  1680. updateCategoryFilterDropdown();
  1681. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.resetAlert);
  1682. }
  1683.  
  1684. async function importTacticsJsonData() {
  1685. try {
  1686. const result = await showAlert({
  1687. title: 'Import Formations (JSON)',
  1688. input: 'text',
  1689. inputValue: '',
  1690. placeholder: 'Paste Formations JSON here',
  1691. showCancelButton: true,
  1692. confirmButtonText: USERSCRIPT_STRINGS.importButton,
  1693. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
  1694. });
  1695. if (!result.isConfirmed || !result.value) return;
  1696. let importedData;
  1697. try {
  1698. importedData = JSON.parse(result.value);
  1699. } catch (e) {
  1700. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.invalidImportError);
  1701. return;
  1702. }
  1703. if (!importedData || !Array.isArray(importedData.tactics) || !importedData.tactics.every(t => t.name && t.id && Array.isArray(t.coordinates))) {
  1704. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.invalidImportError);
  1705. return;
  1706. }
  1707. const importedTactics = importedData.tactics;
  1708. importedTactics.forEach(t => {
  1709. if (!t.hasOwnProperty('style')) t.style = OTHER_CATEGORY_ID;
  1710. if (!t.hasOwnProperty('description')) t.description = '';
  1711. if (t.style && !categories[t.style] && !DEFAULT_CATEGORIES[t.style] && t.style !== OTHER_CATEGORY_ID) {
  1712. addCategory({
  1713. id: t.style,
  1714. name: t.style,
  1715. color: generateCategoryColor(t.style)
  1716. });
  1717. }
  1718. });
  1719. let existingData = await GM_getValue(FORMATIONS_STORAGE_KEY, {
  1720. tactics: []
  1721. });
  1722. let existingTactics = existingData.tactics || [];
  1723. const mergedTactics = [...existingTactics];
  1724. let addedCount = 0;
  1725. for (const impTactic of importedTactics) {
  1726. if (!existingTactics.some(t => t.id === impTactic.id)) {
  1727. mergedTactics.push(impTactic);
  1728. addedCount++;
  1729. } else {
  1730. const existingIndex = mergedTactics.findIndex(t => t.id === impTactic.id);
  1731. if (existingIndex !== -1) {
  1732. mergedTactics[existingIndex] = { ...mergedTactics[existingIndex], ...impTactic };
  1733. }
  1734. }
  1735. }
  1736. await GM_setValue(FORMATIONS_STORAGE_KEY, {
  1737. tactics: mergedTactics
  1738. });
  1739. mergedTactics.sort((a, b) => a.name.localeCompare(b.name));
  1740. tactics = mergedTactics;
  1741. updateTacticsDropdown();
  1742. updateCategoryFilterDropdown();
  1743. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.importAlert + (addedCount > 0 ? ` (${addedCount} new items added)` : ''));
  1744. } catch (error) {
  1745. console.error('ImportError:', error);
  1746. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.invalidImportError + (error.message ? `: ${error.message}` : ''));
  1747. }
  1748. }
  1749.  
  1750. async function exportTacticsJsonData() {
  1751. try {
  1752. const data = GM_getValue(FORMATIONS_STORAGE_KEY, {
  1753. tactics: []
  1754. });
  1755. const jsonString = JSON.stringify(data, null, 2);
  1756. if (navigator.clipboard?.writeText) {
  1757. try {
  1758. await navigator.clipboard.writeText(jsonString);
  1759. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.exportAlert);
  1760. return;
  1761. } catch (clipError) {
  1762. console.warn('Clipboard write failed, fallback.', clipError);
  1763. }
  1764. }
  1765. const textArea = document.createElement('textarea');
  1766. textArea.value = jsonString;
  1767. textArea.style.width = '100%';
  1768. textArea.style.minHeight = '150px';
  1769. textArea.style.marginTop = '10px';
  1770. textArea.style.backgroundColor = 'rgba(0,0,0,0.2)';
  1771. textArea.style.color = 'var(--text-color)';
  1772. textArea.style.border = '1px solid rgba(255,255,255,0.1)';
  1773. textArea.style.borderRadius = '4px';
  1774. textArea.readOnly = true;
  1775. const container = document.createElement('div');
  1776. container.appendChild(document.createTextNode('Copy the JSON data:'));
  1777. container.appendChild(textArea);
  1778. await showAlert({
  1779. title: 'Export Formations (JSON)',
  1780. htmlContent: container,
  1781. confirmButtonText: 'Done'
  1782. });
  1783. textArea.select();
  1784. textArea.setSelectionRange(0, 99999);
  1785. } catch (error) {
  1786. console.error('Export error:', error);
  1787. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, 'Failed to export formations.');
  1788. }
  1789. }
  1790.  
  1791. async function convertXmlToSimpleFormationJson(xmlString, tacticName) {
  1792. const parser = new DOMParser();
  1793. const xmlDoc = parser.parseFromString(xmlString, 'text/xml');
  1794. const parseErrors = xmlDoc.getElementsByTagName('parsererror');
  1795. if (parseErrors.length > 0) throw new Error(USERSCRIPT_STRINGS.xmlValidationError);
  1796. const positionElements = Array.from(xmlDoc.getElementsByTagName('Pos')).filter(el => el.getAttribute('pos') === 'normal');
  1797. if (positionElements.length !== MIN_PLAYERS_ON_PITCH - 1) throw new Error(`XML must contain exactly ${MIN_PLAYERS_ON_PITCH - 1} outfield players. Found ${positionElements.length}.`);
  1798. const coordinates = positionElements.map(el => {
  1799. const x = parseInt(el.getAttribute('x'));
  1800. const y = parseInt(el.getAttribute('y'));
  1801. if (isNaN(x) || isNaN(y)) throw new Error('Invalid coordinates found in XML.');
  1802. return [x - 7, y - 9];
  1803. });
  1804. return {
  1805. name: tacticName,
  1806. coordinates: coordinates
  1807. };
  1808. }
  1809.  
  1810. function getAttr(element, attributeName, defaultValue = null) {
  1811. return element ? element.getAttribute(attributeName) || defaultValue : defaultValue;
  1812. }
  1813.  
  1814. function parseCompleteTacticXml(xmlString) {
  1815. const parser = new DOMParser();
  1816. const xmlDoc = parser.parseFromString(xmlString, "text/xml");
  1817. if (xmlDoc.getElementsByTagName("parsererror").length > 0) throw new Error("XML parsing error");
  1818. const soccerTactics = xmlDoc.querySelector("SoccerTactics");
  1819. if (!soccerTactics) throw new Error("Missing <SoccerTactics>");
  1820. const teamElement = soccerTactics.querySelector("Team");
  1821. const posElements = Array.from(soccerTactics.querySelectorAll("Pos"));
  1822. const subElements = Array.from(soccerTactics.querySelectorAll("Sub"));
  1823. const ruleElements = Array.from(soccerTactics.querySelectorAll("TacticRule"));
  1824. const data = {
  1825. initialCoords: [],
  1826. alt1Coords: [],
  1827. alt2Coords: [],
  1828. teamSettings: {},
  1829. substitutes: [],
  1830. tacticRules: [],
  1831. originalPlayerIDs: new Set(),
  1832. description: ''
  1833. };
  1834. data.teamSettings = {
  1835. passingStyle: getAttr(teamElement, 'tactics', 'shortpass'),
  1836. mentality: getAttr(teamElement, 'playstyle', 'normal'),
  1837. aggression: getAttr(teamElement, 'aggression', 'normal'),
  1838. captainPID: getAttr(teamElement, 'captain', '0')
  1839. };
  1840. if (data.teamSettings.captainPID !== '0') data.originalPlayerIDs.add(data.teamSettings.captainPID);
  1841. posElements.forEach(el => {
  1842. const pid = getAttr(el, 'pid');
  1843. const posType = getAttr(el, 'pos');
  1844. if (!pid) return;
  1845. data.originalPlayerIDs.add(pid);
  1846. if (posType === 'normal' || posType === 'goalie') {
  1847. const x = parseInt(getAttr(el, 'x', 0));
  1848. const y = parseInt(getAttr(el, 'y', 0));
  1849. const x1 = parseInt(getAttr(el, 'x1', x));
  1850. const y1 = parseInt(getAttr(el, 'y1', y));
  1851. const x2 = parseInt(getAttr(el, 'x2', x1));
  1852. const y2 = parseInt(getAttr(el, 'y2', y1));
  1853. data.initialCoords.push({
  1854. pid: pid,
  1855. pos: posType,
  1856. x: x,
  1857. y: y
  1858. });
  1859. data.alt1Coords.push({
  1860. pid: pid,
  1861. pos: posType,
  1862. x: x1,
  1863. y: y1
  1864. });
  1865. data.alt2Coords.push({
  1866. pid: pid,
  1867. pos: posType,
  1868. x: x2,
  1869. y: y2
  1870. });
  1871. }
  1872. });
  1873. subElements.forEach(el => {
  1874. const pid = getAttr(el, 'pid');
  1875. const posType = getAttr(el, 'pos');
  1876. const x = parseInt(getAttr(el, 'x', 0));
  1877. const y = parseInt(getAttr(el, 'y', 0));
  1878. if (pid) {
  1879. data.originalPlayerIDs.add(pid);
  1880. data.substitutes.push({
  1881. pid: pid,
  1882. pos: posType,
  1883. x: x,
  1884. y: y
  1885. });
  1886. }
  1887. });
  1888. ruleElements.forEach(el => {
  1889. const rule = {};
  1890. for (const attr of el.attributes) {
  1891. rule[attr.name] = attr.value;
  1892. if (attr.name === 'out_player' && attr.value !== 'no_change' && attr.value !== '0') data.originalPlayerIDs.add(attr.value);
  1893. if (attr.name === 'in_player_id' && attr.value !== 'NULL' && attr.value !== '0') data.originalPlayerIDs.add(attr.value);
  1894. }
  1895. data.tacticRules.push(rule);
  1896. });
  1897. data.originalPlayerIDs = Array.from(data.originalPlayerIDs);
  1898. return data;
  1899. }
  1900.  
  1901. function generateCompleteTacticXml(tacticData, playerMapping) {
  1902. let xml = `<?xml version="1.0" ?>\n<SoccerTactics>\n`;
  1903. const mappedCaptain = playerMapping[tacticData.teamSettings.captainPID] || '0';
  1904. xml += `\t<Team tactics="${tacticData.teamSettings.passingStyle || 'shortpass'}" playstyle="${tacticData.teamSettings.mentality || 'normal'}" aggression="${tacticData.teamSettings.aggression || 'normal'}" captain="${mappedCaptain}" />\n`;
  1905. const playerCoords = {};
  1906. tacticData.initialCoords.forEach(p => {
  1907. if (!playerCoords[p.pid]) {
  1908. playerCoords[p.pid] = {
  1909. pos: p.pos
  1910. };
  1911. playerCoords[p.pid].initial = {
  1912. x: p.x,
  1913. y: p.y
  1914. };
  1915. }
  1916. });
  1917. tacticData.alt1Coords.forEach(p => {
  1918. if (!playerCoords[p.pid]) return;
  1919. playerCoords[p.pid].alt1 = {
  1920. x: p.x,
  1921. y: p.y
  1922. };
  1923. });
  1924. tacticData.alt2Coords.forEach(p => {
  1925. if (!playerCoords[p.pid]) return;
  1926. playerCoords[p.pid].alt2 = {
  1927. x: p.x,
  1928. y: p.y
  1929. };
  1930. });
  1931. for (const originalPid in playerCoords) {
  1932. const mappedPid = playerMapping[originalPid];
  1933. if (!mappedPid) continue;
  1934. const playerData = playerCoords[originalPid];
  1935. const initial = playerData.initial || {
  1936. x: 0,
  1937. y: 0
  1938. };
  1939. const alt1 = playerData.alt1 || initial;
  1940. const alt2 = playerData.alt2 || alt1;
  1941. xml += `\t<Pos pos="${playerData.pos}" pid="${mappedPid}" x="${initial.x}" y="${initial.y}" x1="${alt1.x}" y1="${alt1.y}" x2="${alt2.x}" y2="${alt2.y}" />\n`;
  1942. }
  1943. tacticData.substitutes.forEach(s => {
  1944. const mappedPid = playerMapping[s.pid];
  1945. if (mappedPid) xml += `\t<Sub pos="${s.pos}" pid="${mappedPid}" x="${s.x}" y="${s.y}" />\n`;
  1946. });
  1947. tacticData.tacticRules.forEach(rule => {
  1948. const mappedOutPlayer = (rule.out_player && rule.out_player !== 'no_change') ? (playerMapping[rule.out_player] || 'no_change') : 'no_change';
  1949. const mappedInPlayer = (rule.in_player_id && rule.in_player_id !== 'NULL') ? (playerMapping[rule.in_player_id] || 'NULL') : 'NULL';
  1950. let includeRule = true;
  1951. if (rule.out_player && rule.out_player !== 'no_change' && mappedOutPlayer === 'no_change') includeRule = false;
  1952. if (rule.in_player_id && rule.in_player_id !== 'NULL' && mappedInPlayer === 'NULL') includeRule = false;
  1953. if (includeRule) {
  1954. xml += '\t<TacticRule';
  1955. for (const attr in rule) {
  1956. let value = rule[attr];
  1957. if (attr === 'out_player') value = mappedOutPlayer;
  1958. if (attr === 'in_player_id') value = mappedInPlayer;
  1959. xml += ` ${attr}="${value}"`;
  1960. }
  1961. xml += ' />\n';
  1962. }
  1963. });
  1964. xml += '</SoccerTactics>';
  1965. return xml;
  1966. }
  1967.  
  1968. async function saveCompleteTactic() {
  1969. const exportButton = document.getElementById('export_button');
  1970. const importExportWindow = document.getElementById('importExportTacticsWindow');
  1971. const playerInfoWindow = document.getElementById('playerInfoWindow');
  1972. const importExportData = document.getElementById('importExportData');
  1973. if (!exportButton || !importExportWindow || !playerInfoWindow || !importExportData) return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, 'Could not find required MZ UI elements for export.');
  1974. const windowHidden = importExportWindow.style.display === 'none';
  1975. if (windowHidden) {
  1976. const toggleButton = document.getElementById('import_export_button');
  1977. if (toggleButton) toggleButton.click();
  1978. else return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, 'Could not find button to toggle XML view.');
  1979. }
  1980. importExportData.value = '';
  1981. exportButton.click();
  1982. await new Promise(r => setTimeout(r, 200));
  1983. const xmlString = importExportData.value;
  1984. if (!xmlString) {
  1985. if (windowHidden) document.getElementById('close_button')?.click();
  1986. return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, 'Export did not produce XML.');
  1987. }
  1988. let savedData;
  1989. try {
  1990. savedData = parseCompleteTacticXml(xmlString);
  1991. } catch (error) {
  1992. console.error("XML Parse Error:", error);
  1993. if (windowHidden) document.getElementById('close_button')?.click();
  1994. return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.errorXmlExportParse);
  1995. }
  1996. const result = await showAlert({
  1997. title: USERSCRIPT_STRINGS.completeTacticNamePrompt,
  1998. input: 'text',
  1999. inputValue: '',
  2000. placeholder: USERSCRIPT_STRINGS.completeTacticNamePlaceholder,
  2001. inputValidator: (v) => {
  2002. if (!v) return USERSCRIPT_STRINGS.noTacticNameProvidedError;
  2003. if (v.length > MAX_TACTIC_NAME_LENGTH) return USERSCRIPT_STRINGS.tacticNameMaxLengthError;
  2004. if (completeTactics.hasOwnProperty(v)) return USERSCRIPT_STRINGS.alreadyExistingTacticNameError;
  2005. return null;
  2006. },
  2007. descriptionInput: 'textarea',
  2008. descriptionValue: '',
  2009. descriptionPlaceholder: USERSCRIPT_STRINGS.descriptionPlaceholder,
  2010. descriptionValidator: (d) => {
  2011. if (d && d.length > MAX_DESCRIPTION_LENGTH) return USERSCRIPT_STRINGS.descriptionMaxLengthError;
  2012. return null;
  2013. },
  2014. showCancelButton: true,
  2015. confirmButtonText: USERSCRIPT_STRINGS.saveButton,
  2016. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton,
  2017. });
  2018. if (!result.isConfirmed || !result.value) {
  2019. if (windowHidden) document.getElementById('close_button')?.click();
  2020. return;
  2021. }
  2022. const baseName = result.value;
  2023. const description = result.description || '';
  2024. const fullName = `${baseName} (${getFormattedDate()})`;
  2025. savedData.description = description;
  2026. completeTactics[fullName] = savedData;
  2027. saveCompleteTacticsData();
  2028. updateCompleteTacticsDropdown(fullName);
  2029. if (windowHidden) document.getElementById('close_button')?.click();
  2030. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.completeTacticSaveSuccess.replace('{}', fullName));
  2031. }
  2032.  
  2033. async function loadCompleteTactic() {
  2034. const selectedName = selectedCompleteTacticName;
  2035. if (!selectedName || !completeTactics[selectedName]) return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noTacticSelectedError);
  2036. showLoadingOverlay();
  2037. const originalAlert = window.alert;
  2038. try {
  2039. const dataToLoad = completeTactics[selectedName];
  2040. const currentRoster = await fetchTeamRoster();
  2041. if (!currentRoster) throw new Error(USERSCRIPT_STRINGS.errorFetchingRoster);
  2042. const rosterSet = new Set(currentRoster);
  2043. const originalPids = dataToLoad.originalPlayerIDs || [];
  2044. const mapping = {};
  2045. const missingPids = [];
  2046. const mappedPids = new Set();
  2047. originalPids.forEach(pid => {
  2048. if (rosterSet.has(pid)) {
  2049. mapping[pid] = pid;
  2050. mappedPids.add(pid);
  2051. } else {
  2052. missingPids.push(pid);
  2053. }
  2054. });
  2055. const availablePids = currentRoster.filter(pid => !mappedPids.has(pid));
  2056. let replacementsFound = 0;
  2057. missingPids.forEach(missingPid => {
  2058. if (availablePids.length > 0) {
  2059. const randomIndex = Math.floor(Math.random() * availablePids.length);
  2060. const replacementPid = availablePids.splice(randomIndex, 1)[0];
  2061. mapping[missingPid] = replacementPid;
  2062. replacementsFound++;
  2063. } else {
  2064. mapping[missingPid] = null;
  2065. }
  2066. });
  2067. const assignedPids = new Set();
  2068. dataToLoad.initialCoords.forEach(p => {
  2069. if (mapping[p.pid]) assignedPids.add(mapping[p.pid]);
  2070. });
  2071. dataToLoad.substitutes.forEach(s => {
  2072. if (mapping[s.pid]) assignedPids.add(mapping[s.pid]);
  2073. });
  2074. if (assignedPids.size < MIN_PLAYERS_ON_PITCH) throw new Error(USERSCRIPT_STRINGS.errorInsufficientPlayers);
  2075. let xmlString;
  2076. try {
  2077. xmlString = generateCompleteTacticXml(dataToLoad, mapping);
  2078. } catch (error) {
  2079. console.error("XML Gen Error:", error);
  2080. throw new Error(USERSCRIPT_STRINGS.errorXmlGenerate);
  2081. }
  2082. let alertContent = null;
  2083. window.alert = (msg) => {
  2084. console.warn("Native alert captured:", msg);
  2085. alertContent = msg;
  2086. };
  2087. const importButton = document.getElementById('import_button');
  2088. const importExportWindow = document.getElementById('importExportTacticsWindow');
  2089. const importExportData = document.getElementById('importExportData');
  2090. if (!importButton || !importExportWindow || !importExportData) throw new Error('Could not find required MZ UI elements for import.');
  2091. const windowHidden = importExportWindow.style.display === 'none';
  2092. if (windowHidden) {
  2093. document.getElementById('import_export_button')?.click();
  2094. await new Promise(r => setTimeout(r, 50));
  2095. }
  2096. importExportData.value = xmlString;
  2097. importButton.click();
  2098. await new Promise(r => setTimeout(r, 300));
  2099. window.alert = originalAlert;
  2100. if (alertContent) throw new Error(USERSCRIPT_STRINGS.invalidXmlForImport + (alertContent.length < 100 ? ` MZ Message: ${alertContent}` : ''));
  2101.  
  2102. const observer = new MutationObserver((mutationsList, obs) => {
  2103. for (const mutation of mutationsList) {
  2104. if (mutation.type === 'childList') {
  2105. const errorBox = document.getElementById('lightbox_tactics_rule_error');
  2106. if (errorBox && errorBox.style.display !== 'none') {
  2107. const okButton = errorBox.querySelector('#powerbox_confirm_ok_button');
  2108. if (okButton) {
  2109. okButton.click();
  2110. obs.disconnect();
  2111. break;
  2112. }
  2113. }
  2114. }
  2115. }
  2116. });
  2117. observer.observe(document.body, {
  2118. childList: true,
  2119. subtree: true
  2120. });
  2121. setTimeout(() => observer.disconnect(), 3000);
  2122. if (replacementsFound > 0) {
  2123. showAlert({
  2124. title: 'Warning',
  2125. text: USERSCRIPT_STRINGS.warningPlayersSubstituted,
  2126. type: 'info'
  2127. });
  2128. }
  2129. else showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.completeTacticLoadSuccess.replace('{}', selectedName));
  2130. } catch (error) {
  2131. console.error("Load Complete Tactic Error:", error);
  2132. showErrorMessage(USERSCRIPT_STRINGS.errorTitle, error.message || 'Unknown error during load.');
  2133. if (window.alert !== originalAlert) window.alert = originalAlert;
  2134. } finally {
  2135. hideLoadingOverlay();
  2136. }
  2137. }
  2138.  
  2139. async function deleteCompleteTactic() {
  2140. const selectedName = selectedCompleteTacticName;
  2141. if (!selectedName || !completeTactics[selectedName]) return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noTacticSelectedError);
  2142. const confirmation = await showAlert({
  2143. title: USERSCRIPT_STRINGS.confirmationTitle,
  2144. text: USERSCRIPT_STRINGS.deleteConfirmation.replace('{}', selectedName),
  2145. showCancelButton: true,
  2146. confirmButtonText: USERSCRIPT_STRINGS.deleteTacticConfirmButton,
  2147. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton,
  2148. type: 'error'
  2149. });
  2150. if (!confirmation.isConfirmed) return;
  2151. delete completeTactics[selectedName];
  2152. selectedCompleteTacticName = null;
  2153. saveCompleteTacticsData();
  2154. updateCompleteTacticsDropdown();
  2155. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.completeTacticDeleteSuccess.replace('{}', selectedName));
  2156. }
  2157.  
  2158. async function editCompleteTactic() {
  2159. const selectedName = selectedCompleteTacticName;
  2160. if (!selectedName || !completeTactics[selectedName]) {
  2161. return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noTacticSelectedError);
  2162. }
  2163. const originalTacticData = completeTactics[selectedName];
  2164. const originalDescription = originalTacticData.description || '';
  2165.  
  2166. const result = await showAlert({
  2167. title: USERSCRIPT_STRINGS.renameCompleteTacticPrompt,
  2168. input: 'text',
  2169. inputValue: selectedName,
  2170. placeholder: USERSCRIPT_STRINGS.completeTacticNamePlaceholder,
  2171. inputValidator: (v) => {
  2172. if (!v) return USERSCRIPT_STRINGS.noTacticNameProvidedError;
  2173. if (v.length > MAX_TACTIC_NAME_LENGTH) return USERSCRIPT_STRINGS.tacticNameMaxLengthError;
  2174. if (v !== selectedName && completeTactics.hasOwnProperty(v)) return USERSCRIPT_STRINGS.alreadyExistingTacticNameError;
  2175. return null;
  2176. },
  2177. descriptionInput: 'textarea',
  2178. descriptionValue: originalDescription,
  2179. descriptionPlaceholder: USERSCRIPT_STRINGS.descriptionPlaceholder,
  2180. descriptionValidator: (d) => {
  2181. if (d && d.length > MAX_DESCRIPTION_LENGTH) return USERSCRIPT_STRINGS.descriptionMaxLengthError;
  2182. return null;
  2183. },
  2184. showCancelButton: true,
  2185. confirmButtonText: USERSCRIPT_STRINGS.saveButton,
  2186. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
  2187. });
  2188.  
  2189. if (!result.isConfirmed || !result.value) return;
  2190.  
  2191. const newName = result.value;
  2192. const newDescription = result.description || '';
  2193.  
  2194. if (newName === selectedName && newDescription === originalDescription) return;
  2195.  
  2196. const tacticData = completeTactics[selectedName];
  2197. tacticData.description = newDescription;
  2198.  
  2199. delete completeTactics[selectedName];
  2200. completeTactics[newName] = tacticData;
  2201.  
  2202. saveCompleteTacticsData();
  2203. selectedCompleteTacticName = newName;
  2204. updateCompleteTacticsDropdown(newName);
  2205. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.completeTacticRenameSuccess.replace('{}', newName));
  2206. }
  2207.  
  2208. async function updateCompleteTactic() {
  2209. const selectedName = selectedCompleteTacticName;
  2210. if (!selectedName || !completeTactics[selectedName]) {
  2211. return showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.noTacticSelectedError);
  2212. }
  2213.  
  2214. const confirmation = await showAlert({
  2215. title: USERSCRIPT_STRINGS.confirmationTitle,
  2216. text: USERSCRIPT_STRINGS.updateCompleteTacticConfirmation.replace('{}', selectedName),
  2217. showCancelButton: true,
  2218. confirmButtonText: USERSCRIPT_STRINGS.updateConfirmButton,
  2219. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
  2220. });
  2221.  
  2222. if (!confirmation.isConfirmed) return;
  2223.  
  2224. const originalAlert = window.alert;
  2225. try {
  2226. const exportButton = document.getElementById('export_button');
  2227. const importExportWindow = document.getElementById('importExportTacticsWindow');
  2228. const importExportData = document.getElementById('importExportData');
  2229. if (!exportButton || !importExportWindow || !importExportData) throw new Error('Could not find required MZ UI elements for export.');
  2230.  
  2231. const windowHidden = importExportWindow.style.display === 'none';
  2232. if (windowHidden) {
  2233. document.getElementById('import_export_button')?.click();
  2234. await new Promise(r => setTimeout(r, 50));
  2235. }
  2236.  
  2237. importExportData.value = '';
  2238. exportButton.click();
  2239. await new Promise(r => setTimeout(r, 200));
  2240. const xmlString = importExportData.value;
  2241. if (windowHidden) document.getElementById('close_button')?.click();
  2242.  
  2243. if (!xmlString) throw new Error('Export did not produce XML.');
  2244.  
  2245. let updatedData;
  2246. try {
  2247. updatedData = parseCompleteTacticXml(xmlString);
  2248. } catch (error) {
  2249. console.error("XML Parse Error on Update:", error);
  2250. throw new Error(USERSCRIPT_STRINGS.errorXmlExportParse);
  2251. }
  2252.  
  2253. updatedData.description = completeTactics[selectedName]?.description || '';
  2254. completeTactics[selectedName] = updatedData;
  2255. saveCompleteTacticsData();
  2256. updateCompleteTacticsDropdown(selectedName);
  2257. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.completeTacticUpdateSuccess.replace('{}', selectedName));
  2258.  
  2259. } catch (error) {
  2260. console.error("Update Complete Tactic Error:", error);
  2261. showErrorMessage(USERSCRIPT_STRINGS.errorTitle, error.message || 'Unknown error during update.');
  2262. if (window.alert !== originalAlert) window.alert = originalAlert;
  2263. const importExportWindow = document.getElementById('importExportTacticsWindow');
  2264. if (importExportWindow && importExportWindow.style.display !== 'none') {
  2265. document.getElementById('close_button')?.click();
  2266. }
  2267. }
  2268. }
  2269.  
  2270. async function importCompleteTactics() {
  2271. try {
  2272. const result = await showAlert({
  2273. title: USERSCRIPT_STRINGS.importCompleteTacticsTitle,
  2274. input: 'text',
  2275. inputValue: '',
  2276. placeholder: USERSCRIPT_STRINGS.importCompleteTacticsPlaceholder,
  2277. showCancelButton: true,
  2278. confirmButtonText: USERSCRIPT_STRINGS.importButton,
  2279. cancelButtonText: USERSCRIPT_STRINGS.cancelConfirmButton
  2280. });
  2281.  
  2282. if (!result.isConfirmed || !result.value) return;
  2283.  
  2284. let importedData;
  2285. try {
  2286. importedData = JSON.parse(result.value);
  2287. } catch (e) {
  2288. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.invalidCompleteImportError);
  2289. return;
  2290. }
  2291.  
  2292. if (typeof importedData !== 'object' || importedData === null || Array.isArray(importedData)) {
  2293. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.invalidCompleteImportError);
  2294. return;
  2295. }
  2296.  
  2297. let addedCount = 0;
  2298. let updatedCount = 0;
  2299. for (const name in importedData) {
  2300. if (importedData.hasOwnProperty(name)) {
  2301. if (typeof importedData[name] === 'object' && importedData[name] !== null) {
  2302. if (!importedData[name].hasOwnProperty('description')) importedData[name].description = '';
  2303. if (!completeTactics.hasOwnProperty(name)) {
  2304. addedCount++;
  2305. } else {
  2306. updatedCount++;
  2307. }
  2308. completeTactics[name] = importedData[name];
  2309. } else {
  2310. console.warn(`MZTM: Skipping invalid tactic data during import for key: ${name}`);
  2311. }
  2312. }
  2313. }
  2314.  
  2315. saveCompleteTacticsData();
  2316. updateCompleteTacticsDropdown();
  2317. let message = USERSCRIPT_STRINGS.importCompleteTacticsAlert;
  2318. if (addedCount > 0 || updatedCount > 0) {
  2319. message += ` (${addedCount > 0 ? `${addedCount} new` : ''}${addedCount > 0 && updatedCount > 0 ? ', ' : ''}${updatedCount > 0 ? `${updatedCount} updated` : ''} items)`;
  2320. }
  2321. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, message);
  2322.  
  2323. } catch (error) {
  2324. console.error('Import Complete Tactics Error:', error);
  2325. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, USERSCRIPT_STRINGS.invalidCompleteImportError + (error.message ? `: ${error.message}` : ''));
  2326. }
  2327. }
  2328.  
  2329. async function exportCompleteTactics() {
  2330. try {
  2331. const jsonString = JSON.stringify(completeTactics, null, 2);
  2332. if (navigator.clipboard?.writeText) {
  2333. try {
  2334. await navigator.clipboard.writeText(jsonString);
  2335. await showSuccessMessage(USERSCRIPT_STRINGS.doneTitle, USERSCRIPT_STRINGS.exportCompleteTacticsAlert);
  2336. return;
  2337. } catch (clipError) {
  2338. console.warn('Clipboard write failed, fallback.', clipError);
  2339. }
  2340. }
  2341. const textArea = document.createElement('textarea');
  2342. textArea.value = jsonString;
  2343. textArea.style.width = '100%';
  2344. textArea.style.minHeight = '150px';
  2345. textArea.style.marginTop = '10px';
  2346. textArea.style.backgroundColor = 'rgba(0,0,0,0.2)';
  2347. textArea.style.color = 'var(--text-color)';
  2348. textArea.style.border = '1px solid rgba(255,255,255,0.1)';
  2349. textArea.style.borderRadius = '4px';
  2350. textArea.readOnly = true;
  2351. const container = document.createElement('div');
  2352. container.appendChild(document.createTextNode('Copy the JSON data:'));
  2353. container.appendChild(textArea);
  2354. await showAlert({
  2355. title: USERSCRIPT_STRINGS.exportCompleteTacticsTitle,
  2356. htmlContent: container,
  2357. confirmButtonText: 'Done'
  2358. });
  2359. textArea.select();
  2360. textArea.setSelectionRange(0, 99999);
  2361. } catch (error) {
  2362. console.error('Export Complete Tactics error:', error);
  2363. await showErrorMessage(USERSCRIPT_STRINGS.errorTitle, 'Failed to export tactics.');
  2364. }
  2365. }
  2366.  
  2367. function createTacticPreviewElement() {
  2368. if (previewElement) return previewElement;
  2369. previewElement = document.createElement('div');
  2370. previewElement.id = 'mztm-tactic-preview';
  2371. previewElement.style.display = 'none';
  2372. previewElement.style.opacity = '0';
  2373. previewElement.addEventListener('mouseenter', () => {
  2374. if (previewHideTimeout) clearTimeout(previewHideTimeout);
  2375. });
  2376. previewElement.addEventListener('mouseleave', hideTacticPreview);
  2377. document.body.appendChild(previewElement);
  2378. return previewElement;
  2379. }
  2380.  
  2381. function updatePreviewPosition(event) {
  2382. if (!previewElement || previewElement.style.display === 'none') return;
  2383. const xOffset = 15;
  2384. const yOffset = 10;
  2385. let x = event.clientX + xOffset;
  2386. let y = event.clientY + yOffset;
  2387. const previewRect = previewElement.getBoundingClientRect();
  2388. const viewportWidth = window.innerWidth;
  2389. const viewportHeight = window.innerHeight;
  2390.  
  2391. if (x + previewRect.width > viewportWidth - 10) {
  2392. x = event.clientX - previewRect.width - xOffset;
  2393. }
  2394. if (y + previewRect.height > viewportHeight - 10) {
  2395. y = event.clientY - previewRect.height - yOffset;
  2396. }
  2397. if (x < 10) x = 10;
  2398. if (y < 10) y = 10;
  2399.  
  2400. previewElement.style.left = `${x}px`;
  2401. previewElement.style.top = `${y}px`;
  2402. }
  2403.  
  2404. function showTacticPreview(event, listItem) {
  2405. if (!listItem || listItem.classList.contains('mztm-custom-select-category') || listItem.classList.contains('mztm-custom-select-no-results')) {
  2406. hideTacticPreview();
  2407. return;
  2408. }
  2409.  
  2410. if (previewHideTimeout) clearTimeout(previewHideTimeout);
  2411.  
  2412. const tacticId = listItem.dataset.tacticId;
  2413. const tacticName = listItem.dataset.tacticName;
  2414. const description = listItem.dataset.description || '';
  2415. const formationString = listItem.dataset.formationString || 'N/A';
  2416. const isCompleteTactic = listItem.closest('#complete_tactics_selector_list');
  2417.  
  2418.  
  2419. if (!tacticId && !tacticName) {
  2420. hideTacticPreview();
  2421. return;
  2422. }
  2423.  
  2424. const previewDiv = createTacticPreviewElement();
  2425. previewDiv.innerHTML = `
  2426. <div class="mztm-preview-formation"><strong>${USERSCRIPT_STRINGS.previewFormationLabel}</strong> ${formationString}</div>
  2427. ${description ? `<div class="mztm-preview-desc">${description.replace(/\n/g, '<br>')}</div>` : '<div class="mztm-preview-no-desc">No description available.</div>'}
  2428. `;
  2429. previewDiv.style.display = 'block';
  2430. requestAnimationFrame(() => {
  2431. updatePreviewPosition(event);
  2432. previewDiv.style.opacity = '1';
  2433. });
  2434.  
  2435. document.addEventListener('mousemove', updatePreviewPosition);
  2436. }
  2437.  
  2438. function hideTacticPreview() {
  2439. if (previewHideTimeout) clearTimeout(previewHideTimeout);
  2440. previewHideTimeout = setTimeout(() => {
  2441. if (previewElement) {
  2442. previewElement.style.opacity = '0';
  2443. setTimeout(() => {
  2444. if (previewElement && previewElement.style.opacity === '0') {
  2445. previewElement.style.display = 'none';
  2446. }
  2447. }, 200);
  2448. document.removeEventListener('mousemove', updatePreviewPosition);
  2449. }
  2450. previewHideTimeout = null;
  2451. }, 100);
  2452. }
  2453.  
  2454. function addPreviewListenersToList(listElement) {
  2455. if (!listElement) return;
  2456.  
  2457. listElement.addEventListener('mouseover', (event) => {
  2458. const listItem = event.target.closest('.mztm-custom-select-item');
  2459. if (listItem && !listItem.classList.contains('disabled')) {
  2460. showTacticPreview(event, listItem);
  2461. } else if (!listItem) {
  2462. hideTacticPreview();
  2463. }
  2464. });
  2465.  
  2466. listElement.addEventListener('mouseout', (event) => {
  2467. const listItem = event.target.closest('.mztm-custom-select-item');
  2468. if (listItem) {
  2469. const related = event.relatedTarget;
  2470. if (!listItem.contains(related) && related !== previewElement) {
  2471. hideTacticPreview();
  2472. }
  2473. } else if (!listElement.contains(event.relatedTarget) && (!previewElement || event.relatedTarget !== previewElement)) {
  2474. hideTacticPreview();
  2475. }
  2476. });
  2477.  
  2478. window.addEventListener('scroll', hideTacticPreview, true);
  2479. }
  2480.  
  2481. function closeAllCustomDropdowns(exceptElement = null) {
  2482. document.querySelectorAll('.mztm-custom-select-list-container.open').forEach(container => {
  2483. const wrapper = container.closest('.mztm-custom-select-wrapper');
  2484. if (wrapper !== exceptElement?.closest('.mztm-custom-select-wrapper')) {
  2485. container.classList.remove('open');
  2486. const trigger = wrapper?.querySelector('.mztm-custom-select-trigger');
  2487. trigger?.classList.remove('open');
  2488. }
  2489. });
  2490. currentOpenDropdown = exceptElement?.closest('.mztm-custom-select-wrapper') || null;
  2491. }
  2492.  
  2493. document.addEventListener('click', (event) => {
  2494. if (currentOpenDropdown && !currentOpenDropdown.contains(event.target)) {
  2495. closeAllCustomDropdowns();
  2496. }
  2497. });
  2498.  
  2499. function createCustomSelect(id, placeholderText) {
  2500. const wrapper = document.createElement('div');
  2501. wrapper.className = 'mztm-custom-select-wrapper';
  2502. wrapper.id = `${id}_wrapper`;
  2503.  
  2504. const trigger = document.createElement('div');
  2505. trigger.className = 'mztm-custom-select-trigger';
  2506. trigger.id = `${id}_trigger`;
  2507. trigger.tabIndex = 0;
  2508. const triggerText = document.createElement('span');
  2509. triggerText.className = 'mztm-custom-select-text mztm-custom-select-placeholder';
  2510. triggerText.textContent = placeholderText;
  2511. trigger.appendChild(triggerText);
  2512.  
  2513. const listContainer = document.createElement('div');
  2514. listContainer.className = 'mztm-custom-select-list-container';
  2515. listContainer.id = `${id}_list_container`;
  2516. const list = document.createElement('ul');
  2517. list.className = 'mztm-custom-select-list';
  2518. list.id = `${id}_list`;
  2519. listContainer.appendChild(list);
  2520.  
  2521. addPreviewListenersToList(list);
  2522.  
  2523. trigger.addEventListener('click', (e) => {
  2524. e.stopPropagation();
  2525. const isOpen = listContainer.classList.contains('open');
  2526. closeAllCustomDropdowns(wrapper);
  2527. if (!isOpen && !trigger.classList.contains('disabled')) {
  2528. listContainer.classList.add('open');
  2529. trigger.classList.add('open');
  2530. currentOpenDropdown = wrapper;
  2531. }
  2532. });
  2533.  
  2534. trigger.addEventListener('keydown', (e) => {
  2535. if (e.key === 'Enter' || e.key === ' ') {
  2536. e.preventDefault();
  2537. trigger.click();
  2538. }
  2539. });
  2540.  
  2541. list.addEventListener('click', (e) => {
  2542. const item = e.target.closest('.mztm-custom-select-item');
  2543. if (item && !item.classList.contains('disabled')) {
  2544. const value = item.dataset.value || item.dataset.tacticId || item.dataset.tacticName;
  2545. const text = item.textContent;
  2546.  
  2547. triggerText.textContent = text;
  2548. triggerText.classList.remove('mztm-custom-select-placeholder');
  2549. trigger.dataset.selectedValue = value;
  2550.  
  2551. if (id === 'tactics_selector') {
  2552. handleTacticSelection(value);
  2553. } else if (id === 'complete_tactics_selector') {
  2554. selectedCompleteTacticName = value;
  2555. }
  2556.  
  2557. closeAllCustomDropdowns();
  2558.  
  2559. const changeEvent = new Event('change', { bubbles: true });
  2560. trigger.dispatchEvent(changeEvent);
  2561. }
  2562. });
  2563.  
  2564. wrapper.appendChild(trigger);
  2565. wrapper.appendChild(listContainer);
  2566. return wrapper;
  2567. }
  2568.  
  2569. function createTacticsSelector() {
  2570. const container = document.createElement('div');
  2571. container.className = 'tactics-selector-section';
  2572. const controlsContainer = document.createElement('div');
  2573. controlsContainer.className = 'formations-controls-container';
  2574.  
  2575. const dropdownWrapper = createCustomSelect('tactics_selector', USERSCRIPT_STRINGS.tacticsDropdownMenuLabel);
  2576.  
  2577. const searchBox = document.createElement('input');
  2578. searchBox.type = 'text';
  2579. searchBox.className = 'tactics-search-box';
  2580. searchBox.placeholder = USERSCRIPT_STRINGS.searchPlaceholder;
  2581. searchBox.addEventListener('input', (e) => {
  2582. searchTerm = e.target.value.toLowerCase();
  2583. updateTacticsDropdown(selectedFormationTacticId);
  2584. });
  2585.  
  2586. const filterDropdownWrapper = document.createElement('div');
  2587. filterDropdownWrapper.className = 'category-filter-wrapper';
  2588. const filterSelect = document.createElement('select');
  2589. filterSelect.id = 'category_filter_selector';
  2590. filterSelect.addEventListener('change', (e) => {
  2591. currentFilter = e.target.value;
  2592. GM_setValue(CATEGORY_FILTER_STORAGE_KEY, currentFilter);
  2593. updateTacticsDropdown(selectedFormationTacticId);
  2594. });
  2595.  
  2596. const manageBtn = document.createElement('button');
  2597. manageBtn.id = 'manage_items_btn';
  2598. manageBtn.className = 'mzbtn manage-items-btn';
  2599. manageBtn.innerHTML = '⚙️';
  2600. manageBtn.title = USERSCRIPT_STRINGS.managementModalTitle;
  2601. manageBtn.addEventListener('click', showManagementModal);
  2602. filterDropdownWrapper.appendChild(filterSelect);
  2603. filterDropdownWrapper.appendChild(manageBtn);
  2604.  
  2605. appendChildren(controlsContainer, [dropdownWrapper, searchBox, filterDropdownWrapper]);
  2606. container.appendChild(controlsContainer);
  2607. return container;
  2608. }
  2609.  
  2610. function updateCategoryFilterDropdown() {
  2611. const filterSelect = document.getElementById('category_filter_selector');
  2612. if (!filterSelect) return;
  2613. filterSelect.innerHTML = '';
  2614. const usedCategoryIds = new Set(tactics.map(t => t.style || OTHER_CATEGORY_ID));
  2615. let categoriesToShow = [{
  2616. id: 'all',
  2617. name: USERSCRIPT_STRINGS.allTacticsFilter
  2618. }];
  2619. Object.values(categories)
  2620. .filter(cat => cat.id !== 'all' && (usedCategoryIds.has(cat.id) || Object.keys(DEFAULT_CATEGORIES).includes(cat.id) || cat.id === OTHER_CATEGORY_ID))
  2621. .sort((a, b) => {
  2622. if (a.id === OTHER_CATEGORY_ID) return 1;
  2623. if (b.id === OTHER_CATEGORY_ID) return -1;
  2624. return a.name.localeCompare(b.name);
  2625. })
  2626. .forEach(cat => categoriesToShow.push({ id: cat.id, name: getCategoryName(cat.id) }));
  2627.  
  2628. let foundCurrentFilter = false;
  2629. categoriesToShow.forEach(categoryInfo => {
  2630. const option = document.createElement('option');
  2631. option.value = categoryInfo.id;
  2632. option.textContent = categoryInfo.name;
  2633. filterSelect.appendChild(option);
  2634. if (categoryInfo.id === currentFilter) {
  2635. foundCurrentFilter = true;
  2636. }
  2637. });
  2638.  
  2639. if (foundCurrentFilter) {
  2640. filterSelect.value = currentFilter;
  2641. } else {
  2642. filterSelect.value = 'all';
  2643. currentFilter = 'all';
  2644. GM_setValue(CATEGORY_FILTER_STORAGE_KEY, currentFilter);
  2645. }
  2646.  
  2647. filterSelect.disabled = categoriesToShow.length <= 1;
  2648. }
  2649.  
  2650. function updateTacticsDropdown(currentSelectedId = null) {
  2651. const listElement = document.getElementById('tactics_selector_list');
  2652. const triggerElement = document.getElementById('tactics_selector_trigger');
  2653. const triggerTextElement = triggerElement?.querySelector('.mztm-custom-select-text');
  2654. const wrapper = document.getElementById('tactics_selector_wrapper');
  2655. const searchBox = document.querySelector('.tactics-search-box');
  2656.  
  2657. if (!listElement || !triggerElement || !triggerTextElement || !wrapper) return;
  2658.  
  2659. listElement.innerHTML = '';
  2660.  
  2661. if (searchTerm.length > 0) {
  2662. wrapper.classList.add('filtering');
  2663. searchBox?.classList.add('filtering');
  2664. } else {
  2665. wrapper.classList.remove('filtering');
  2666. searchBox?.classList.remove('filtering');
  2667. }
  2668.  
  2669. const filteredTactics = tactics.filter(t => {
  2670. const nameMatch = searchTerm === '' || t.name.toLowerCase().includes(searchTerm);
  2671. const categoryMatch = currentFilter === 'all' || (currentFilter === OTHER_CATEGORY_ID && (!t.style || t.style === OTHER_CATEGORY_ID)) || t.style === currentFilter;
  2672. return nameMatch && categoryMatch;
  2673. });
  2674.  
  2675. const groupedTactics = {};
  2676. Object.keys(categories).forEach(id => {
  2677. if (id !== 'all') groupedTactics[id] = [];
  2678. });
  2679. if (!groupedTactics[OTHER_CATEGORY_ID]) groupedTactics[OTHER_CATEGORY_ID] = [];
  2680.  
  2681. filteredTactics.forEach(t => {
  2682. const categoryId = t.style || OTHER_CATEGORY_ID;
  2683. if (!groupedTactics[categoryId]) {
  2684. if (!groupedTactics[OTHER_CATEGORY_ID]) groupedTactics[OTHER_CATEGORY_ID] = [];
  2685. groupedTactics[OTHER_CATEGORY_ID].push(t);
  2686. }
  2687. else groupedTactics[categoryId].push(t);
  2688. });
  2689.  
  2690. const categoryOrder = Object.keys(groupedTactics).filter(id => groupedTactics[id].length > 0).sort((a, b) => {
  2691. if (a === currentFilter) return -1;
  2692. if (b === currentFilter) return 1;
  2693. if (DEFAULT_CATEGORIES[a] && !DEFAULT_CATEGORIES[b]) return -1;
  2694. if (!DEFAULT_CATEGORIES[a] && DEFAULT_CATEGORIES[b]) return 1;
  2695. if (a === OTHER_CATEGORY_ID) return 1;
  2696. if (b === OTHER_CATEGORY_ID) return -1;
  2697. return (getCategoryName(a) || '').localeCompare(getCategoryName(b) || '');
  2698. });
  2699.  
  2700. let itemsAdded = 0;
  2701. categoryOrder.forEach(categoryId => {
  2702. if (groupedTactics[categoryId].length > 0) {
  2703. addTacticItemsGroup(listElement, groupedTactics[categoryId], getCategoryName(categoryId), categoryId);
  2704. itemsAdded += groupedTactics[categoryId].length;
  2705. }
  2706. });
  2707.  
  2708. if (itemsAdded === 0) {
  2709. const noResultsItem = document.createElement('li');
  2710. noResultsItem.className = 'mztm-custom-select-no-results';
  2711. noResultsItem.textContent = tactics.length === 0 ? USERSCRIPT_STRINGS.noTacticsSaved : USERSCRIPT_STRINGS.noTacticsFound;
  2712. listElement.appendChild(noResultsItem);
  2713. triggerElement.classList.add('disabled');
  2714. triggerTextElement.textContent = tactics.length === 0 ? USERSCRIPT_STRINGS.noTacticsSaved : USERSCRIPT_STRINGS.tacticsDropdownMenuLabel;
  2715. triggerTextElement.classList.add('mztm-custom-select-placeholder');
  2716. delete triggerElement.dataset.selectedValue;
  2717. selectedFormationTacticId = null;
  2718. } else {
  2719. triggerElement.classList.remove('disabled');
  2720. const currentSelection = tactics.find(t => t.id === currentSelectedId);
  2721. if (currentSelection) {
  2722. triggerTextElement.textContent = currentSelection.name;
  2723. triggerTextElement.classList.remove('mztm-custom-select-placeholder');
  2724. triggerElement.dataset.selectedValue = currentSelection.id;
  2725. selectedFormationTacticId = currentSelection.id;
  2726. } else {
  2727. triggerTextElement.textContent = USERSCRIPT_STRINGS.tacticsDropdownMenuLabel;
  2728. triggerTextElement.classList.add('mztm-custom-select-placeholder');
  2729. delete triggerElement.dataset.selectedValue;
  2730. selectedFormationTacticId = null;
  2731. }
  2732. }
  2733. }
  2734.  
  2735. function addTacticItemsGroup(listElement, tacticsList, groupLabel, categoryId) {
  2736. if (tacticsList.length === 0) return;
  2737.  
  2738. const categoryHeader = document.createElement('li');
  2739. categoryHeader.className = 'mztm-custom-select-category';
  2740. categoryHeader.textContent = groupLabel;
  2741. listElement.appendChild(categoryHeader);
  2742.  
  2743. tacticsList.sort((a, b) => a.name.localeCompare(b.name));
  2744. tacticsList.forEach(tactic => {
  2745. const item = document.createElement('li');
  2746. item.className = 'mztm-custom-select-item';
  2747. item.textContent = tactic.name;
  2748. item.dataset.tacticId = tactic.id;
  2749. item.dataset.value = tactic.id;
  2750. item.dataset.description = tactic.description || '';
  2751. item.dataset.style = tactic.style || OTHER_CATEGORY_ID;
  2752. item.dataset.formationString = formatFormationString(getFormation(tactic.coordinates));
  2753. listElement.appendChild(item);
  2754. });
  2755. }
  2756.  
  2757. function createCompleteTacticsSelector() {
  2758. const container = document.createElement('div');
  2759. container.className = 'tactics-selector-section';
  2760. const label = document.createElement('label');
  2761. label.textContent = '';
  2762. label.className = 'tactics-selector-label';
  2763.  
  2764. const dropdownWrapper = createCustomSelect('complete_tactics_selector', USERSCRIPT_STRINGS.completeTacticsDropdownMenuLabel);
  2765.  
  2766. container.appendChild(label);
  2767. container.appendChild(dropdownWrapper);
  2768. return container;
  2769. }
  2770.  
  2771. function updateCompleteTacticsDropdown(currentSelectedName = null) {
  2772. const listElement = document.getElementById('complete_tactics_selector_list');
  2773. const triggerElement = document.getElementById('complete_tactics_selector_trigger');
  2774. const triggerTextElement = triggerElement?.querySelector('.mztm-custom-select-text');
  2775. const wrapper = document.getElementById('complete_tactics_selector_wrapper');
  2776.  
  2777. if (!listElement || !triggerElement || !triggerTextElement || !wrapper) return;
  2778.  
  2779. listElement.innerHTML = '';
  2780.  
  2781. const names = Object.keys(completeTactics).sort((a, b) => a.localeCompare(b));
  2782.  
  2783. if (names.length === 0) {
  2784. const noResultsItem = document.createElement('li');
  2785. noResultsItem.className = 'mztm-custom-select-no-results';
  2786. noResultsItem.textContent = USERSCRIPT_STRINGS.noCompleteTacticsSaved;
  2787. listElement.appendChild(noResultsItem);
  2788. triggerElement.classList.add('disabled');
  2789. triggerTextElement.textContent = USERSCRIPT_STRINGS.noCompleteTacticsSaved;
  2790. triggerTextElement.classList.add('mztm-custom-select-placeholder');
  2791. delete triggerElement.dataset.selectedValue;
  2792. selectedCompleteTacticName = null;
  2793. } else {
  2794. triggerElement.classList.remove('disabled');
  2795. names.forEach(name => {
  2796. const tactic = completeTactics[name];
  2797. const item = document.createElement('li');
  2798. item.className = 'mztm-custom-select-item';
  2799. item.textContent = name;
  2800. item.dataset.tacticName = name;
  2801. item.dataset.value = name;
  2802. item.dataset.description = tactic.description || '';
  2803. item.dataset.formationString = formatFormationString(getFormationFromCompleteTactic(tactic));
  2804. listElement.appendChild(item);
  2805. });
  2806.  
  2807. const currentSelection = currentSelectedName && completeTactics[currentSelectedName] ? currentSelectedName : null;
  2808.  
  2809. if (currentSelection) {
  2810. triggerTextElement.textContent = currentSelection;
  2811. triggerTextElement.classList.remove('mztm-custom-select-placeholder');
  2812. triggerElement.dataset.selectedValue = currentSelection;
  2813. selectedCompleteTacticName = currentSelection;
  2814. } else {
  2815. triggerTextElement.textContent = USERSCRIPT_STRINGS.completeTacticsDropdownMenuLabel;
  2816. triggerTextElement.classList.add('mztm-custom-select-placeholder');
  2817. delete triggerElement.dataset.selectedValue;
  2818. selectedCompleteTacticName = null;
  2819. }
  2820. }
  2821. }
  2822.  
  2823. function createButton(id, text, clickHandler) {
  2824. const button = document.createElement('button');
  2825. setUpButton(button, id, text);
  2826. if (clickHandler) {
  2827. button.addEventListener('click', async (e) => {
  2828. e.stopPropagation();
  2829. try {
  2830. await clickHandler();
  2831. } catch (err) {
  2832. console.error('Button click failed:', err);
  2833. showErrorMessage('Action Failed', `${err.message || err}`);
  2834. }
  2835. });
  2836. }
  2837. return button;
  2838. }
  2839.  
  2840. async function checkVersion() {
  2841. const savedVersion = GM_getValue(VERSION_KEY, null);
  2842. if (!savedVersion || savedVersion !== SCRIPT_VERSION) {
  2843. await showWelcomeMessage();
  2844. GM_setValue(VERSION_KEY, SCRIPT_VERSION);
  2845. }
  2846. }
  2847.  
  2848. function createModeToggleSwitch() {
  2849. const label = document.createElement('label');
  2850. label.className = 'mode-toggle-switch';
  2851. const input = document.createElement('input');
  2852. input.type = 'checkbox';
  2853. input.id = 'view-mode-toggle';
  2854. input.addEventListener('change', (e) => setViewMode(e.target.checked ? 'complete' : 'normal'));
  2855. const slider = document.createElement('span');
  2856. slider.className = 'mode-toggle-slider';
  2857. label.appendChild(input);
  2858. label.appendChild(slider);
  2859. return label;
  2860. }
  2861.  
  2862. function createModeLabel(mode, isPrefix = false) {
  2863. const span = document.createElement('span');
  2864. span.className = 'mode-toggle-label';
  2865. span.textContent = isPrefix ? USERSCRIPT_STRINGS.modeLabel : (mode === 'normal' ? USERSCRIPT_STRINGS.normalModeLabel : USERSCRIPT_STRINGS.completeModeLabel);
  2866. span.id = `mode-label-${mode}`;
  2867. return span;
  2868. }
  2869.  
  2870. function setViewMode(mode) {
  2871. currentViewMode = mode;
  2872. GM_setValue(VIEW_MODE_KEY, mode);
  2873. const normalContent = document.getElementById('normal-tactics-content');
  2874. const completeContent = document.getElementById('complete-tactics-content');
  2875. const toggleInput = document.getElementById('view-mode-toggle');
  2876. const normalLabel = document.getElementById('mode-label-normal');
  2877. const completeLabel = document.getElementById('mode-label-complete');
  2878. const isNormal = mode === 'normal';
  2879. if (normalContent) normalContent.style.display = isNormal ? 'block' : 'none';
  2880. if (completeContent) completeContent.style.display = isNormal ? 'none' : 'block';
  2881. if (toggleInput) toggleInput.checked = !isNormal;
  2882. if (normalLabel) normalLabel.classList.toggle('active', isNormal);
  2883. if (completeLabel) completeLabel.classList.toggle('active', !isNormal);
  2884. }
  2885.  
  2886. function createMainContainer() {
  2887. const container = document.createElement('div');
  2888. container.id = 'mz_tactics_panel';
  2889. container.classList.add('mz-panel');
  2890. const header = document.createElement('div');
  2891. header.classList.add('mz-group-main-title');
  2892. const titleContainer = document.createElement('div');
  2893. titleContainer.className = 'mz-title-container';
  2894. const titleText = document.createElement('span');
  2895. titleText.textContent = USERSCRIPT_STRINGS.managerTitle;
  2896. titleText.classList.add('mz-main-title');
  2897. const versionText = document.createElement('span');
  2898. versionText.textContent = 'v' + DISPLAY_VERSION;
  2899. versionText.classList.add('mz-version-text');
  2900. const modeToggleContainer = document.createElement('div');
  2901. modeToggleContainer.className = 'mode-toggle-container';
  2902. const prefixLabel = createModeLabel('', true);
  2903. const modeLabelNormal = createModeLabel('normal');
  2904. const toggleSwitch = createModeToggleSwitch();
  2905. const modeLabelComplete = createModeLabel('complete');
  2906. appendChildren(modeToggleContainer, [prefixLabel, modeLabelNormal, toggleSwitch, modeLabelComplete]);
  2907. appendChildren(titleContainer, [titleText, versionText, modeToggleContainer]);
  2908. header.appendChild(titleContainer);
  2909. const toggleButton = createToggleButton();
  2910. header.appendChild(toggleButton);
  2911. container.appendChild(header);
  2912. const group = document.createElement('div');
  2913. group.classList.add('mz-group');
  2914. container.appendChild(group);
  2915.  
  2916. const normalContent = document.createElement('div');
  2917. normalContent.id = 'normal-tactics-content';
  2918. normalContent.className = 'section-content';
  2919. const tacticsSelectorSection = createTacticsSelector();
  2920. const normalButtonsSection = document.createElement('div');
  2921. normalButtonsSection.className = 'action-buttons-section';
  2922. const addCurrentBtn = createButton('add_current_tactic_btn', USERSCRIPT_STRINGS.addCurrentTactic, addNewTactic);
  2923. const addXmlBtn = createButton('add_xml_tactic_btn', USERSCRIPT_STRINGS.addWithXmlButton, addNewTacticWithXml);
  2924. const editBtn = createButton('edit_tactic_button', USERSCRIPT_STRINGS.renameButton, () => editTactic());
  2925. const updateBtn = createButton('update_tactic_button', USERSCRIPT_STRINGS.updateButton, updateTactic);
  2926. const deleteBtn = createButton('delete_tactic_button', USERSCRIPT_STRINGS.deleteButton, deleteTactic);
  2927. const importBtn = createButton('import_tactics_btn', USERSCRIPT_STRINGS.importButton, importTacticsJsonData);
  2928. const exportBtn = createButton('export_tactics_btn', USERSCRIPT_STRINGS.exportButton, exportTacticsJsonData);
  2929. const resetBtn = createButton('reset_tactics_btn', USERSCRIPT_STRINGS.resetButton, resetTactics);
  2930. const clearBtn = createButton('clear_tactics_btn', USERSCRIPT_STRINGS.clearButton, clearTactics);
  2931. const normalButtonsRow1 = document.createElement('div');
  2932. normalButtonsRow1.className = 'action-buttons-row';
  2933. appendChildren(normalButtonsRow1, [addCurrentBtn, addXmlBtn, editBtn, updateBtn, deleteBtn]);
  2934. const normalButtonsRow2 = document.createElement('div');
  2935. normalButtonsRow2.className = 'action-buttons-row';
  2936. appendChildren(normalButtonsRow2, [importBtn, exportBtn, resetBtn, clearBtn]);
  2937. appendChildren(normalButtonsSection, [normalButtonsRow1, normalButtonsRow2]);
  2938. appendChildren(normalContent, [tacticsSelectorSection, normalButtonsSection, createHiddenTriggerButton(), createCombinedInfoButton()]);
  2939. group.appendChild(normalContent);
  2940.  
  2941. const completeContent = document.createElement('div');
  2942. completeContent.id = 'complete-tactics-content';
  2943. completeContent.className = 'section-content';
  2944. completeContent.style.display = 'none';
  2945. const completeTacticsSelectorSection = createCompleteTacticsSelector();
  2946. const completeButtonsSection = document.createElement('div');
  2947. completeButtonsSection.className = 'action-buttons-section';
  2948. const completeButtonsRow1 = document.createElement('div');
  2949. completeButtonsRow1.className = 'action-buttons-row';
  2950. const saveCompleteBtn = createButton('save_complete_tactic_button', USERSCRIPT_STRINGS.saveCompleteTacticButton, saveCompleteTactic);
  2951. const loadCompleteBtn = createButton('load_complete_tactic_button', USERSCRIPT_STRINGS.loadCompleteTacticButton, loadCompleteTactic);
  2952. const renameCompleteBtn = createButton('rename_complete_tactic_button', USERSCRIPT_STRINGS.renameCompleteTacticButton, editCompleteTactic);
  2953. const updateCompleteBtn = createButton('update_complete_tactic_button', USERSCRIPT_STRINGS.updateCompleteTacticButton, updateCompleteTactic);
  2954. const deleteCompleteBtn = createButton('delete_complete_tactic_button', USERSCRIPT_STRINGS.deleteCompleteTacticButton, deleteCompleteTactic);
  2955. appendChildren(completeButtonsRow1, [saveCompleteBtn, loadCompleteBtn, renameCompleteBtn, updateCompleteBtn, deleteCompleteBtn]);
  2956. const completeButtonsRow2 = document.createElement('div');
  2957. completeButtonsRow2.className = 'action-buttons-row';
  2958. const importCompleteBtn = createButton('import_complete_tactics_btn', USERSCRIPT_STRINGS.importCompleteTacticsButton, importCompleteTactics);
  2959. const exportCompleteBtn = createButton('export_complete_tactics_btn', USERSCRIPT_STRINGS.exportCompleteTacticsButton, exportCompleteTactics);
  2960. appendChildren(completeButtonsRow2, [importCompleteBtn, exportCompleteBtn]);
  2961. appendChildren(completeButtonsSection, [completeButtonsRow1, completeButtonsRow2]);
  2962. appendChildren(completeContent, [completeTacticsSelectorSection, completeButtonsSection, createCombinedInfoButton()]);
  2963. group.appendChild(completeContent);
  2964.  
  2965. return container;
  2966. }
  2967.  
  2968. function createHiddenTriggerButton() {
  2969. const button = document.createElement('button');
  2970. button.id = 'hidden_trigger_button';
  2971. button.textContent = '';
  2972. button.style.cssText = 'position:absolute; opacity:0; pointer-events:none; width:0; height:0; padding:0; margin:0; border:0;';
  2973. button.addEventListener('click', function () {
  2974. const presetSelect = document.getElementById('tactics_preset');
  2975. if (presetSelect) {
  2976. presetSelect.value = '5-3-2';
  2977. presetSelect.dispatchEvent(new Event('change'));
  2978. }
  2979. });
  2980. return button;
  2981. }
  2982.  
  2983. function setUpButton(button, id, text) {
  2984. button.id = id;
  2985. button.classList.add('mzbtn');
  2986. button.textContent = text;
  2987. }
  2988.  
  2989. function createModalTabs(tabsConfig, modalBody) {
  2990. const tabsContainer = document.createElement('div');
  2991. tabsContainer.className = 'modal-tabs';
  2992. tabsConfig.forEach((tab, index) => {
  2993. const tabButton = document.createElement('button');
  2994. tabButton.className = 'modal-tab';
  2995. tabButton.textContent = tab.title;
  2996. tabButton.dataset.tabId = tab.id;
  2997. if (index === 0) tabButton.classList.add('active');
  2998. tabButton.addEventListener('click', () => {
  2999. modalBody.querySelectorAll('.modal-tab').forEach(t => t.classList.remove('active'));
  3000. modalBody.querySelectorAll('.management-modal-content, .modal-tab-content').forEach(c => c.classList.remove('active'));
  3001. tabButton.classList.add('active');
  3002. const content = modalBody.querySelector(`.management-modal-content[data-tab-id="${tab.id}"], .modal-tab-content[data-tab-id="${tab.id}"]`);
  3003. if (content) content.classList.add('active');
  3004. });
  3005. tabsContainer.appendChild(tabButton);
  3006. });
  3007. return tabsContainer;
  3008. }
  3009.  
  3010. function createTabbedModalContent(tabsConfig) {
  3011. const wrapper = document.createElement('div');
  3012. wrapper.className = 'modal-info-wrapper';
  3013. const tabs = createModalTabs(tabsConfig, wrapper);
  3014. wrapper.appendChild(tabs);
  3015. tabsConfig.forEach((tab, index) => {
  3016. const contentDiv = document.createElement('div');
  3017. contentDiv.className = 'modal-tab-content';
  3018. contentDiv.dataset.tabId = tab.id;
  3019. if (index === 0) contentDiv.classList.add('active');
  3020. const content = tab.contentGenerator();
  3021. contentDiv.appendChild(content);
  3022. wrapper.appendChild(contentDiv);
  3023. });
  3024. return wrapper;
  3025. }
  3026.  
  3027. function createAboutTabContent() {
  3028. const content = document.createElement('div');
  3029. const aboutSection = document.createElement('div');
  3030. const aboutTitle = document.createElement('h3');
  3031. aboutTitle.textContent = 'About';
  3032. const infoText = document.createElement('p');
  3033. infoText.id = 'info_modal_info_text';
  3034. infoText.innerHTML = USERSCRIPT_STRINGS.modalContentInfoText;
  3035. const feedbackText = document.createElement('p');
  3036. feedbackText.id = 'info_modal_feedback_text';
  3037. feedbackText.innerHTML = USERSCRIPT_STRINGS.modalContentFeedbackText;
  3038. appendChildren(aboutSection, [aboutTitle, infoText, feedbackText]);
  3039. content.appendChild(aboutSection);
  3040. const faqSection = document.createElement('div');
  3041. faqSection.className = 'faq-section';
  3042. const faqTitle = document.createElement('h3');
  3043. faqTitle.textContent = 'FAQ/Function Explanations';
  3044. faqSection.appendChild(faqTitle);
  3045.  
  3046. const formationItems = [
  3047. { q: "<code>Add Current</code> 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." },
  3048. { q: "<code>Add via XML</code> 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." },
  3049. { q: "Category Filter Dropdown & <code>⚙️</code> 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)." },
  3050. { q: "<code>Edit</code> Button (Formations Mode)", a: "Allows renaming the selected formation, changing its assigned category, and editing its description via a popup." },
  3051. { q: "<code>Update Coords</code> 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)." },
  3052. { q: "<code>Delete</code> Button (Formations Mode)", a: "Permanently removes the selected formation from the storage." },
  3053. { q: "<code>Import</code> Button (Formations Mode)", a: "Imports multiple formations from a JSON text format. Merges with existing formations (updates name/category/description if ID matches)." },
  3054. { q: "<code>Export</code> Button (Formations Mode)", a: "Exports all saved formations (including descriptions) into a JSON text format (copied to clipboard)." },
  3055. { q: "<code>Reset</code> Button (Formations Mode)", a: "Deletes all saved formations and custom categories, restoring defaults. Also resets the saved category filter." },
  3056. { q: "<code>Clear</code> Button (Formations Mode)", a: "Deletes all saved formations. Also resets the saved category filter." },
  3057. { q: "Management Modal (Gear Icon ⚙️)", a: "Opens a dedicated window to manage formations (edit name/description/category, delete) and categories (add, remove) in bulk." },
  3058. { 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." }
  3059. ];
  3060.  
  3061. const tacticItems = [
  3062. { q: "<code>Save Current</code> 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." },
  3063. { q: "<code>Load</code> 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." },
  3064. { q: "<code>Rename</code> Button (Tactics Mode)", a: "Allows renaming the selected complete tactic and editing its description via a popup." },
  3065. { q: "<code>Update with Current</code> 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." },
  3066. { q: "<code>Delete</code> Button (Tactics Mode)", a: "Permanently removes the selected complete tactic." },
  3067. { q: "<code>Import</code> 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)." },
  3068. { q: "<code>Export</code> Button (Tactics Mode)", a: "Exports all saved complete tactics (including descriptions) into a JSON text format (copied to clipboard)." },
  3069. { 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." }
  3070. ];
  3071.  
  3072. const combinedItems = [...formationItems, ...tacticItems].sort((a, b) => {
  3073. 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);
  3074. 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);
  3075. if (modeA !== modeB) return modeA - modeB;
  3076. return a.q.localeCompare(b.q);
  3077. });
  3078.  
  3079. combinedItems.forEach(item => {
  3080. const faqItemDiv = document.createElement('div');
  3081. faqItemDiv.className = 'faq-item';
  3082. const question = document.createElement('h4');
  3083. question.innerHTML = item.q;
  3084. const answer = document.createElement('p');
  3085. answer.textContent = item.a;
  3086. appendChildren(faqItemDiv, [question, answer]);
  3087. faqSection.appendChild(faqItemDiv);
  3088. });
  3089. content.appendChild(faqSection);
  3090. return content;
  3091. }
  3092.  
  3093. function createLinksTabContent() {
  3094. const content = document.createElement('div');
  3095. const linksSection = document.createElement('div');
  3096. const linksTitle = document.createElement('h3');
  3097. linksTitle.textContent = 'Useful Links';
  3098. const resourcesText = createUsefulContent();
  3099. const linksMap = new Map([
  3100. ['gewlaht - BoooM', 'https://www.managerzone.com/?p=forum&sub=topic&topic_id=11415137&forum_id=49&sport=soccer'],
  3101. ['taktikskola by honken91', 'https://www.managerzone.com/?p=forum&sub=topic&topic_id=12653892&forum_id=4&sport=soccer'],
  3102. ['peto - mix de dibujos', 'https://www.managerzone.com/?p=forum&sub=topic&topic_id=12196312&forum_id=255&sport=soccer'],
  3103. ['The Zone Chile', 'https://www.managerzone.com/thezone/paper.php?paper_id=18036&page=9&sport=soccer'],
  3104. ['Tactics guide by lukasz87o/filipek4', 'https://www.managerzone.com/?p=forum&sub=topic&topic_id=12766444&forum_id=12&sport=soccer&share_sport=soccer'],
  3105. ['MZExtension/van.mz.playerAdvanced by vanjoge', 'https://greasyfork.org/en/scripts/373382-van-mz-playeradvanced'],
  3106. ['Mazyar Userscript', 'https://greasyfork.org/en/scripts/476290-mazyar'],
  3107. ['Stats Xente Userscript', 'https://greasyfork.org/en/scripts/491442-stats-xente-script'],
  3108. ['More userscripts', 'https://greasyfork.org/en/users/1088808-douglasdotv']
  3109. ]);
  3110. const linksList = createLinksList(linksMap);
  3111. appendChildren(linksSection, [linksTitle, resourcesText, linksList]);
  3112. content.appendChild(linksSection);
  3113. return content;
  3114. }
  3115.  
  3116. function createCombinedInfoButton() {
  3117. const button = createButton('info_button', USERSCRIPT_STRINGS.infoButton, null);
  3118. button.classList.add('footer-actions');
  3119. button.style.background = 'transparent';
  3120. button.style.border = 'none';
  3121. button.style.boxShadow = 'none';
  3122. button.style.fontFamily = '"Quicksand", sans-serif';
  3123. button.style.color = 'gold';
  3124. button.addEventListener('click', (e) => {
  3125. e.stopPropagation();
  3126. const tabsConfig = [{
  3127. id: 'about',
  3128. title: 'About & FAQ',
  3129. contentGenerator: createAboutTabContent
  3130. }, {
  3131. id: 'links',
  3132. title: 'Useful Links',
  3133. contentGenerator: createLinksTabContent
  3134. }];
  3135. const modalContent = createTabbedModalContent(tabsConfig);
  3136. showAlert({
  3137. title: 'MZ Tactics Manager Info',
  3138. htmlContent: modalContent,
  3139. confirmButtonText: DEFAULT_MODAL_STRINGS.ok
  3140. });
  3141. });
  3142. return button;
  3143. }
  3144.  
  3145. function createUsefulContent() {
  3146. const p = document.createElement('p');
  3147. p.id = 'useful_content';
  3148. p.textContent = USERSCRIPT_STRINGS.usefulContent;
  3149. return p;
  3150. }
  3151.  
  3152. function createLinksList(linksMap) {
  3153. const list = document.createElement('ul');
  3154. linksMap.forEach((href, text) => {
  3155. const listItem = document.createElement('li');
  3156. const anchor = document.createElement('a');
  3157. anchor.href = href;
  3158. anchor.target = '_blank';
  3159. anchor.rel = 'noopener noreferrer';
  3160. anchor.textContent = text;
  3161. listItem.appendChild(anchor);
  3162. list.appendChild(listItem);
  3163. });
  3164. return list;
  3165. }
  3166.  
  3167. function createToggleButton() {
  3168. const button = document.createElement('button');
  3169. button.id = 'toggle_panel_btn';
  3170. button.innerHTML = '✕';
  3171. button.title = 'Hide panel';
  3172. return button;
  3173. }
  3174.  
  3175. function createCollapsedIcon() {
  3176. const icon = document.createElement('div');
  3177. icon.id = 'collapsed_icon';
  3178. icon.innerHTML = 'TM';
  3179. icon.title = 'Show MZ Tactics Manager';
  3180. collapsedIconElement = icon;
  3181. return icon;
  3182. }
  3183.  
  3184. async function initializeScriptData() {
  3185. loadCategories();
  3186. currentFilter = GM_getValue(CATEGORY_FILTER_STORAGE_KEY, 'all');
  3187. const ids = await fetchTeamIdAndUsername();
  3188. if (!ids.teamId) {
  3189. console.warn("MZTM: Failed to get Team ID.");
  3190. }
  3191. let tacticData = GM_getValue(FORMATIONS_STORAGE_KEY);
  3192. const oldTacticData = GM_getValue(OLD_FORMATIONS_STORAGE_KEY);
  3193. if (!tacticData && oldTacticData && oldTacticData.tactics && Array.isArray(oldTacticData.tactics)) {
  3194. console.log(`MZTM: Migrating tactics from old storage key '${OLD_FORMATIONS_STORAGE_KEY}' to '${FORMATIONS_STORAGE_KEY}'.`);
  3195. tacticData = oldTacticData;
  3196. tacticData.tactics = tacticData.tactics.filter(t => t && t.name && t.id && Array.isArray(t.coordinates));
  3197. tacticData.tactics.forEach(t => {
  3198. if (!t.hasOwnProperty('style')) t.style = OTHER_CATEGORY_ID;
  3199. if (!t.hasOwnProperty('description')) t.description = '';
  3200. });
  3201. GM_setValue(FORMATIONS_STORAGE_KEY, tacticData);
  3202. GM_deleteValue(OLD_FORMATIONS_STORAGE_KEY);
  3203. console.log(`MZTM: Migration complete. Deleted old key '${OLD_FORMATIONS_STORAGE_KEY}'.`);
  3204. } else if (!tacticData) {
  3205. console.log("MZTM: No existing formations data found. Initializing empty store.");
  3206. tacticData = {
  3207. tactics: []
  3208. };
  3209. GM_setValue(FORMATIONS_STORAGE_KEY, tacticData);
  3210. } else {
  3211. if (!tacticData.tactics || !Array.isArray(tacticData.tactics)) tacticData.tactics = [];
  3212. tacticData.tactics = tacticData.tactics.filter(t => t && t.name && t.id && Array.isArray(t.coordinates));
  3213. let dataChanged = false;
  3214. tacticData.tactics.forEach(t => {
  3215. if (!t.hasOwnProperty('style')) {
  3216. t.style = OTHER_CATEGORY_ID;
  3217. dataChanged = true;
  3218. }
  3219. if (!t.hasOwnProperty('description')) {
  3220. t.description = '';
  3221. dataChanged = true;
  3222. }
  3223. });
  3224. if (dataChanged) GM_setValue(FORMATIONS_STORAGE_KEY, tacticData);
  3225. }
  3226. tactics = tacticData.tactics || [];
  3227. tactics.sort((a, b) => a.name.localeCompare(b.name));
  3228. loadCompleteTacticsData();
  3229. const storedCompleteTactics = GM_getValue(COMPLETE_TACTICS_STORAGE_KEY, {});
  3230. let completeTacticsChanged = false;
  3231. for (const name in storedCompleteTactics) {
  3232. if (storedCompleteTactics.hasOwnProperty(name)) {
  3233. if (!storedCompleteTactics[name].hasOwnProperty('description')) {
  3234. storedCompleteTactics[name].description = '';
  3235. completeTacticsChanged = true;
  3236. }
  3237. }
  3238. }
  3239. if (completeTacticsChanged) GM_setValue(COMPLETE_TACTICS_STORAGE_KEY, storedCompleteTactics);
  3240. completeTactics = storedCompleteTactics;
  3241. await checkVersion();
  3242. }
  3243.  
  3244. function setUpTacticsInterface(mainContainer) {
  3245. const toggleButton = mainContainer.querySelector('#toggle_panel_btn');
  3246. const collapsedIcon = collapsedIconElement || createCollapsedIcon();
  3247. let isCollapsed = GM_getValue(COLLAPSED_KEY, false);
  3248. const anchorButtonId = 'replace-player-btn';
  3249. const applyCollapseState = (instant = false) => {
  3250. const anchorButton = document.getElementById(anchorButtonId);
  3251. if (collapsedIcon && collapsedIcon.parentNode) {
  3252. collapsedIcon.parentNode.removeChild(collapsedIcon);
  3253. }
  3254. if (isCollapsed) {
  3255. if (instant) {
  3256. mainContainer.style.transition = 'none';
  3257. mainContainer.classList.add('collapsed');
  3258. void mainContainer.offsetHeight;
  3259. mainContainer.style.transition = '';
  3260. } else {
  3261. mainContainer.classList.add('collapsed');
  3262. }
  3263. toggleButton.innerHTML = '☰';
  3264. toggleButton.title = 'Show panel';
  3265. if (anchorButton) {
  3266. insertAfterElement(collapsedIcon, anchorButton);
  3267. collapsedIcon.classList.add('visible');
  3268. } else {
  3269. console.warn(`MZTM: Anchor button #${anchorButtonId} not found for collapsed icon.`);
  3270. collapsedIcon.classList.remove('visible');
  3271. }
  3272. } else {
  3273. mainContainer.classList.remove('collapsed');
  3274. toggleButton.innerHTML = '✕';
  3275. toggleButton.title = 'Hide panel';
  3276. collapsedIcon.classList.remove('visible');
  3277. }
  3278. };
  3279. applyCollapseState(true);
  3280.  
  3281. function togglePanel() {
  3282. isCollapsed = !isCollapsed;
  3283. GM_setValue(COLLAPSED_KEY, isCollapsed);
  3284. applyCollapseState();
  3285. }
  3286. toggleButton.addEventListener('click', (e) => {
  3287. e.stopPropagation();
  3288. togglePanel();
  3289. });
  3290. collapsedIcon.addEventListener('click', () => {
  3291. togglePanel();
  3292. });
  3293. }
  3294.  
  3295. async function initialize() {
  3296. const tacticsBox = document.getElementById('tactics_box');
  3297. if (!tacticsBox || !isFootball()) {
  3298. console.log("MZTM: Not on valid page or tactics box not found.");
  3299. return;
  3300. }
  3301. const cachedUserInfo = GM_getValue(USER_INFO_CACHE_KEY);
  3302. if (cachedUserInfo && typeof cachedUserInfo === 'object' && cachedUserInfo.teamId && cachedUserInfo.username && cachedUserInfo.timestamp) {
  3303. userInfoCache = cachedUserInfo;
  3304. if (Date.now() - userInfoCache.timestamp < USER_INFO_CACHE_DURATION_MS) {
  3305. teamId = userInfoCache.teamId;
  3306. username = userInfoCache.username;
  3307. }
  3308. }
  3309. const cachedRoster = GM_getValue(ROSTER_CACHE_KEY);
  3310. if (cachedRoster && typeof cachedRoster === 'object' && cachedRoster.data && cachedRoster.timestamp) {
  3311. rosterCache = cachedRoster;
  3312. }
  3313. try {
  3314. collapsedIconElement = createCollapsedIcon();
  3315. createTacticPreviewElement();
  3316. await initializeScriptData();
  3317. const mainContainer = createMainContainer();
  3318. setUpTacticsInterface(mainContainer);
  3319. insertAfterElement(mainContainer, tacticsBox);
  3320. updateTacticsDropdown();
  3321. updateCategoryFilterDropdown();
  3322. updateCompleteTacticsDropdown();
  3323. const savedMode = GM_getValue(VIEW_MODE_KEY, 'normal');
  3324. setViewMode(savedMode);
  3325. } catch (error) {
  3326. console.error('MZTM Initialization Error:', error);
  3327. const errorDiv = document.createElement('div');
  3328. errorDiv.textContent = 'Error initializing MZ Tactics Manager. Check console for details.';
  3329. errorDiv.style.cssText = 'color:red; padding:10px; border:1px solid red; margin:10px;';
  3330. insertAfterElement(errorDiv, tacticsBox);
  3331. }
  3332. }
  3333.  
  3334. window.addEventListener('load', initialize);
  3335. })();