Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Join the Playtest on Steam Now: SpiritVale

Module:GameSkills: Difference between revisions

From SpiritVale Wiki
No edit summary
No edit summary
Line 3: Line 3:
-- Phase 6.5+ (Plug-in Slot Architecture)
-- Phase 6.5+ (Plug-in Slot Architecture)
--
--
-- Standard Hero Layout (reused across the wiki):
-- Standard Hero Layout:
--  1) hero-title-bar        (TOP BAR, 2 slots: herobar 1..2)
--  1) hero-title-bar        (TOP BAR, 2 slots: herobar 1..2)
--        - Herobar 1: Icon + Skill Name (left)
--  2) hero-description-bar  (description strip)
--        - Herobar 2: Reserved for compact info (right)
--  2) hero-description-bar  (description strip) [special-cased for now]
--  3) hero-modules row      (4 slots: hero-module-1..4)
--  3) hero-modules row      (4 slots: hero-module-1..4)
--        - Slot 1: Level Selector
--        - Slot 2: Skill Type
--        - Slot 3: SourceType (Modifier + Source + Scaling) OR blank
--        - Slot 4: Quick Stats (Range/Area/Cost/Cast/Cooldown/Duration)
--
--
-- Requires Common.js logic that updates:
-- Requires Common.js:
--  - .sv-dyn spans via data-series
--  - updates .sv-dyn spans via data-series
--  - .sv-level-num + data-level on .sv-skill-card
--  - updates .sv-level-num + data-level on .sv-skill-card
--  - binds to input.sv-level-range inside each card
--  - binds to input.sv-level-range inside each card
--
-- Upgrade: shared slot wrapper classes
--  - .sv-hero-slot and .sv-hero-slot-body are applied to BOTH:
--      * hero-bar-module (hero bar)
--      * hero-module    (tile grid)
--  This allows "real" modules (SkillType/SourceType/QuickStats/etc.) to be moved
--  between slots without CSS refactors.


local GameData = require("Module:GameData")
local GameData = require("Module:GameData")
Line 112: Line 99:
end
end


local function kebabCase(s)
if type(s) ~= "string" then
return nil
end
-- Handle "ABc" boundaries, then "aB" boundaries
s = mw.ustring.gsub(s, "([A-Z]+)([A-Z][a-z])", "%1-%2")
s = mw.ustring.gsub(s, "([a-z0-9])([A-Z])", "%1-%2")
s = mw.ustring.lower(s)
return s
end
-- Add a labeled infobox row (with optional hooks for future)
local function addRow(tbl, label, value, rowClass, dataKey)
local function addRow(tbl, label, value, rowClass, dataKey)
if value == nil or value == "" then
if value == nil or value == "" then
Line 131: Line 106:
local row = tbl:tag("tr")
local row = tbl:tag("tr")
row:addClass("sv-row")
row:addClass("sv-row")
if rowClass then
if rowClass then row:addClass(rowClass) end
row:addClass(rowClass)
if dataKey then row:attr("data-field", dataKey) end
end
if dataKey then
row:attr("data-field", dataKey)
end


row:tag("th"):wikitext(label):done()
row:tag("th"):wikitext(label):done()
Line 142: Line 113:
end
end


-- Handles either a scalar OR { Value = ..., Unit = ... }
-- { Value, Unit } or scalar
-- IMPORTANT: wikiprep often converts unit-wrapped pairs into strings already.
local function formatUnitValue(v)
local function formatUnitValue(v)
if type(v) == "table" and v.Value ~= nil then
if type(v) == "table" and v.Value ~= nil then
Line 200: Line 170:


local function isNonZeroScalar(v)
local function isNonZeroScalar(v)
if v == nil then
if v == nil then return false end
return false
if type(v) == "number" then return v ~= 0 end
end
if type(v) == "number" then
return v ~= 0
end
if type(v) == "string" then
if type(v) == "string" then
local n = tonumber(v)
local n = tonumber(v)
if n == nil then
if n == nil then return v ~= "" end
return v ~= ""
end
return n ~= 0
return n ~= 0
end
end
Line 225: Line 189:
return isZeroish(v.Value)
return isZeroish(v.Value)
end
end
local s = mw.text.trim(tostring(v))
local s = mw.text.trim(tostring(v))
if s == "" then return true end
if s == "" then return true end
-- common “0” shapes once wikiprep has stringified
if s == "0" or s == "0.0" or s == "0.00" then return true end
if s == "0" or s == "0.0" or s == "0.00" then return true end
if s == "0s" or s == "0 s" then return true end
if s == "0s" or s == "0 s" then return true end
if s == "0m" or s == "0 m" then return true end
if s == "0m" or s == "0 m" then return true end
if s == "0%" or s == "0 %" then return true end
if s == "0%" or s == "0 %" then return true end
-- numeric-with-unit like "0.0000s"
 
local n = tonumber((mw.ustring.gsub(s, "[^0-9%.%-]", "")))
local n = tonumber((mw.ustring.gsub(s, "[^0-9%.%-]", "")))
return (n ~= nil and n == 0)
return (n ~= nil and n == 0)
end
end


-- Base/Per Level renderer:
local function valuePairRawText(block)
-- - Per Level list -> dynamic span (or single value if flat)
-- - Per Level scalar -> "Base" + "Per Level" lines
local function valuePairDynamicLines(name, block, maxLevel, level)
if type(block) ~= "table" then
if type(block) ~= "table" then
return {}
return nil
end
end


Line 248: Line 209:
local per  = block["Per Level"]
local per  = block["Per Level"]


-- Per Level list (expanded by wikiprep)
if type(per) == "table" then
if type(per) == "table" then
if #per == 0 then
if #per == 0 then
local baseText = formatUnitValue(base)
return formatUnitValue(base)
return baseText and { string.format("%s: %s", name, mw.text.nowiki(baseText)) } or {}
end
end
if isFlatList(per) then
if isFlatList(per) then
local baseText = formatUnitValue(base)
return formatUnitValue(base) or tostring(per[1])
local one = formatUnitValue(per[1]) or tostring(per[1])
local show = baseText or one
return show and { string.format("%s: %s", name, mw.text.nowiki(show)) } or {}
end
end


local series = {}
local vals = {}
for _, v in ipairs(per) do
for _, v in ipairs(per) do
table.insert(series, formatUnitValue(v) or tostring(v))
table.insert(vals, formatUnitValue(v) or tostring(v))
end
end
 
return (#vals > 0) and table.concat(vals, " / ") or nil
local dyn = dynSpan(series, level)
return dyn and { string.format("%s: %s", name, dyn) } or {}
end
end


-- scalar Per Level
local lines = {}
local baseText = formatUnitValue(base)
local baseText = formatUnitValue(base)
local perText  = formatUnitValue(per)
local perText  = formatUnitValue(per)


if baseText then
if baseText and perText and isNonZeroScalar(per) then
table.insert(lines, string.format("%s: %s", name, mw.text.nowiki(baseText)))
return string.format("%s (Per Level: %s)", baseText, perText)
end
if perText and isNonZeroScalar(per) then
table.insert(lines, string.format("%s Per Level: %s", name, mw.text.nowiki(perText)))
end
end


return lines
return baseText or perText
end
end


local function valuePairDynamicText(name, block, maxLevel, level, sep)
local function valuePairDynamicValueOnly(block, maxLevel, level)
local lines = valuePairDynamicLines(name, block, maxLevel, level)
return (#lines > 0) and table.concat(lines, sep or "<br />") or nil
end
 
local function valuePairRawText(block)
if type(block) ~= "table" then
if type(block) ~= "table" then
return nil
return nil
Line 301: Line 244:
if type(per) == "table" then
if type(per) == "table" then
if #per == 0 then
if #per == 0 then
return formatUnitValue(base)
local baseText = formatUnitValue(base)
return baseText and mw.text.nowiki(baseText) or nil
end
end
if isFlatList(per) then
if isFlatList(per) then
return formatUnitValue(base) or tostring(per[1])
local one  = formatUnitValue(per[1]) or tostring(per[1])
local show = formatUnitValue(base) or one
return show and mw.text.nowiki(show) or nil
end
end


local vals = {}
local series = {}
for _, v in ipairs(per) do
for _, v in ipairs(per) do
table.insert(vals, formatUnitValue(v) or tostring(v))
table.insert(series, formatUnitValue(v) or tostring(v))
end
end
return (#vals > 0) and table.concat(vals, " / ") or nil
return dynSpan(series, level)
end
end


local baseText = formatUnitValue(base)
local txt = valuePairRawText(block)
local perText  = formatUnitValue(per)
return txt and mw.text.nowiki(txt) or nil
end


if baseText and perText and isNonZeroScalar(per) then
----------------------------------------------------------------------
return string.format("%s (Per Level: %s)", baseText, perText)
-- Lookups
end
----------------------------------------------------------------------


return baseText or perText
local function getSkillById(id)
id = trim(id)
if not id then return nil end
local dataset = getSkills()
return (dataset.byId or {})[id]
end
end


-- Prefer “value only” (dynSpan when series list exists)
local function findSkillByName(name)
local function valuePairDynamicValueOnly(block, maxLevel, level)
name = trim(name)
if type(block) ~= "table" then
if not name then return nil end
return nil
end


local base = block.Base
local dataset = getSkills()
local per  = block["Per Level"]
local byName = dataset.byName or {}


if type(per) == "table" then
if byName[name] then
if #per == 0 then
return byName[name]
local baseText = formatUnitValue(base)
end
return baseText and mw.text.nowiki(baseText) or nil
end


if isFlatList(per) then
for _, rec in ipairs(dataset.records or {}) do
local one  = formatUnitValue(per[1]) or tostring(per[1])
if type(rec) == "table" then
local show = formatUnitValue(base) or one
if rec["External Name"] == name or rec.Name == name or rec["Display Name"] == name then
return show and mw.text.nowiki(show) or nil
return rec
end
end
end
local series = {}
for _, v in ipairs(per) do
table.insert(series, formatUnitValue(v) or tostring(v))
end
return dynSpan(series, level)
end
end


local txt = valuePairRawText(block)
return nil
return txt and mw.text.nowiki(txt) or nil
end
end


----------------------------------------------------------------------
----------------------------------------------------------------------
-- Lookups
-- Legacy damage helpers
----------------------------------------------------------------------
----------------------------------------------------------------------


local function getSkillById(id)
local function basisLabel(entry, isHealing)
id = trim(id)
if isHealing then
if not id then
return "Healing"
return nil
end
end
local dataset = getSkills()
return (dataset.byId or {})[id]
end


local function findSkillByName(name)
local atk  = entry and entry["ATK-Based"]
name = trim(name)
local matk = entry and entry["MATK-Based"]
if not name then
 
return nil
if atk and matk then
return "Attack/Magic Attack"
elseif atk then
return "Attack"
elseif matk then
return "Magic Attack"
end
end


local dataset = getSkills()
return "Damage"
local byName = dataset.byName or {}
end


if byName[name] then
local function formatDamageEntry(entry, maxLevel, level)
return byName[name]
if type(entry) ~= "table" then
return nil
end
end


for _, rec in ipairs(dataset.records or {}) do
local isHealing = (entry.Type == "Healing")
if type(rec) == "table" then
local basis = isHealing and "Healing" or basisLabel(entry, false)
if rec["External Name"] == name or rec.Name == name or rec["Display Name"] == name then
return rec
end
end
end


return nil
local baseRaw = entry["Base %"]
end
local perRaw  = entry["Per Level %"]


----------------------------------------------------------------------
local baseN = toNum(baseRaw)
-- Formatting helpers (legacy + mechanics/status/etc.)
local perN  = toNum(perRaw)
----------------------------------------------------------------------


local function basisLabel(entry, isHealing)
local function baseIsPresent()
if isHealing then
if baseN ~= nil then
return "Healing"
return baseN ~= 0
end
if baseRaw ~= nil then
local s = tostring(baseRaw)
return (s ~= "" and s ~= "0" and s ~= "0.0" and s ~= "0.00")
end
return false
end
end


local atk  = entry and entry["ATK-Based"]
local baseText
local matk = entry and entry["MATK-Based"]
if baseIsPresent() then
baseText = (baseN ~= nil) and (fmtNum(baseN) .. "%") or (tostring(baseRaw) .. "%")
end


if atk and matk then
if perN == nil or perN == 0 or not maxLevel or maxLevel <= 0 then
return "Attack/Magic Attack"
return baseText and mw.text.nowiki(baseText .. " " .. basis) or nil
elseif atk then
return "Attack"
elseif matk then
return "Magic Attack"
end
end


return "Damage"
local series = {}
for lv = 1, maxLevel do
local perPart = perN * lv
 
if baseText and baseN ~= nil then
local total = baseN + perPart
table.insert(series, string.format("%s%% %s", fmtNum(total), basis))
elseif baseText then
table.insert(series, string.format("%s + %s%% %s", baseText, fmtNum(perPart), basis))
else
table.insert(series, string.format("%s%% %s", fmtNum(perPart), basis))
end
end
 
return dynSpan(series, level)
end
end


local function formatDamageEntry(entry, maxLevel, level)
local function formatDamageList(list, maxLevel, level, includeTypePrefix)
if type(entry) ~= "table" then
if type(list) ~= "table" or #list == 0 then
return nil
return nil
end
end


local isHealing = (entry.Type == "Healing")
local parts = {}
local basis = isHealing and "Healing" or basisLabel(entry, false)
for _, d in ipairs(list) do
 
if type(d) == "table" then
local baseRaw = entry["Base %"]
local txt = formatDamageEntry(d, maxLevel, level)
local perRaw  = entry["Per Level %"]
if txt then
if includeTypePrefix and d.Type and d.Type ~= "" then
table.insert(parts, mw.text.nowiki(tostring(d.Type) .. ": ") .. txt)
else
table.insert(parts, txt)
end
end
end
end
 
return (#parts > 0) and table.concat(parts, "<br />") or nil
end


local baseN = toNum(baseRaw)
----------------------------------------------------------------------
local perN  = toNum(perRaw)
-- Users matching
----------------------------------------------------------------------


local function baseIsPresent()
local function skillMatchesUser(rec, userName)
if baseN ~= nil then
if type(rec) ~= "table" or not userName or userName == "" then
return baseN ~= 0
end
if baseRaw ~= nil then
local s = tostring(baseRaw)
return (s ~= "" and s ~= "0" and s ~= "0.0" and s ~= "0.00")
end
return false
return false
end
end


local baseText
local users = rec.Users
if baseIsPresent() then
if type(users) ~= "table" then
baseText = (baseN ~= nil) and (fmtNum(baseN) .. "%") or (tostring(baseRaw) .. "%")
return false
end
end


if perN == nil or perN == 0 or not maxLevel or maxLevel <= 0 then
local userLower = mw.ustring.lower(userName)
return baseText and mw.text.nowiki(baseText .. " " .. basis) or nil
 
local function listHas(list)
if type(list) ~= "table" then
return false
end
for _, v in ipairs(list) do
if type(v) == "string" and mw.ustring.lower(v) == userLower then
return true
end
end
return false
end
end


local series = {}
return listHas(users.Classes) or listHas(users.Summons) or listHas(users.Monsters) or listHas(users.Events)
for lv = 1, maxLevel do
end
local perPart = perN * lv


if baseText and baseN ~= nil then
----------------------------------------------------------------------
local total = baseN + perPart
-- Hide Users on direct skill pages
table.insert(series, string.format("%s%% %s", fmtNum(total), basis))
----------------------------------------------------------------------
elseif baseText then
 
table.insert(series, string.format("%s + %s%% %s", baseText, fmtNum(perPart), basis))
local function isDirectSkillPage(rec)
else
if type(rec) ~= "table" then
table.insert(series, string.format("%s%% %s", fmtNum(perPart), basis))
return false
end
end
end


return dynSpan(series, level)
local pageTitle = mw.title.getCurrentTitle()
end
local pageName  = pageTitle and pageTitle.text or ""
 
pageName = trim(pageName)
local function formatDamageList(list, maxLevel, level, includeTypePrefix)
if not pageName then
if type(list) ~= "table" or #list == 0 then
return false
return nil
end
end


local parts = {}
pageName = mw.ustring.lower(pageName)
for _, d in ipairs(list) do
 
if type(d) == "table" then
local ext = trim(rec["External Name"] or rec.Name or rec["Display Name"])
local txt = formatDamageEntry(d, maxLevel, level)
local internal = trim(rec["Internal Name"] or rec.InternalName or rec.InternalID)
if txt then
if includeTypePrefix and d.Type and d.Type ~= "" then
table.insert(parts, mw.text.nowiki(tostring(d.Type) .. ": ") .. txt)
else
table.insert(parts, txt)
end
end
end
end


return (#parts > 0) and table.concat(parts, "<br />") or nil
return (ext and mw.ustring.lower(ext) == pageName) or (internal and mw.ustring.lower(internal) == pageName) or false
end
end


local function formatCombo(combo)
----------------------------------------------------------------------
if type(combo) ~= "table" then
-- Slot config (edit these tables only to rearrange layout)
return nil
----------------------------------------------------------------------
end


local parts = {}
local HERO_BAR_SLOT_ASSIGNMENT = {
[1] = "IconName",
[2] = "SkillType",
}


if combo.Type then
local HERO_MODULE_SLOT_ASSIGNMENT = {
table.insert(parts, "Type: " .. mw.text.nowiki(tostring(combo.Type)))
[1] = "SourceType",
end
[2] = "QuickStats",
[3] = "SpecialMechanics",
[4] = "LevelSelector", -- NEW
}
 
----------------------------------------------------------------------
-- Slot scaffolds
----------------------------------------------------------------------
 
local function heroBarBox(slot, extraClasses, innerHtml, isEmpty)
local box = mw.html.create("div")
box:addClass("hero-bar-module")
box:addClass("hero-bar-module-" .. tostring(slot))
box:attr("data-hero-bar-module", tostring(slot))


local durText = formatUnitValue(combo.Duration)
-- Mark herobar slot 2 as "compact-spread target" (CSS does the rest)
if durText then
if slot == 2 then
table.insert(parts, "Duration: " .. mw.text.nowiki(durText))
box:addClass("sv-herobar-compact")
end
end


if combo.Percent ~= nil then
if extraClasses then
local pctText = formatUnitValue(combo.Percent)
if type(extraClasses) == "string" then
if pctText then
box:addClass(extraClasses)
table.insert(parts, "Bonus: " .. mw.text.nowiki(pctText))
elseif type(extraClasses) == "table" then
for _, c in ipairs(extraClasses) do box:addClass(c) end
end
end
end
end


return (#parts > 0) and table.concat(parts, ", ") or nil
if isEmpty then
end
box:addClass("hero-bar-module-empty")
 
local function formatMechanicEffects(effects, maxLevel, level)
if type(effects) ~= "table" then
return nil
end
end


local keys = {}
local body = box:tag("div"):addClass("hero-bar-module-body")
for k, _ in pairs(effects) do
if innerHtml and innerHtml ~= "" then
table.insert(keys, k)
body:wikitext(innerHtml)
end
end
table.sort(keys)


local parts = {}
return tostring(box)
end


local function effectAmount(block)
local function moduleBox(slot, extraClasses, innerHtml, isEmpty)
if type(block) ~= "table" then
local box = mw.html.create("div")
return nil
box:addClass("hero-module")
end
box:addClass("hero-module-" .. tostring(slot))
box:attr("data-hero-module", tostring(slot))


local per = block["Per Level"]
if extraClasses then
if type(per) == "table" and #per > 0 then
if type(extraClasses) == "string" then
if isFlatList(per) then
box:addClass(extraClasses)
return mw.text.nowiki(formatUnitValue(per[1]) or tostring(per[1]))
elseif type(extraClasses) == "table" then
end
for _, c in ipairs(extraClasses) do box:addClass(c) end
local series = {}
for _, v in ipairs(per) do
table.insert(series, formatUnitValue(v) or tostring(v))
end
return dynSpan(series, level)
end
end
end


local txt = valuePairRawText(block)
if isEmpty then
return txt and mw.text.nowiki(txt) or nil
box:addClass("hero-module-empty")
end
end


for _, name in ipairs(keys) do
local body = box:tag("div"):addClass("hero-module-body")
local block = effects[name]
if innerHtml and innerHtml ~= "" then
if type(block) == "table" then
body:wikitext(innerHtml)
local t = block.Type
end


if t ~= nil and tostring(t) ~= "" then
return tostring(box)
local amt = effectAmount(block)
end
local seg = mw.text.nowiki(tostring(t) .. " - " .. tostring(name))
if amt then
seg = seg .. " + " .. amt
end
table.insert(parts, seg)
else
local txt = valuePairDynamicText(name, block, maxLevel, level, ", ")
if txt then
table.insert(parts, txt)
end
end
end
end


return (#parts > 0) and table.concat(parts, "<br />") or nil
----------------------------------------------------------------------
end
-- Shared helpers (Source + QuickStats + SpecialMechanics)
----------------------------------------------------------------------


local function formatModifiers(mods)
local function formatScalingCompactLines(scaling)
if type(mods) ~= "table" then
if type(scaling) ~= "table" then
return nil
return {}
end
end


local parts = {}
local list = scaling
 
if #list == 0 then
local function collect(label, sub)
if scaling.Percent ~= nil or scaling["Scaling ID"] or scaling["Scaling Name"] then
if type(sub) ~= "table" then
list = { scaling }
return
else
return {}
end
end
end


local flags = {}
local out = {}
for k, v in pairs(sub) do
for _, s in ipairs(list) do
if v then
if type(s) == "table" then
table.insert(flags, k)
local stat = s["Scaling Name"] or s["Scaling ID"] or "Unknown"
local pct  = s.Percent
local pctN = toNum(pct)
 
if pctN ~= nil and pctN ~= 0 then
table.insert(out, string.format("%s%% %s", fmtNum(pctN), stat))
elseif pct ~= nil and tostring(pct) ~= "" and tostring(pct) ~= "0" then
table.insert(out, string.format("%s%% %s", tostring(pct), stat))
end
end
end
table.sort(flags)
if #flags > 0 then
table.insert(parts, string.format("%s: %s", label, table.concat(flags, ", ")))
end
end
end
end


collect("Movement", mods["Movement Modifiers"])
return out
collect("Combat",  mods["Combat Modifiers"])
collect("Special",  mods["Special Modifiers"])
 
return (#parts > 0) and table.concat(parts, "<br />") or nil
end
end


local function formatStatusApplications(list, maxLevel, level, suppressDurationIndex)
local function basisWordFromFlags(atkFlag, matkFlag)
if type(list) ~= "table" or #list == 0 then
if atkFlag and matkFlag then
return nil
return "Hybrid"
end
elseif atkFlag then
 
return "Attack"
local parts = {}
elseif matkFlag then
for idx, s in ipairs(list) do
return "Magic Attack"
if type(s) == "table" then
local typ  = s.Type or s.Scope or "Target"
local name = s["Status External Name"] or s["Status Internal Name"] or "Unknown status"
 
local seg = tostring(typ) .. " – " .. tostring(name)
local detail = {}
 
-- Duration (optionally suppressed if QuickStats promoted it)
if idx ~= suppressDurationIndex and type(s.Duration) == "table" then
local t = valuePairDynamicText("Duration", s.Duration, maxLevel, level, "; ")
if t then table.insert(detail, t) end
end
 
if type(s.Chance) == "table" then
local t = valuePairDynamicText("Chance", s.Chance, maxLevel, level, "; ")
if t then table.insert(detail, t) end
end
 
if #detail > 0 then
seg = seg .. " (" .. table.concat(detail, ", ") .. ")"
end
 
table.insert(parts, seg)
end
end
end
 
return nil
return (#parts > 0) and table.concat(parts, "<br />") or nil
end
end


local function formatStatusRemoval(list, maxLevel, level)
local function legacyPercentAtLevel(entry, level)
if type(list) ~= "table" or #list == 0 then
if type(entry) ~= "table" then
return nil
return nil
end
end


local parts = {}
local baseRaw = entry["Base %"]
for _, r in ipairs(list) do
local perRaw  = entry["Per Level %"]
if type(r) == "table" then
local baseN  = toNum(baseRaw)
local names = r["Status External Name"]
local perN    = toNum(perRaw)
local label


if type(names) == "table" then
if perN ~= nil and perN ~= 0 then
label = table.concat(names, ", ")
local total = (baseN or 0) + (perN * level)
elseif type(names) == "string" then
return fmtNum(total) .. "%"
label = names
end
else
label = "Status"
end


local amt
if baseN ~= nil then
if type(r["Per Level"]) == "table" and #r["Per Level"] > 0 and not isFlatList(r["Per Level"]) then
return fmtNum(baseN) .. "%"
local series = {}
end
for _, v in ipairs(r["Per Level"]) do
if baseRaw ~= nil and tostring(baseRaw) ~= "" then
table.insert(series, formatUnitValue(v) or tostring(v))
return tostring(baseRaw) .. "%"
end
amt = dynSpan(series, level)
else
amt = valuePairRawText(r)
amt = amt and mw.text.nowiki(amt) or nil
end
 
local seg = mw.text.nowiki(label)
if amt then
seg = seg .. " " .. amt
end
table.insert(parts, seg)
end
end
end


return (#parts > 0) and table.concat(parts, "<br />") or nil
return nil
end
end


local function formatEvents(list)
local function seriesFromValuePair(block, maxLevel)
if type(list) ~= "table" or #list == 0 then
if type(block) ~= "table" then
return nil
return nil
end
end


local parts = {}
local base = block.Base
for _, ev in ipairs(list) do
local per  = block["Per Level"]
if type(ev) == "table" then
 
local action = ev.Action or "On event"
local function pickUnit(v)
local name  = ev["Skill Internal Name"] or ev["Skill External Name"] or "Unknown skill"
if type(v) == "table" and v.Unit and v.Unit ~= "" then
table.insert(parts, string.format("%s → %s", action, name))
return v.Unit
end
end
return nil
end
end
local unit = pickUnit(base) or pickUnit(per)


return (#parts > 0) and table.concat(parts, "<br />") or nil
local function fmtAny(v)
end
local t = formatUnitValue(v)
 
return t and tostring(t) or (v ~= nil and tostring(v) or nil)
----------------------------------------------------------------------
-- User matching (for auto lists on class pages)
----------------------------------------------------------------------
 
local function skillMatchesUser(rec, userName)
if type(rec) ~= "table" or not userName or userName == "" then
return false
end
end


local users = rec.Users
local series = {}
if type(users) ~= "table" then
return false
end


local userLower = mw.ustring.lower(userName)
-- Expanded per-level series (wikiprep)
if type(per) == "table" and #per > 0 then
for lv = 1, maxLevel do
local raw = per[lv] or per[#per]
local one = fmtAny(raw)
if one == nil or isZeroish(raw) or isZeroish(one) then
one = "—"
end
series[lv] = one
end
return series
end


local function listHas(list)
-- Empty per-list -> base only
if type(list) ~= "table" then
if type(per) == "table" and #per == 0 then
return false
local one = fmtAny(base)
if one == nil or isZeroish(base) or isZeroish(one) then
one = "—"
end
end
for _, v in ipairs(list) do
for lv = 1, maxLevel do
if type(v) == "string" and mw.ustring.lower(v) == userLower then
series[lv] = one
return true
end
end
end
return false
return series
end
end


return listHas(users.Classes) or listHas(users.Summons) or listHas(users.Monsters) or listHas(users.Events)
-- Scalar per -> compute base + per*level (fallback)
end
local baseN = toNum(base) or 0
local perN  = toNum(per)


----------------------------------------------------------------------
if perN ~= nil then
-- Direct page detection (hide Users on the skill's own page)
for lv = 1, maxLevel do
----------------------------------------------------------------------
local total = baseN + (perN * lv)
 
local v = unit and { Value = total, Unit = unit } or total
local function isDirectSkillPage(rec)
local one = fmtAny(v)
if type(rec) ~= "table" then
if one == nil or total == 0 or isZeroish(one) then
return false
one = ""
end
series[lv] = one
end
return series
end
end


local pageTitle = mw.title.getCurrentTitle()
-- Base-only scalar
local pageName  = pageTitle and pageTitle.text or ""
local raw = (base ~= nil) and base or per
pageName = trim(pageName)
local one = fmtAny(raw)
if not pageName then
if one == nil then
return false
return nil
end
if isZeroish(raw) or isZeroish(one) then
one = "—"
end
for lv = 1, maxLevel do
series[lv] = one
end
end
 
return series
pageName = mw.ustring.lower(pageName)
 
local ext = trim(rec["External Name"] or rec.Name or rec["Display Name"])
local internal = trim(rec["Internal Name"] or rec.InternalName or rec.InternalID)
 
return (ext and mw.ustring.lower(ext) == pageName) or (internal and mw.ustring.lower(internal) == pageName) or false
end
end


----------------------------------------------------------------------
local function displayFromSeries(series, level)
-- Plug-in slot config (EDIT THESE TABLES ONLY to rearrange layout)
if type(series) ~= "table" or #series == 0 then
----------------------------------------------------------------------
return nil
end


-- Hero bar: 2 slots
local any = false
local HERO_BAR_SLOT_ASSIGNMENT = {
for _, v in ipairs(series) do
[1] = "IconName",
if v ~= "" then
[2] = "SkillType",
any = true
}
break
 
-- Modules row: 4 slots
local HERO_MODULE_SLOT_ASSIGNMENT = {
[1] = "SourceType",
[2] = "QuickStats",
[3] = "ReservedInfo",
[4] = "LevelSelector",
}
 
----------------------------------------------------------------------
-- Slot scaffolds (stable containers; plug-ins provide inner content)
----------------------------------------------------------------------
 
local function heroBarBox(slot, pluginName, extraClasses, innerHtml, isEmpty)
local box = mw.html.create("div")
box:addClass("hero-bar-module")
box:addClass("hero-bar-module-" .. tostring(slot))
box:attr("data-hero-bar-module", tostring(slot))
 
-- Shared cross-slot hooks
box:addClass("sv-hero-slot")
box:addClass("sv-hero-slot-bar")
 
if pluginName then
local k = kebabCase(pluginName)
if k then
box:attr("data-plugin", k)
box:addClass("sv-plugin-" .. k)
end
end
end
if not any then
return nil
end
end


if extraClasses then
if isFlatList(series) then
if type(extraClasses) == "string" then
return mw.text.nowiki(series[1])
box:addClass(extraClasses)
elseif type(extraClasses) == "table" then
for _, c in ipairs(extraClasses) do
box:addClass(c)
end
end
end
end
return dynSpan(series, level)
end


if isEmpty then
local function formatAreaSize(area)
box:addClass("hero-bar-module-empty")
if type(area) ~= "table" then
return nil
end
end


local body = box:tag("div"):addClass("hero-bar-module-body"):addClass("sv-hero-slot-body")
local raw = area["Area Size"]
if innerHtml and innerHtml ~= "" then
if raw == nil then
body:wikitext(innerHtml)
return nil
end
end


return tostring(box)
local name, num
end


local function moduleBox(slot, pluginName, extraClasses, innerHtml, isEmpty)
if type(raw) == "table" then
local box = mw.html.create("div")
name = raw.Name or raw.ID or raw.Value
box:addClass("hero-module")
num  = raw.Value
box:addClass("hero-module-" .. tostring(slot))
if raw.Name or raw.ID then
box:attr("data-hero-module", tostring(slot))
name = raw.Name or raw.ID
 
-- Shared cross-slot hooks
box:addClass("sv-hero-slot")
box:addClass("sv-hero-slot-tile")
 
if pluginName then
local k = kebabCase(pluginName)
if k then
box:attr("data-plugin", k)
box:addClass("sv-plugin-" .. k)
end
end
elseif type(raw) == "string" then
name = raw
elseif type(raw) == "number" then
num = raw
end
end


if extraClasses then
if num == nil then
if type(extraClasses) == "string" then
num = toNum(area["Area Value"]) or toNum(area["Area Size Value"]) or toNum(area["Area Number"]) or toNum(area["Area Radius"])
box:addClass(extraClasses)
elseif type(extraClasses) == "table" then
for _, c in ipairs(extraClasses) do
box:addClass(c)
end
end
end
end


if isEmpty then
if name ~= nil then
box:addClass("hero-module-empty")
local s = mw.text.trim(tostring(name))
if s == "" or isNoneLike(s) then
return nil
end
if mw.ustring.find(s, "%(") then
return mw.text.nowiki(s)
end
if num ~= nil and num ~= 0 then
return mw.text.nowiki(string.format("%s (%s)", s, fmtNum(num)))
end
return mw.text.nowiki(s)
end
end


local body = box:tag("div"):addClass("hero-module-body"):addClass("sv-hero-slot-body")
if num ~= nil and num ~= 0 then
if innerHtml and innerHtml ~= "" then
return mw.text.nowiki(string.format("(%s)", fmtNum(num)))
body:wikitext(innerHtml)
end
end


return tostring(box)
return nil
end
end


----------------------------------------------------------------------
local function skillHasAnyDamage(rec, maxLevel)
-- Shared helpers used by plug-ins (Source + QuickStats)
if type(rec.Source) == "table" then
----------------------------------------------------------------------
local s = seriesFromValuePair(rec.Source, maxLevel)
if s then
for _, v in ipairs(s) do
if v ~= "—" then return true end
end
end
end


local function formatScalingCompactLines(scaling)
if type(rec.Damage) == "table" then
if type(scaling) ~= "table" then
local dmg = rec.Damage
return {}
for _, key in ipairs({ "Main Damage", "Flat Damage", "Reflect Damage" }) do
end
local lst = dmg[key]
 
if type(lst) == "table" and #lst > 0 then
local list = scaling
return true
if #list == 0 then
end
if scaling.Percent ~= nil or scaling["Scaling ID"] or scaling["Scaling Name"] then
list = { scaling }
else
return {}
end
end
end
end


local out = {}
return false
for _, s in ipairs(list) do
end
if type(s) == "table" then
local stat = s["Scaling Name"] or s["Scaling ID"] or "Unknown"
local pct  = s.Percent
local pctN = toNum(pct)


if pctN ~= nil and pctN ~= 0 then
local function computeDurationPromotion(rec, maxLevel)
table.insert(out, string.format("%s%% %s", fmtNum(pctN), stat))
if type(rec) ~= "table" then return nil end
elseif pct ~= nil and tostring(pct) ~= "" and tostring(pct) ~= "0" then
if skillHasAnyDamage(rec, maxLevel) then return nil end
table.insert(out, string.format("%s%% %s", tostring(pct), stat))
 
end
local mech = (type(rec.Mechanics) == "table") and rec.Mechanics or {}
local bt  = (type(mech["Basic Timings"]) == "table") and mech["Basic Timings"] or {}
local durS = seriesFromValuePair(bt["Duration"], maxLevel)
 
if durS ~= nil then
local any = false
for _, v in ipairs(durS) do
if v ~= "—" then any = true break end
end
if any then
return nil
end
end
end
end


return out
local apps = rec["Status Applications"]
end
if type(apps) ~= "table" then return nil end


local function basisWordFromFlags(atkFlag, matkFlag)
for idx, app in ipairs(apps) do
if atkFlag and matkFlag then
if type(app) == "table" and type(app.Duration) == "table" then
return "Hybrid"
local s = seriesFromValuePair(app.Duration, maxLevel)
elseif atkFlag then
if s then
return "Attack"
for _, v in ipairs(s) do
elseif matkFlag then
if v ~= "" then
return "Magic Attack"
return {
durationBlock = app.Duration,
suppressDurationIndex = idx,
}
end
end
end
end
end
end
return nil
return nil
end
end


local function sourceValueForLevel(src, maxLevel, level)
----------------------------------------------------------------------
if type(src) ~= "table" then
-- Plug-ins
return nil
----------------------------------------------------------------------
end
 
local PLUGINS = {}


local per = src["Per Level"]
-- Hero Bar Slot 1: Icon + Name
if type(per) == "table" and #per > 0 then
function PLUGINS.IconName(rec, ctx)
if isFlatList(per) then
local icon  = rec.Icon
local one  = formatUnitValue(per[1]) or tostring(per[1])
local title = rec["External Name"] or rec.Name or rec["Internal Name"] or "Unknown Skill"
local show = formatUnitValue(src.Base) or one
 
return show and mw.text.nowiki(show) or nil
local wrap = mw.html.create("div")
end
wrap:addClass("sv-herobar-1-wrap")


local series = {}
if icon and icon ~= "" then
for _, v in ipairs(per) do
wrap:tag("div")
table.insert(series, formatUnitValue(v) or tostring(v))
:addClass("sv-herobar-icon")
end
:wikitext(string.format("[[File:%s|80px|link=]]", icon))
return dynSpan(series, level)
end
end


return valuePairDynamicValueOnly(src, maxLevel, level)
wrap:tag("div")
end
:addClass("spiritvale-infobox-title")
:wikitext(title)


local function legacyPercentAtLevel(entry, level)
return {
if type(entry) ~= "table" then
inner = tostring(wrap),
return nil
classes = "module-herobar-1",
end
}
end


local baseRaw = entry["Base %"]
-- Reserved placeholder (kept for future)
local perRaw  = entry["Per Level %"]
function PLUGINS.ReservedInfo(rec, ctx)
local baseN  = toNum(baseRaw)
local wrap = mw.html.create("div")
local perN    = toNum(perRaw)
wrap:addClass("sv-herobar-2-wrap")
return {
inner = tostring(wrap),
classes = "module-herobar-2",
}
end


if perN ~= nil and perN ~= 0 then
-- Module: Level Selector
local total = (baseN or 0) + (perN * level)
function PLUGINS.LevelSelector(rec, ctx)
return fmtNum(total) .. "%"
local level = ctx.level or 1
end
local maxLevel = ctx.maxLevel or 1


if baseN ~= nil then
local inner = mw.html.create("div")
return fmtNum(baseN) .. "%"
inner:addClass("sv-level-ui")
end
if baseRaw ~= nil and tostring(baseRaw) ~= "" then
return tostring(baseRaw) .. "%"
end


return nil
inner:tag("div")
end
:addClass("sv-level-label")
:wikitext("Level <span class=\"sv-level-num\">" .. tostring(level) .. "</span> / " .. tostring(maxLevel))


local function seriesFromValuePair(block, maxLevel)
local slider = inner:tag("div"):addClass("sv-level-slider")
if type(block) ~= "table" then
return nil
end


local base = block.Base
if tonumber(maxLevel) and tonumber(maxLevel) > 1 then
local per  = block["Per Level"]
slider:tag("input")
 
:attr("type", "range")
local function pickUnit(v)
:attr("min", "1")
if type(v) == "table" and v.Unit and v.Unit ~= "" then
:attr("max", tostring(maxLevel))
return v.Unit
:attr("value", tostring(level))
end
:addClass("sv-level-range")
return nil
:attr("aria-label", "Skill level select")
else
inner:addClass("sv-level-ui-single")
slider:addClass("sv-level-slider-single")
end
end
local unit = pickUnit(base) or pickUnit(per)


local function fmtAny(v)
return {
local t = formatUnitValue(v)
inner = tostring(inner),
return t and tostring(t) or (v ~= nil and tostring(v) or nil)
classes = "module-level-selector",
end
}
end


local series = {}
-- Module: Skill Type
function PLUGINS.SkillType(rec, ctx)
local typeBlock = (type(rec.Type) == "table") and rec.Type or {}
local hideDamageAndElement = (ctx.nonDamaging == true)


-- Preferred: expanded series (wikiprep)
local function valName(x)
if type(per) == "table" and #per > 0 then
if x == nil then return nil end
for lv = 1, maxLevel do
if type(x) == "table" then
local raw = per[lv] or per[#per]
if x.Name and x.Name ~= "" then return tostring(x.Name) end
local one = fmtAny(raw)
if x.ID and x.ID ~= "" then return tostring(x.ID) end
if one == nil or isZeroish(raw) or isZeroish(one) then
if x.Value ~= nil then return tostring(x.Value) end
one = ""
end
end
if type(x) == "string" and x ~= "" then
series[lv] = one
return x
end
end
return series
return nil
end
end


-- Empty per-list -> base only
local grid = mw.html.create("div")
if type(per) == "table" and #per == 0 then
grid:addClass("sv-type-grid")
local one = fmtAny(base)
grid:addClass("sv-compact-root")
if one == nil or isZeroish(base) or isZeroish(one) then
 
one = ""
local added = false
end
local function addChunk(label, rawVal)
for lv = 1, maxLevel do
local v = valName(rawVal)
series[lv] = one
if not v or v == "" then return end
end
added = true
return series
 
local chunk = grid:tag("div"):addClass("sv-type-chunk")
chunk:tag("div"):addClass("sv-type-label"):wikitext(mw.text.nowiki(label))
chunk:tag("div"):addClass("sv-type-value"):wikitext(mw.text.nowiki(v))
end
 
if not hideDamageAndElement then
addChunk("Damage", typeBlock.Damage  or typeBlock["Damage Type"])
addChunk("Element", typeBlock.Element or typeBlock["Element Type"])
end
end


-- Scalar per -> compute base + per*level (fallback)
addChunk("Target", typeBlock.Target or typeBlock["Target Type"])
local baseN = toNum(base) or 0
addChunk("Cast",  typeBlock.Cast  or typeBlock["Cast Type"])
local perN  = toNum(per)


if perN ~= nil then
return {
for lv = 1, maxLevel do
inner = added and tostring(grid) or "",
local total = baseN + (perN * lv)
classes = "module-skill-type",
local v = unit and { Value = total, Unit = unit } or total
}
local one = fmtAny(v)
end
if one == nil or total == 0 or isZeroish(one) then
 
one = ""
-- Module: SourceType (Modifier + Source + Scaling)
end
function PLUGINS.SourceType(rec, ctx)
series[lv] = one
local level = ctx.level or 1
local maxLevel = ctx.maxLevel or 1
 
local basisWord = nil
local sourceKind = nil
local sourceVal  = nil
local scaling    = nil
 
local function sourceValueForLevel(src)
if type(src) ~= "table" then
return nil
end
end
return series
end


-- Base-only scalar
local per = src["Per Level"]
local raw = (base ~= nil) and base or per
if type(per) == "table" and #per > 0 then
local one = fmtAny(raw)
if isFlatList(per) then
if one == nil then
local one = formatUnitValue(per[1]) or tostring(per[1])
return nil
local show = formatUnitValue(src.Base) or one
end
return show and mw.text.nowiki(show) or nil
if isZeroish(raw) or isZeroish(one) then
end
one = "—"
 
end
local series = {}
for lv = 1, maxLevel do
for _, v in ipairs(per) do
series[lv] = one
table.insert(series, formatUnitValue(v) or tostring(v))
end
end
return series
return dynSpan(series, level)
end
end


local function displayFromSeries(series, level)
return valuePairDynamicValueOnly(src, maxLevel, level)
if type(series) ~= "table" or #series == 0 then
return nil
end
end


local any = false
if type(rec.Source) == "table" then
for _, v in ipairs(series) do
local src = rec.Source
if v ~= "" then
local atkFlag  = (src["ATK-Based"] == true)
any = true
local matkFlag = (src["MATK-Based"] == true)
break
basisWord = basisWordFromFlags(atkFlag, matkFlag)
end
end
if not any then
return nil
end


if isFlatList(series) then
sourceKind = src.Type or ((src.Healing == true) and "Healing") or "Damage"
return mw.text.nowiki(series[1])
sourceVal  = sourceValueForLevel(src)
scaling    = src.Scaling
end
end
return dynSpan(series, level)
end


local function formatAreaSize(area)
-- Fallback to legacy Damage lists if Source absent
if type(area) ~= "table" then
if (sourceVal == nil or sourceVal == "") and type(rec.Damage) == "table" then
return nil
local dmg = rec.Damage
end
scaling = scaling or dmg.Scaling


local raw = area["Area Size"]
local main = dmg["Main Damage"]
if raw == nil then
local refl = dmg["Reflect Damage"]
return nil
local flat = dmg["Flat Damage"]
end


local name, num
if type(main) == "table" and #main > 0 then
local pick = nil
for _, d in ipairs(main) do
if type(d) == "table" and d.Type ~= "Healing" then
pick = d
break
end
end
pick = pick or main[1]


if type(raw) == "table" then
if type(pick) == "table" then
name = raw.Name or raw.ID or raw.Value
local atkFlag  = (pick["ATK-Based"] == true)
num = raw.Value
local matkFlag = (pick["MATK-Based"] == true)
if raw.Name or raw.ID then
basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)
name = raw.Name or raw.ID
 
sourceKind = (pick.Type == "Healing") and "Healing" or "Damage"
sourceVal  = legacyPercentAtLevel(pick, level)
end
elseif type(refl) == "table" and #refl > 0 and type(refl[1]) == "table" then
local pick = refl[1]
local atkFlag = (pick["ATK-Based"] == true)
local matkFlag = (pick["MATK-Based"] == true)
basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)
 
sourceKind = "Reflect"
sourceVal  = legacyPercentAtLevel(pick, level)
elseif type(flat) == "table" and #flat > 0 and type(flat[1]) == "table" then
local pick = flat[1]
local atkFlag  = (pick["ATK-Based"] == true)
local matkFlag = (pick["MATK-Based"] == true)
basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)
 
sourceKind = "Flat"
sourceVal  = legacyPercentAtLevel(pick, level)
end
end
elseif type(raw) == "string" then
name = raw
elseif type(raw) == "number" then
num = raw
end
end


if num == nil then
local scalingLines = formatScalingCompactLines(scaling)
num = toNum(area["Area Value"]) or toNum(area["Area Size Value"]) or toNum(area["Area Number"]) or toNum(area["Area Radius"])
local hasSource    = (sourceVal ~= nil and tostring(sourceVal) ~= "")
end
local hasScaling  = (type(scalingLines) == "table" and #scalingLines > 0)


if name ~= nil then
if (not hasSource) and (not hasScaling) then
local s = mw.text.trim(tostring(name))
return nil
if s == "" or isNoneLike(s) then
return nil
end
if mw.ustring.find(s, "%(") then
return mw.text.nowiki(s)
end
if num ~= nil and num ~= 0 then
return mw.text.nowiki(string.format("%s (%s)", s, fmtNum(num)))
end
return mw.text.nowiki(s)
end
end


if num ~= nil and num ~= 0 then
local hasMod = (basisWord ~= nil and tostring(basisWord) ~= "")
return mw.text.nowiki(string.format("(%s)", fmtNum(num)))
end


return nil
local extra = { "skill-source-module" }
end
table.insert(extra, hasMod and "sv-has-mod" or "sv-no-mod")


local function skillHasAnyDamage(rec, maxLevel)
if hasSource and (not hasScaling) then
if type(rec.Source) == "table" then
table.insert(extra, "sv-only-source")
local s = seriesFromValuePair(rec.Source, maxLevel)
elseif hasScaling and (not hasSource) then
if s then
table.insert(extra, "sv-only-scaling")
for _, v in ipairs(s) do
if v ~= "" then return true end
end
end
end
end


if type(rec.Damage) == "table" then
local wrap = mw.html.create("div")
local dmg = rec.Damage
wrap:addClass("sv-source-grid")
for _, key in ipairs({ "Main Damage", "Flat Damage", "Reflect Damage" }) do
wrap:addClass("sv-compact-root")
local lst = dmg[key]
if type(lst) == "table" and #lst > 0 then
return true
end
end
end


return false
if hasMod then
end
local modCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-modifier")
modCol:tag("div"):addClass("sv-source-pill"):wikitext("Modifier")
modCol:tag("div"):addClass("sv-modifier-value"):wikitext(mw.text.nowiki(basisWord))
end


local function computeDurationPromotion(rec, maxLevel)
if hasSource then
-- Only:
local sourceCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-main")
-- - non-damaging skills
sourceCol:tag("div"):addClass("sv-source-pill"):wikitext(mw.text.nowiki(sourceKind or "Source"))
-- - AND missing/blank Duration in Basic Timings
sourceCol:tag("div"):addClass("sv-source-value"):wikitext(sourceVal)
-- - AND a Status Application has a Duration block
end
-- Then: promote that status duration into QuickStats and suppress it in Applies row.
if type(rec) ~= "table" then return nil end
if skillHasAnyDamage(rec, maxLevel) then return nil end


local mech = (type(rec.Mechanics) == "table") and rec.Mechanics or {}
if hasScaling then
local bt  = (type(mech["Basic Timings"]) == "table") and mech["Basic Timings"] or {}
local scalingCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-scaling")
local durS = seriesFromValuePair(bt["Duration"], maxLevel)
scalingCol:tag("div"):addClass("sv-source-pill"):wikitext("Scaling")


if durS ~= nil then
local list = scalingCol:tag("div"):addClass("sv-scaling-list")
local any = false
for _, line in ipairs(scalingLines) do
for _, v in ipairs(durS) do
list:tag("div"):addClass("sv-scaling-item"):wikitext(mw.text.nowiki(line))
if v ~= "" then any = true break end
end
if any then
return nil
end
end
end
end
-- if durS is nil OR all "—", allow promotion


local apps = rec["Status Applications"]
return {
if type(apps) ~= "table" then return nil end
inner = tostring(wrap),
classes = extra,
}
end
 
-- Module: Quick Stats (3x2)
function PLUGINS.QuickStats(rec, ctx)
local level = ctx.level or 1
local maxLevel = ctx.maxLevel or 1
local promo = ctx.promo


for idx, app in ipairs(apps) do
local mech = (type(rec) == "table" and type(rec.Mechanics) == "table") and rec.Mechanics or {}
if type(app) == "table" and type(app.Duration) == "table" then
local bt  = (type(mech["Basic Timings"]) == "table") and mech["Basic Timings"] or {}
local s = seriesFromValuePair(app.Duration, maxLevel)
local rc  = (type(mech["Resource Cost"]) == "table") and mech["Resource Cost"] or {}
if s then
 
for _, v in ipairs(s) do
local function dash() return "—" end
if v ~= "" then
 
return {
-- Range (0 => —)
durationBlock = app.Duration,
local rangeVal = nil
suppressDurationIndex = idx,
if mech.Range ~= nil and not isNoneLike(mech.Range) then
}
local n = toNum(mech.Range)
end
if n ~= nil then
end
if n ~= 0 then
rangeVal = mw.text.nowiki(formatUnitValue(mech.Range) or tostring(mech.Range))
end
else
local t = mw.text.trim(tostring(mech.Range))
if t ~= "" and not isNoneLike(t) then
rangeVal = mw.text.nowiki(t)
end
end
end
end
end
end


return nil
-- Area
end
local areaVal = formatAreaSize(mech.Area)


----------------------------------------------------------------------
-- Timings
-- Plug-ins (name -> { inner = "...", classes = "..."/{...} } OR nil/"")
local castVal = displayFromSeries(seriesFromValuePair(bt["Cast Time"], maxLevel), level)
----------------------------------------------------------------------
local cdVal  = displayFromSeries(seriesFromValuePair(bt["Cooldown"],  maxLevel), level)
local durVal  = displayFromSeries(seriesFromValuePair(bt["Duration"],  maxLevel), level)


local PLUGINS = {}
-- Promote status duration if needed
if (durVal == nil) and type(promo) == "table" and type(promo.durationBlock) == "table" then
durVal = displayFromSeries(seriesFromValuePair(promo.durationBlock, maxLevel), level)
end


-- Hero Bar Slot 1: Icon + Name  (EXCEPTION: not required to be "portable")
-- Cost: MP + HP
function PLUGINS.IconName(rec, ctx)
local function labeledSeries(block, label)
local icon  = rec.Icon
local s = seriesFromValuePair(block, maxLevel)
local title = rec["External Name"] or rec.Name or rec["Internal Name"] or "Unknown Skill"
if not s then return nil end
local any = false
for i, v in ipairs(s) do
if v ~= "" then
s[i] = tostring(v) .. " " .. label
any = true
else
s[i] = ""
end
end
return any and s or nil
end


local wrap = mw.html.create("div")
local mpS = labeledSeries(rc["Mana Cost"], "MP")
wrap:addClass("sv-herobar-1-wrap")
local hpS = labeledSeries(rc["Health Cost"], "HP")


if icon and icon ~= "" then
local costSeries = {}
wrap:tag("div")
for lv = 1, maxLevel do
:addClass("sv-herobar-icon")
local mp = mpS and mpS[lv] or "—"
:wikitext(string.format("[[File:%s|80px|link=]]", icon))
local hp = hpS and hpS[lv] or "—"
 
if mp ~= "—" and hp ~= "" then
costSeries[lv] = mp .. " + " .. hp
elseif mp ~= "" then
costSeries[lv] = mp
elseif hp ~= "" then
costSeries[lv] = hp
else
costSeries[lv] = "—"
end
end
end


wrap:tag("div")
local costVal = displayFromSeries(costSeries, level)
:addClass("spiritvale-infobox-title")
 
:wikitext(title)
local grid = mw.html.create("div")
grid:addClass("sv-m4-grid")
grid:addClass("sv-compact-root")


return {
local function addCell(label, val)
inner = tostring(wrap),
local cell = grid:tag("div"):addClass("sv-m4-cell")
classes = "module-herobar-1",
cell:tag("div"):addClass("sv-m4-label"):wikitext(mw.text.nowiki(label))
}
cell:tag("div"):addClass("sv-m4-value"):wikitext(val or dash())
end
end
 
addCell("Range",     rangeVal)
addCell("Area",      areaVal)
addCell("Cost",      costVal)
addCell("Cast Time", castVal)
addCell("Cooldown",  cdVal)
addCell("Duration",  durVal)


-- Hero Bar Slot 2: Reserved container (EXCEPTION)
function PLUGINS.ReservedInfo(rec, ctx)
local wrap = mw.html.create("div")
wrap:addClass("sv-herobar-2-wrap")
return {
return {
inner = tostring(wrap),
inner = tostring(grid),
classes = "module-herobar-2",
classes = "module-quick-stats",
}
}
end
end


-- Module Slot 1: Level Selector (EXCEPTION)
-- Module: Special Mechanics (Special Mechanics + Flags + Combo)
function PLUGINS.LevelSelector(rec, ctx)
function PLUGINS.SpecialMechanics(rec, ctx)
local level = ctx.level or 1
local level = ctx.level or 1
local maxLevel = ctx.maxLevel or 1
local maxLevel = ctx.maxLevel or 1


local inner = mw.html.create("div")
local mech = (type(rec) == "table" and type(rec.Mechanics) == "table") and rec.Mechanics or {}
inner:addClass("sv-level-ui")
local effects = (type(mech.Effects) == "table") and mech.Effects or nil
local combo  = (type(mech.Combo) == "table") and mech.Combo or nil
local mods    = (type(rec.Modifiers) == "table") and rec.Modifiers or nil


inner:tag("div")
-- Collect flags as a flat, de-duped set
:addClass("sv-level-label")
local flagSet = {}
:wikitext("Level <span class=\"sv-level-num\">" .. tostring(level) .. "</span> / " .. tostring(maxLevel))


local slider = inner:tag("div"):addClass("sv-level-slider")
local function addFlags(sub)
if type(sub) ~= "table" then return end
for k, v in pairs(sub) do
if v then
flagSet[tostring(k)] = true
end
end
end


if tonumber(maxLevel) and tonumber(maxLevel) > 1 then
if mods then
slider:tag("input")
addFlags(mods["Movement Modifiers"])
:attr("type", "range")
addFlags(mods["Combat Modifiers"])
:attr("min", "1")
addFlags(mods["Special Modifiers"])
:attr("max", tostring(maxLevel))
for k, v in pairs(mods) do
:attr("value", tostring(level))
if type(v) == "boolean" and v then
:addClass("sv-level-range")
flagSet[tostring(k)] = true
:attr("aria-label", "Skill level select")
end
else
end
inner:addClass("sv-level-ui-single")
slider:addClass("sv-level-slider-single")
end
end


return {
local flags = {}
inner = tostring(inner),
for k, _ in pairs(flagSet) do table.insert(flags, k) end
classes = "module-level-selector",
table.sort(flags)
}
 
end
-- Collect special mechanics into (label,value) items
local items = {}
 
if effects then
local keys = {}
for k, _ in pairs(effects) do table.insert(keys, k) end
table.sort(keys)
 
for _, name in ipairs(keys) do
local block = effects[name]
if type(block) == "table" then
local disp = displayFromSeries(seriesFromValuePair(block, maxLevel), level)
local t = trim(block.Type)
 
local parts = {}
if t and not isNoneLike(t) and mw.ustring.lower(t) ~= mw.ustring.lower(tostring(name)) then
table.insert(parts, mw.text.nowiki(t))
end
if disp then
table.insert(parts, disp)
end


-- Module: Skill Type  (PORTABLE)
local value = nil
function PLUGINS.SkillType(rec, ctx)
if #parts == 1 then
local typeBlock = (type(rec.Type) == "table") and rec.Type or {}
value = parts[1]
local hideDamageAndElement = (ctx.nonDamaging == true)
elseif #parts >= 2 then
value = parts[1] .. ": " .. parts[2]
end


local function valName(x)
if value then
if x == nil then return nil end
table.insert(items, { label = tostring(name), value = value })
if type(x) == "table" then
end
if x.Name and x.Name ~= "" then return tostring(x.Name) end
end
if x.ID and x.ID ~= "" then return tostring(x.ID) end
if x.Value ~= nil then return tostring(x.Value) end
end
end
if type(x) == "string" and x ~= "" then
return x
end
return nil
end
end


local grid = mw.html.create("div")
-- Combo (append last)
grid:addClass("sv-type-grid")
if combo then
local typ = trim(combo.Type)
if typ and not isNoneLike(typ) then
local details = {}


local added = false
local pct = formatUnitValue(combo.Percent)
local function addChunk(label, rawVal)
if pct and not isZeroish(pct) then
local v = valName(rawVal)
table.insert(details, mw.text.nowiki(pct))
if not v or v == "" then return end
end
added = true
 
local dur = formatUnitValue(combo.Duration)
if dur and not isZeroish(dur) then
table.insert(details, mw.text.nowiki(dur))
end
 
local comboText
if #details > 0 then
comboText = mw.text.nowiki(typ) .. " (" .. table.concat(details, ", ") .. ")"
else
comboText = mw.text.nowiki(typ)
end
 
table.insert(items, { label = "Combo", value = comboText })
end
end
 
local hasAny = (#flags > 0) or (#items > 0)
 
local root = mw.html.create("div")
root:addClass("sv-sm-root")
root:addClass("sv-compact-root")


local chunk = grid:tag("div"):addClass("sv-type-chunk")
if not hasAny then
chunk:tag("div"):addClass("sv-type-label"):wikitext(mw.text.nowiki(label))
root:tag("div")
chunk:tag("div"):addClass("sv-type-value"):wikitext(mw.text.nowiki(v))
:addClass("sv-sm-empty")
:wikitext("No Special Mechanics")
return {
inner = tostring(root),
classes = "module-special-mechanics",
}
end
end


if not hideDamageAndElement then
local layout = root:tag("div"):addClass("sv-sm-layout")
addChunk("Damage",  typeBlock.Damage  or typeBlock["Damage Type"])
if #flags > 0 then
addChunk("Element", typeBlock.Element or typeBlock["Element Type"])
layout:addClass("sv-sm-has-flags")
local fcol = layout:tag("div"):addClass("sv-sm-flags")
for _, f in ipairs(flags) do
fcol:tag("div"):addClass("sv-sm-flag"):wikitext(mw.text.nowiki(f))
end
end
end


addChunk("Target", typeBlock.Target or typeBlock["Target Type"])
local wrap = layout:tag("div"):addClass("sv-sm-items")
addChunk("Cast",  typeBlock.Cast  or typeBlock["Cast Type"])
for _, it in ipairs(items) do
local one = wrap:tag("div"):addClass("sv-sm-item")
one:tag("div"):addClass("sv-sm-label"):wikitext(mw.text.nowiki(it.label))
one:tag("div"):addClass("sv-sm-value"):wikitext(it.value or "")
end


return {
return {
inner = added and tostring(grid) or "",
inner = tostring(root),
classes = "module-skill-type",
classes = "module-special-mechanics",
}
}
end
end


-- Module: SourceType (Modifier + Source + Scaling)  (PORTABLE)
----------------------------------------------------------------------
function PLUGINS.SourceType(rec, ctx)
-- Generic slot renderers
local level = ctx.level or 1
----------------------------------------------------------------------
local maxLevel = ctx.maxLevel or 1


local basisWord = nil
local function normalizeResult(res)
local sourceKind = nil
if res == nil then return nil end
local sourceVal  = nil
if type(res) == "string" then
local scaling    = nil
return { inner = res, classes = nil }
 
if type(rec.Source) == "table" then
local src = rec.Source
local atkFlag  = (src["ATK-Based"] == true)
local matkFlag = (src["MATK-Based"] == true)
basisWord = basisWordFromFlags(atkFlag, matkFlag)
 
sourceKind = src.Type or ((src.Healing == true) and "Healing") or "Damage"
sourceVal  = sourceValueForLevel(src, maxLevel, level)
scaling    = src.Scaling
end
end
if type(res) == "table" then
local inner = res.inner
if type(inner) ~= "string" then
inner = (inner ~= nil) and tostring(inner) or ""
end
return { inner = inner, classes = res.classes }
end
return { inner = tostring(res), classes = nil }
end


-- Fallback to legacy Damage lists if Source absent
local function safeCallPlugin(name, rec, ctx)
if (sourceVal == nil or sourceVal == "") and type(rec.Damage) == "table" then
local fn = PLUGINS[name]
local dmg = rec.Damage
if type(fn) ~= "function" then
scaling = scaling or dmg.Scaling
return nil
end
local ok, out = pcall(fn, rec, ctx)
if not ok then
return nil
end
return normalizeResult(out)
end


local main = dmg["Main Damage"]
local function renderHeroBarSlot(slotIndex, rec, ctx)
local refl = dmg["Reflect Damage"]
local pluginName = HERO_BAR_SLOT_ASSIGNMENT[slotIndex]
local flat = dmg["Flat Damage"]
if not pluginName then
return heroBarBox(slotIndex, nil, "", true)
end


if type(main) == "table" and #main > 0 then
local res = safeCallPlugin(pluginName, rec, ctx)
local pick = nil
if not res or not res.inner or res.inner == "" then
for _, d in ipairs(main) do
return heroBarBox(slotIndex, nil, "", true)
if type(d) == "table" and d.Type ~= "Healing" then
end
pick = d
break
end
end
pick = pick or main[1]


if type(pick) == "table" then
return heroBarBox(slotIndex, res.classes, res.inner, false)
local atkFlag  = (pick["ATK-Based"] == true)
end
local matkFlag = (pick["MATK-Based"] == true)
basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)


sourceKind = (pick.Type == "Healing") and "Healing" or "Damage"
local function renderModuleSlot(slotIndex, rec, ctx)
sourceVal  = legacyPercentAtLevel(pick, level)
local pluginName = HERO_MODULE_SLOT_ASSIGNMENT[slotIndex]
end
if not pluginName then
elseif type(refl) == "table" and #refl > 0 and type(refl[1]) == "table" then
return moduleBox(slotIndex, nil, "", true)
local pick = refl[1]
end
local atkFlag  = (pick["ATK-Based"] == true)
local matkFlag = (pick["MATK-Based"] == true)
basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)


sourceKind = "Reflect"
local res = safeCallPlugin(pluginName, rec, ctx)
sourceVal  = legacyPercentAtLevel(pick, level)
if not res or not res.inner or res.inner == "" then
elseif type(flat) == "table" and #flat > 0 and type(flat[1]) == "table" then
return moduleBox(slotIndex, nil, "", true)
local pick = flat[1]
local atkFlag  = (pick["ATK-Based"] == true)
local matkFlag = (pick["MATK-Based"] == true)
basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)
 
sourceKind = "Flat"
sourceVal  = legacyPercentAtLevel(pick, level)
end
end
end


local scalingLines = formatScalingCompactLines(scaling)
return moduleBox(slotIndex, res.classes, res.inner, false)
local hasSource    = (sourceVal ~= nil and tostring(sourceVal) ~= "")
end
local hasScaling  = (type(scalingLines) == "table" and #scalingLines > 0)


if (not hasSource) and (not hasScaling) then
----------------------------------------------------------------------
return nil
-- UI builders
end
----------------------------------------------------------------------


local hasMod = (basisWord ~= nil and tostring(basisWord) ~= "")
local function buildHeroBarUI(rec, ctx)
local bar = mw.html.create("div")
bar:addClass("hero-bar-grid")
bar:wikitext(renderHeroBarSlot(1, rec, ctx))
bar:wikitext(renderHeroBarSlot(2, rec, ctx))
return tostring(bar)
end


local extra = { "module-source-type" }
local function buildHeroModulesUI(rec, ctx)
table.insert(extra, hasMod and "sv-has-mod" or "sv-no-mod")
local grid = mw.html.create("div")
 
grid:addClass("hero-modules-grid")
if hasSource and (not hasScaling) then
for slot = 1, 4 do
table.insert(extra, "sv-only-source")
grid:wikitext(renderModuleSlot(slot, rec, ctx))
elseif hasScaling and (not hasSource) then
table.insert(extra, "sv-only-scaling")
end
end
return tostring(grid)
end


local wrap = mw.html.create("div")
local function addHeroModulesRow(tbl, modulesUI)
wrap:addClass("sv-source-grid")
if not modulesUI or modulesUI == "" then
 
return
if hasMod then
local modCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-modifier")
modCol:tag("div"):addClass("sv-source-pill"):wikitext("Modifier")
modCol:tag("div"):addClass("sv-modifier-value"):wikitext(mw.text.nowiki(basisWord))
end
end


if hasSource then
local row = tbl:tag("tr")
local sourceCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-main")
row:addClass("hero-modules-row")
sourceCol:tag("div"):addClass("sv-source-pill"):wikitext(mw.text.nowiki(sourceKind or "Source"))
sourceCol:tag("div"):addClass("sv-source-value"):wikitext(sourceVal)
end


if hasScaling then
local cell = row:tag("td")
local scalingCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-scaling")
cell:attr("colspan", 2)
scalingCol:tag("div"):addClass("sv-source-pill"):wikitext("Scaling")
cell:addClass("hero-modules-cell")
cell:wikitext(modulesUI)
end


local list = scalingCol:tag("div"):addClass("sv-scaling-list")
----------------------------------------------------------------------
for _, line in ipairs(scalingLines) do
-- Infobox builder
list:tag("div"):addClass("sv-scaling-item"):wikitext(mw.text.nowiki(line))
----------------------------------------------------------------------
end
end


return {
local function buildInfobox(rec, opts)
inner = tostring(wrap),
opts = opts or {}
classes = extra,
local showUsers = (opts.showUsers ~= false)
}
end


-- Module: Quick Stats (PORTABLE)
local maxLevel = tonumber(rec["Max Level"]) or 1
function PLUGINS.QuickStats(rec, ctx)
if maxLevel < 1 then maxLevel = 1 end
local level = ctx.level or 1
local level = clamp(maxLevel, 1, maxLevel)
local maxLevel = ctx.maxLevel or 1
local promo = ctx.promo


local mech = (type(rec) == "table" and type(rec.Mechanics) == "table") and rec.Mechanics or {}
local ctx = {
local bt  = (type(mech["Basic Timings"]) == "table") and mech["Basic Timings"] or {}
maxLevel = maxLevel,
local rc  = (type(mech["Resource Cost"]) == "table") and mech["Resource Cost"] or {}
level = level,
nonDamaging = false,
promo = nil,
}


local function dash() return "—" end
-- Non-damaging hides Damage/Element in SkillType
 
do
-- Range (0 => —)
local dmgVal = nil
local rangeVal = nil
if type(rec.Type) == "table" then
if mech.Range ~= nil and not isNoneLike(mech.Range) then
dmgVal = rec.Type.Damage or rec.Type["Damage Type"]
local n = toNum(mech.Range)
if type(dmgVal) == "table" then
if n ~= nil then
dmgVal = dmgVal.Name or dmgVal.ID or dmgVal.Value
if n ~= 0 then
rangeVal = mw.text.nowiki(formatUnitValue(mech.Range) or tostring(mech.Range))
end
else
local t = mw.text.trim(tostring(mech.Range))
if t ~= "" and not isNoneLike(t) then
rangeVal = mw.text.nowiki(t)
end
end
end
end
ctx.nonDamaging = isNoneLike(dmgVal) or (not skillHasAnyDamage(rec, maxLevel))
end
end


-- Area
ctx.promo = computeDurationPromotion(rec, maxLevel)
local areaVal = formatAreaSize(mech.Area)


-- Timings
local root = mw.html.create("table")
local castSeries = seriesFromValuePair(bt["Cast Time"], maxLevel)
root:addClass("spiritvale-skill-infobox")
local cdSeries  = seriesFromValuePair(bt["Cooldown"], maxLevel)
root:addClass("sv-skill-card")
local durSeries  = seriesFromValuePair(bt["Duration"], maxLevel)
root:attr("data-max-level", tostring(maxLevel))
root:attr("data-level", tostring(level))


local castVal = displayFromSeries(castSeries, level)
if opts.inList then
local cdVal  = displayFromSeries(cdSeries, level)
root:addClass("sv-skill-inlist")
local durVal  = displayFromSeries(durSeries, level)
end


-- Promote status duration if needed
local internalId = trim(rec["Internal Name"] or rec.InternalID or rec.ID)
if (durVal == nil) and type(promo) == "table" and type(promo.durationBlock) == "table" then
if internalId then
durSeries = seriesFromValuePair(promo.durationBlock, maxLevel)
root:attr("data-skill-id", internalId)
durVal = displayFromSeries(durSeries, level)
end
end


-- Cost: combine MP + HP; never show "0 HP" (seriesFromValuePair already turns 0 into "—")
local desc  = rec.Description or ""
local function labeledSeries(block, label)
 
local s = seriesFromValuePair(block, maxLevel)
-- Hero Title Bar
if not s then return nil end
local heroRow = root:tag("tr")
local any = false
heroRow:addClass("spiritvale-infobox-main")
for i, v in ipairs(s) do
heroRow:addClass("sv-hero-title-row")
if v ~= "" then
heroRow:addClass("hero-title-bar")
s[i] = tostring(v) .. " " .. label
any = true
else
s[i] = ""
end
end
return any and s or nil
end


local mpS = labeledSeries(rc["Mana Cost"], "MP")
local heroCell = heroRow:tag("th")
local hpS = labeledSeries(rc["Health Cost"], "HP")
heroCell:attr("colspan", 2)
heroCell:addClass("sv-hero-title-cell")
heroCell:wikitext(buildHeroBarUI(rec, ctx))


local costSeries = {}
-- Description Bar
for lv = 1, maxLevel do
if desc ~= "" then
local mp = mpS and mpS[lv] or ""
local descRow = root:tag("tr")
local hp = hpS and hpS[lv] or ""
descRow:addClass("spiritvale-infobox-main")
descRow:addClass("sv-hero-desc-row")
descRow:addClass("hero-description-bar")


if mp ~= "" and hp ~= "—" then
local descCell = descRow:tag("td")
costSeries[lv] = mp .. " + " .. hp
descCell:attr("colspan", 2)
elseif mp ~= "—" then
descCell:addClass("sv-hero-desc-cell")
costSeries[lv] = mp
elseif hp ~= "" then
costSeries[lv] = hp
else
costSeries[lv] = ""
end
end


local costVal = displayFromSeries(costSeries, level)
local descInner = descCell:tag("div")
descInner:addClass("spiritvale-infobox-main-right-inner")


local grid = mw.html.create("div")
descInner:tag("div")
grid:addClass("sv-m4-grid")
:addClass("spiritvale-infobox-description")
 
:wikitext(string.format("''%s''", desc))
local function addCell(label, val)
local cell = grid:tag("div"):addClass("sv-m4-cell")
cell:tag("div"):addClass("sv-m4-label"):wikitext(mw.text.nowiki(label))
cell:tag("div"):addClass("sv-m4-value"):wikitext(val or dash())
end
end


addCell("Range",    rangeVal)
-- Modules row
addCell("Area",      areaVal)
addHeroModulesRow(root, buildHeroModulesUI(rec, ctx))
addCell("Cost",      costVal)
addCell("Cast Time", castVal)
addCell("Cooldown", cdVal)
addCell("Duration",  durVal)


return {
-- Users (hide on direct skill page)
inner = tostring(grid),
if showUsers then
classes = "module-quick-stats",
local users = rec.Users or {}
}
addRow(root, "Classes",  listToText(users.Classes),  "sv-row-users", "Users.Classes")
end
addRow(root, "Summons",  listToText(users.Summons),  "sv-row-users", "Users.Summons")
addRow(root, "Monsters", listToText(users.Monsters), "sv-row-users", "Users.Monsters")
addRow(root, "Events",  listToText(users.Events),  "sv-row-users", "Users.Events")
end


----------------------------------------------------------------------
-- Requirements
-- Generic slot renderers
local req = rec.Requirements or {}
----------------------------------------------------------------------
local hasReq =
(type(req["Required Skills"]) == "table" and #req["Required Skills"] > 0) or
(type(req["Required Weapons"]) == "table" and #req["Required Weapons"] > 0) or
(type(req["Required Stances"]) == "table" and #req["Required Stances"] > 0)
 
if hasReq then
if type(req["Required Skills"]) == "table" and #req["Required Skills"] > 0 then
local skillParts = {}
for _, rs in ipairs(req["Required Skills"]) do
local nameReq = rs["Skill External Name"] or rs["Skill Internal Name"] or "Unknown"
local lvlReq  = rs["Required Level"]
if lvlReq then
table.insert(skillParts, string.format("%s (Lv.%s)", nameReq, lvlReq))
else
table.insert(skillParts, nameReq)
end
end
addRow(root, "Required Skills", table.concat(skillParts, ", "), "sv-row-req", "Requirements.Required Skills")
end


local function normalizeResult(res)
addRow(root, "Required Weapons", listToText(req["Required Weapons"]), "sv-row-req", "Requirements.Required Weapons")
if res == nil then return nil end
addRow(root, "Required Stances", listToText(req["Required Stances"]), "sv-row-req", "Requirements.Required Stances")
if type(res) == "string" then
return { inner = res, classes = nil }
end
end
if type(res) == "table" then
 
local inner = res.inner
-- Mechanics (keep small extras only; Special Mechanics/Flags/Combo are now in the module)
if type(inner) ~= "string" then
local mech = rec.Mechanics or {}
inner = (inner ~= nil) and tostring(inner) or ""
if next(mech) ~= nil then
if mech["Autocast Multiplier"] ~= nil then
addRow(root, "Autocast Multiplier", tostring(mech["Autocast Multiplier"]), "sv-row-mech", "Mechanics.Autocast Multiplier")
end
end
return { inner = inner, classes = res.classes }
end
end
return { inner = tostring(res), classes = nil }
end


local function safeCallPlugin(name, rec, ctx)
-- Legacy damage breakdown (only when Source absent)
local fn = PLUGINS[name]
if type(rec.Source) ~= "table" then
if type(fn) ~= "function" then
local dmg = rec.Damage or {}
return nil
if next(dmg) ~= nil then
end
local main = dmg["Main Damage"]
local ok, out = pcall(fn, rec, ctx)
local mainNonHeal, healOnly = {}, {}
if not ok then
return nil
end
return normalizeResult(out)
end


local function renderHeroBarSlot(slotIndex, rec, ctx)
if type(main) == "table" then
local pluginName = HERO_BAR_SLOT_ASSIGNMENT[slotIndex]
for _, d in ipairs(main) do
if not pluginName then
if type(d) == "table" and d.Type == "Healing" then
return heroBarBox(slotIndex, nil, nil, "", true)
table.insert(healOnly, d)
end
else
table.insert(mainNonHeal, d)
end
end
end


local res = safeCallPlugin(pluginName, rec, ctx)
addRow(root, "Main Damage",   formatDamageList(mainNonHeal, maxLevel, level, (#mainNonHeal > 1)), "sv-row-source", "Damage.Main Damage")
if not res or not res.inner or res.inner == "" then
addRow(root, "Flat Damage",    formatDamageList(dmg["Flat Damage"], maxLevel, level, false),        "sv-row-source", "Damage.Flat Damage")
return heroBarBox(slotIndex, pluginName, nil, "", true)
addRow(root, "Reflect Damage", formatDamageList(dmg["Reflect Damage"], maxLevel, level, false),    "sv-row-source", "Damage.Reflect Damage")
addRow(root, "Healing",        formatDamageList(healOnly, maxLevel, level, false),                 "sv-row-source", "Damage.Healing")
end
end
end


return heroBarBox(slotIndex, pluginName, res.classes, res.inner, false)
-- Status rows (unchanged)
end
local function formatStatusApplications(list, suppressDurationIndex)
if type(list) ~= "table" or #list == 0 then return nil end


local function renderModuleSlot(slotIndex, rec, ctx)
local parts = {}
local pluginName = HERO_MODULE_SLOT_ASSIGNMENT[slotIndex]
for idx, s in ipairs(list) do
if not pluginName then
if type(s) == "table" then
return moduleBox(slotIndex, nil, nil, "", true)
local typ  = s.Type or s.Scope or "Target"
end
local name = s["Status External Name"] or s["Status Internal Name"] or "Unknown status"
local seg = tostring(typ) .. " " .. tostring(name)
local detail = {}


local res = safeCallPlugin(pluginName, rec, ctx)
if idx ~= suppressDurationIndex and type(s.Duration) == "table" then
if not res or not res.inner or res.inner == "" then
local t = valuePairDynamicValueOnly(s.Duration, maxLevel, level)
return moduleBox(slotIndex, pluginName, nil, "", true)
if t then table.insert(detail, "Duration: " .. t) end
end
end


return moduleBox(slotIndex, pluginName, res.classes, res.inner, false)
if type(s.Chance) == "table" then
end
local t = valuePairDynamicValueOnly(s.Chance, maxLevel, level)
if t then table.insert(detail, "Chance: " .. t) end
end


----------------------------------------------------------------------
if #detail > 0 then
-- UI builders (hero bar + modules grid)
seg = seg .. " (" .. table.concat(detail, ", ") .. ")"
----------------------------------------------------------------------
end


local function buildHeroBarUI(rec, ctx)
table.insert(parts, seg)
local bar = mw.html.create("div")
end
bar:addClass("hero-bar-grid")
end


bar:wikitext(renderHeroBarSlot(1, rec, ctx))
return (#parts > 0) and table.concat(parts, "<br />") or nil
bar:wikitext(renderHeroBarSlot(2, rec, ctx))
end


return tostring(bar)
local function formatStatusRemoval(list)
end
if type(list) ~= "table" or #list == 0 then return nil end


local function buildHeroModulesUI(rec, ctx)
local parts = {}
local grid = mw.html.create("div")
for _, r in ipairs(list) do
grid:addClass("hero-modules-grid")
if type(r) == "table" then
local names = r["Status External Name"]
local label


for slot = 1, 4 do
if type(names) == "table" then
grid:wikitext(renderModuleSlot(slot, rec, ctx))
label = table.concat(names, ", ")
end
elseif type(names) == "string" then
label = names
else
label = "Status"
end


return tostring(grid)
local amt = valuePairRawText(r)
end
amt = amt and mw.text.nowiki(amt) or nil


local function addHeroModulesRow(tbl, modulesUI)
local seg = mw.text.nowiki(label)
if not modulesUI or modulesUI == "" then
if amt then
return
seg = seg .. " " .. amt
end
end
 
table.insert(parts, seg)
local row = tbl:tag("tr")
row:addClass("hero-modules-row")
 
local cell = row:tag("td")
cell:attr("colspan", 2)
cell:addClass("hero-modules-cell")
cell:wikitext(modulesUI)
end
 
----------------------------------------------------------------------
-- Infobox builder
----------------------------------------------------------------------
 
local function buildInfobox(rec, opts)
opts = opts or {}
local showUsers = (opts.showUsers ~= false)
 
local maxLevel = tonumber(rec["Max Level"]) or 1
if maxLevel < 1 then maxLevel = 1 end
local level = clamp(maxLevel, 1, maxLevel)
 
-- ctx passed to every plug-in (the only allowed “shared state”)
local ctx = {
maxLevel = maxLevel,
level = level,
-- computed below:
nonDamaging = false,
promo = nil,
}
 
-- Determine “non-damaging” for SkillType (hide Damage/Element)
do
local dmgVal = nil
if type(rec.Type) == "table" then
dmgVal = rec.Type.Damage or rec.Type["Damage Type"]
if type(dmgVal) == "table" then
dmgVal = dmgVal.Name or dmgVal.ID or dmgVal.Value
end
end
ctx.nonDamaging = isNoneLike(dmgVal) or (not skillHasAnyDamage(rec, maxLevel))
end
 
-- Duration promotion (for QuickStats + Applies suppression)
ctx.promo = computeDurationPromotion(rec, maxLevel)
 
local root = mw.html.create("table")
root:addClass("spiritvale-skill-infobox")
root:addClass("sv-skill-card")
root:attr("data-max-level", tostring(maxLevel))
root:attr("data-level", tostring(level))
 
if opts.inList then
root:addClass("sv-skill-inlist")
end
 
local internalId = trim(rec["Internal Name"] or rec.InternalID or rec.ID)
if internalId then
root:attr("data-skill-id", internalId)
end
 
local desc  = rec.Description or ""
 
-- Hero Title Bar
local heroRow = root:tag("tr")
heroRow:addClass("spiritvale-infobox-main")
heroRow:addClass("sv-hero-title-row")
heroRow:addClass("hero-title-bar")
 
local heroCell = heroRow:tag("th")
heroCell:attr("colspan", 2)
heroCell:addClass("sv-hero-title-cell")
heroCell:wikitext(buildHeroBarUI(rec, ctx))
 
-- Description Bar (special-cased for now)
if desc ~= "" then
local descRow = root:tag("tr")
descRow:addClass("spiritvale-infobox-main")
descRow:addClass("sv-hero-desc-row")
descRow:addClass("hero-description-bar")
 
local descCell = descRow:tag("td")
descCell:attr("colspan", 2)
descCell:addClass("sv-hero-desc-cell")
 
local descInner = descCell:tag("div")
descInner:addClass("spiritvale-infobox-main-right-inner")
 
descInner:tag("div")
:addClass("spiritvale-infobox-description")
:wikitext(string.format("''%s''", desc))
end
 
-- Modules row
local modulesUI = buildHeroModulesUI(rec, ctx)
addHeroModulesRow(root, modulesUI)
 
-- Users (hide on direct skill page)
if showUsers then
local users = rec.Users or {}
addRow(root, "Classes",  listToText(users.Classes),  "sv-row-users", "Users.Classes")
addRow(root, "Summons",  listToText(users.Summons),  "sv-row-users", "Users.Summons")
addRow(root, "Monsters", listToText(users.Monsters), "sv-row-users", "Users.Monsters")
addRow(root, "Events",  listToText(users.Events),  "sv-row-users", "Users.Events")
end
 
-- Requirements
local req = rec.Requirements or {}
local hasReq =
(type(req["Required Skills"]) == "table" and #req["Required Skills"] > 0) or
(type(req["Required Weapons"]) == "table" and #req["Required Weapons"] > 0) or
(type(req["Required Stances"]) == "table" and #req["Required Stances"] > 0)
 
if hasReq then
if type(req["Required Skills"]) == "table" and #req["Required Skills"] > 0 then
local skillParts = {}
for _, rs in ipairs(req["Required Skills"]) do
local nameReq = rs["Skill External Name"] or rs["Skill Internal Name"] or "Unknown"
local lvlReq  = rs["Required Level"]
if lvlReq then
table.insert(skillParts, string.format("%s (Lv.%s)", nameReq, lvlReq))
else
table.insert(skillParts, nameReq)
end
end
end
addRow(root, "Required Skills", table.concat(skillParts, ", "), "sv-row-req", "Requirements.Required Skills")
end
end


addRow(root, "Required Weapons", listToText(req["Required Weapons"]), "sv-row-req", "Requirements.Required Weapons")
return (#parts > 0) and table.concat(parts, "<br />") or nil
addRow(root, "Required Stances", listToText(req["Required Stances"]), "sv-row-req", "Requirements.Required Stances")
end
end


-- Mechanics (detailed rows still shown; Range/Area/Timings/Cost are in QuickStats)
local suppressIdx = (type(ctx.promo) == "table") and ctx.promo.suppressDurationIndex or nil
local mech = rec.Mechanics or {}
local statusApps = formatStatusApplications(rec["Status Applications"], suppressIdx)
if next(mech) ~= nil then
local statusRem  = formatStatusRemoval(rec["Status Removal"])
if mech["Autocast Multiplier"] ~= nil then
if statusApps or statusRem then
addRow(root, "Autocast Multiplier", tostring(mech["Autocast Multiplier"]), "sv-row-mech", "Mechanics.Autocast Multiplier")
addRow(root, "Applies", statusApps, "sv-row-status", "Status Applications")
end
addRow(root, "Removes", statusRem, "sv-row-status", "Status Removal")
 
addRow(root, "Combo",             formatCombo(mech.Combo), "sv-row-mech", "Mechanics.Combo")
addRow(root, "Special Mechanics", formatMechanicEffects(mech.Effects, maxLevel, level), "sv-row-mech", "Mechanics.Effects")
end
end


-- Source + Scaling are displayed in SourceType module now, so we do NOT repeat them as body rows.
-- Events
-- Keep the detailed legacy damage breakdown rows only (Main/Flat/Reflect/Healing) when Source missing.
local function formatEvents(list)
if type(rec.Source) ~= "table" then
if type(list) ~= "table" or #list == 0 then return nil end
local dmg = rec.Damage or {}
local parts = {}
if next(dmg) ~= nil then
for _, ev in ipairs(list) do
local main = dmg["Main Damage"]
if type(ev) == "table" then
local mainNonHeal, healOnly = {}, {}
local action = ev.Action or "On event"
 
local name  = ev["Skill Internal Name"] or ev["Skill External Name"] or "Unknown skill"
if type(main) == "table" then
table.insert(parts, string.format("%s → %s", action, name))
for _, d in ipairs(main) do
if type(d) == "table" and d.Type == "Healing" then
table.insert(healOnly, d)
else
table.insert(mainNonHeal, d)
end
end
end
end
local flatList = dmg["Flat Damage"]
local reflList = dmg["Reflect Damage"]
addRow(root, "Main Damage",    formatDamageList(mainNonHeal, maxLevel, level, (#mainNonHeal > 1)), "sv-row-source", "Damage.Main Damage")
addRow(root, "Flat Damage",    formatDamageList(flatList, maxLevel, level, false), "sv-row-source", "Damage.Flat Damage")
addRow(root, "Reflect Damage", formatDamageList(reflList, maxLevel, level, false), "sv-row-source", "Damage.Reflect Damage")
addRow(root, "Healing",        formatDamageList(healOnly, maxLevel, level, false), "sv-row-source", "Damage.Healing")
end
end
return (#parts > 0) and table.concat(parts, "<br />") or nil
end
end


-- Modifiers flags
local modsText = formatModifiers(rec.Modifiers)
if modsText then
addRow(root, "Flags", modsText, "sv-row-meta", "Modifiers")
end
-- Status (suppress promoted duration line if needed)
local suppressIdx = (type(ctx.promo) == "table") and ctx.promo.suppressDurationIndex or nil
local statusApps = formatStatusApplications(rec["Status Applications"], maxLevel, level, suppressIdx)
local statusRem  = formatStatusRemoval(rec["Status Removal"], maxLevel, level)
if statusApps or statusRem then
addRow(root, "Applies", statusApps, "sv-row-status", "Status Applications")
addRow(root, "Removes", statusRem,  "sv-row-status", "Status Removal")
end
-- Events
local eventsText = formatEvents(rec.Events)
local eventsText = formatEvents(rec.Events)
if eventsText then
if eventsText then

Revision as of 19:52, 17 December 2025

Module:GameSkills

Module:GameSkills renders skill data from Data:skills.json into a reusable infobox-style table.

It is intended to be used via a template (for example Template:Skill) so that skills can be embedded on any page without creating individual skill pages.

This module:

  • Loads data via Module:GameDataGameData.loadSkills().
  • Looks up skills primarily by display "Name" (what editors use), with "Internal Name" as a fallback.
  • Builds a table with only the fields that actually exist for that skill.

Data source

Skill data comes from Data:skills.json, which is a JSON page with this top-level structure (see Module:GameData/doc for full details):

{
  "version": "SpiritVale-0.8.2",
  "schema_version": 1,
  "generated_at": "2025-12-12T17:24:05.807675+00:00",
  "records": [
    {
      "Name": "Some Skill",
      "Internal Name": "SomeSkillInternalId",
      "...": "other fields specific to skills"
    }
  ]
}

Each record is a single skill. Important keys:

  • "Name" – the display name (what players and editors will usually see and use).
  • "Internal Name" – the stable ID used internally and available as an optional parameter for power users and tooling.

Output

For a given skill, the module renders a table with the CSS class spiritvale-skill-infobox.

Depending on what exists in the JSON record, the table may include:

  • Header row with skill name (and icon, if present).
  • Icon (from "Icon", as a file name like skill-example.webp).
  • Description.
  • Type information:
    • Damage Type
    • Element Type
    • Target Type
    • Cast Type
  • Max Level.
  • Users:
    • Classes
    • Summons
    • Monsters
    • Events
  • Requirements:
    • Required Skills (with required level)
    • Required Weapons
    • Required Stances
  • Mechanics:
    • Range
    • Cast Time / Cooldown / Duration
    • Mana Cost
  • Damage and scaling:
    • Main Damage (base and per-level, where present)
    • Scaling (stat-based contributions)
  • Status interactions:
    • Status Applications (status name, scope, basic duration/chance info)

Rows are only shown if the underlying field exists in the JSON for that skill.


Public interface

The module exposes a single entry point for templates:

GameSkills.infobox(frame)

This is usually called via #invoke from a template, not directly from pages.

It accepts the following parameters (either passed directly or via a wrapper template):

  • 1 – unnamed parameter; treated as the skill "Name".
  • name – explicit display "Name" of the skill (equivalent to 1).
  • id"Internal Name" of the skill (optional fallback / power use).

Lookup order:

  1. If name or the first unnamed parameter is provided and matches a record’s "Name", that record is used.
  2. Otherwise, if id is provided and matches an "Internal Name", that record is used.
  3. If nothing is found, a small error message is returned and the page is categorized for tracking.

Example direct usage (not recommended; normally use a template):

No skills found for: GameSkills

or:

No skills found for: GameSkills

Template:Skill

The recommended way to use this module is via a small wrapper template, for example:

Template:Skill
 No skills found for: GameSkills

Typical usage on any page:

Bash
Damage
Melee
Element
Neutral
Target
Enemy
Cast
Target
Delivers a crushing blow with a chance to stun the target.
Modifier
Attack
Damage
325%
Scaling
2% Strength
Range
Area
Cost
12 MP
Cast Time
Cooldown
Duration
Self Centered
Combo
Ready (4s)
Level 10 / 10
<input type="range" min="1" max="10" value="10" class="sv-level-range" aria-label="Skill level select" />
ClassesWarrior, Weaver
MonstersAshrend, Goblin King
Required SkillsAxe Mastery (Lv.1)
AppliesTarget – Stun (Duration: 3s, Chance: 30%)

or, explicitly:

Bash
Damage
Melee
Element
Neutral
Target
Enemy
Cast
Target
Delivers a crushing blow with a chance to stun the target.
Modifier
Attack
Damage
325%
Scaling
2% Strength
Range
Area
Cost
12 MP
Cast Time
Cooldown
Duration
Self Centered
Combo
Ready (4s)
Level 10 / 10
<input type="range" min="1" max="10" value="10" class="sv-level-range" aria-label="Skill level select" />
ClassesWarrior, Weaver
MonstersAshrend, Goblin King
Required SkillsAxe Mastery (Lv.1)
AppliesTarget – Stun (Duration: 3s, Chance: 30%)

Internal IDs can still be used when needed:

Unknown Skill: Bash_InternalId

This keeps page wikitext simple while centralizing all JSON loading and formatting logic inside Lua.


-- Module:GameSkills
--
-- Phase 6.5+ (Plug-in Slot Architecture)
--
-- Standard Hero Layout:
--   1) hero-title-bar        (TOP BAR, 2 slots: herobar 1..2)
--   2) hero-description-bar  (description strip)
--   3) hero-modules row      (4 slots: hero-module-1..4)
--
-- Requires Common.js:
--   - updates .sv-dyn spans via data-series
--   - updates .sv-level-num + data-level on .sv-skill-card
--   - binds to input.sv-level-range inside each card

local GameData = require("Module:GameData")

local p = {}

----------------------------------------------------------------------
-- Data cache
----------------------------------------------------------------------

local skillsCache

local function getSkills()
	if not skillsCache then
		skillsCache = GameData.loadSkills()
	end
	return skillsCache
end

----------------------------------------------------------------------
-- Small utilities
----------------------------------------------------------------------

local function getArgs(frame)
	local parent = frame:getParent()
	return (parent and parent.args) or frame.args
end

local function trim(s)
	if type(s) ~= "string" then
		return nil
	end
	s = mw.text.trim(s)
	return (s ~= "" and s) or nil
end

local function toNum(v)
	if type(v) == "number" then
		return v
	end
	if type(v) == "string" then
		return tonumber(v)
	end
	if type(v) == "table" and v.Value ~= nil then
		return toNum(v.Value)
	end
	return nil
end

local function clamp(n, lo, hi)
	if type(n) ~= "number" then
		return lo
	end
	if n < lo then return lo end
	if n > hi then return hi end
	return n
end

local function fmtNum(n)
	if type(n) ~= "number" then
		return (n ~= nil) and tostring(n) or nil
	end

	if math.abs(n - math.floor(n)) < 1e-9 then
		return tostring(math.floor(n))
	end

	local s = string.format("%.4f", n)
	s = mw.ustring.gsub(s, "0+$", "")
	s = mw.ustring.gsub(s, "%.$", "")
	return s
end

local function listToText(list, sep)
	if type(list) ~= "table" or #list == 0 then
		return nil
	end
	return table.concat(list, sep or ", ")
end

local function isNoneLike(v)
	if v == nil then return true end
	local s = mw.text.trim(tostring(v))
	if s == "" then return true end
	s = mw.ustring.lower(s)
	return (s == "none" or s == "no" or s == "n/a" or s == "na" or s == "null")
end

local function addRow(tbl, label, value, rowClass, dataKey)
	if value == nil or value == "" then
		return
	end

	local row = tbl:tag("tr")
	row:addClass("sv-row")
	if rowClass then row:addClass(rowClass) end
	if dataKey then row:attr("data-field", dataKey) end

	row:tag("th"):wikitext(label):done()
	row:tag("td"):wikitext(value):done()
end

-- { Value, Unit } or scalar
local function formatUnitValue(v)
	if type(v) == "table" and v.Value ~= nil then
		local unit = v.Unit
		local val  = v.Value

		if unit == "percent_decimal" or unit == "percent_whole" or unit == "percent" then
			return tostring(val) .. "%"
		elseif unit == "seconds" then
			return tostring(val) .. "s"
		elseif unit == "meters" then
			return tostring(val) .. "m"
		elseif unit == "tiles" then
			return tostring(val) .. " tiles"
		elseif unit and unit ~= "" then
			return tostring(val) .. " " .. tostring(unit)
		else
			return tostring(val)
		end
	end

	return (v ~= nil) and tostring(v) or nil
end

----------------------------------------------------------------------
-- Dynamic spans (JS-driven)
----------------------------------------------------------------------

local function dynSpan(series, level)
	if type(series) ~= "table" or #series == 0 then
		return nil
	end

	level = clamp(level or #series, 1, #series)

	local span = mw.html.create("span")
	span:addClass("sv-dyn")
	span:attr("data-series", mw.text.jsonEncode(series))
	span:wikitext(mw.text.nowiki(series[level] or ""))

	return tostring(span)
end

local function isFlatList(list)
	if type(list) ~= "table" or #list == 0 then
		return false
	end
	local first = tostring(list[1])
	for i = 2, #list do
		if tostring(list[i]) ~= first then
			return false
		end
	end
	return true
end

local function isNonZeroScalar(v)
	if v == nil then return false end
	if type(v) == "number" then return v ~= 0 end
	if type(v) == "string" then
		local n = tonumber(v)
		if n == nil then return v ~= "" end
		return n ~= 0
	end
	if type(v) == "table" and v.Value ~= nil then
		return isNonZeroScalar(v.Value)
	end
	return true
end

local function isZeroish(v)
	if v == nil then return true end
	if type(v) == "number" then return v == 0 end
	if type(v) == "table" and v.Value ~= nil then
		return isZeroish(v.Value)
	end

	local s = mw.text.trim(tostring(v))
	if s == "" then return true end
	if s == "0" or s == "0.0" or s == "0.00" then return true end
	if s == "0s" or s == "0 s" then return true end
	if s == "0m" or s == "0 m" then return true end
	if s == "0%" or s == "0 %" then return true end

	local n = tonumber((mw.ustring.gsub(s, "[^0-9%.%-]", "")))
	return (n ~= nil and n == 0)
end

local function valuePairRawText(block)
	if type(block) ~= "table" then
		return nil
	end

	local base = block.Base
	local per  = block["Per Level"]

	if type(per) == "table" then
		if #per == 0 then
			return formatUnitValue(base)
		end
		if isFlatList(per) then
			return formatUnitValue(base) or tostring(per[1])
		end

		local vals = {}
		for _, v in ipairs(per) do
			table.insert(vals, formatUnitValue(v) or tostring(v))
		end
		return (#vals > 0) and table.concat(vals, " / ") or nil
	end

	local baseText = formatUnitValue(base)
	local perText  = formatUnitValue(per)

	if baseText and perText and isNonZeroScalar(per) then
		return string.format("%s (Per Level: %s)", baseText, perText)
	end

	return baseText or perText
end

local function valuePairDynamicValueOnly(block, maxLevel, level)
	if type(block) ~= "table" then
		return nil
	end

	local base = block.Base
	local per  = block["Per Level"]

	if type(per) == "table" then
		if #per == 0 then
			local baseText = formatUnitValue(base)
			return baseText and mw.text.nowiki(baseText) or nil
		end

		if isFlatList(per) then
			local one  = formatUnitValue(per[1]) or tostring(per[1])
			local show = formatUnitValue(base) or one
			return show and mw.text.nowiki(show) or nil
		end

		local series = {}
		for _, v in ipairs(per) do
			table.insert(series, formatUnitValue(v) or tostring(v))
		end
		return dynSpan(series, level)
	end

	local txt = valuePairRawText(block)
	return txt and mw.text.nowiki(txt) or nil
end

----------------------------------------------------------------------
-- Lookups
----------------------------------------------------------------------

local function getSkillById(id)
	id = trim(id)
	if not id then return nil end
	local dataset = getSkills()
	return (dataset.byId or {})[id]
end

local function findSkillByName(name)
	name = trim(name)
	if not name then return nil end

	local dataset = getSkills()
	local byName = dataset.byName or {}

	if byName[name] then
		return byName[name]
	end

	for _, rec in ipairs(dataset.records or {}) do
		if type(rec) == "table" then
			if rec["External Name"] == name or rec.Name == name or rec["Display Name"] == name then
				return rec
			end
		end
	end

	return nil
end

----------------------------------------------------------------------
-- Legacy damage helpers
----------------------------------------------------------------------

local function basisLabel(entry, isHealing)
	if isHealing then
		return "Healing"
	end

	local atk  = entry and entry["ATK-Based"]
	local matk = entry and entry["MATK-Based"]

	if atk and matk then
		return "Attack/Magic Attack"
	elseif atk then
		return "Attack"
	elseif matk then
		return "Magic Attack"
	end

	return "Damage"
end

local function formatDamageEntry(entry, maxLevel, level)
	if type(entry) ~= "table" then
		return nil
	end

	local isHealing = (entry.Type == "Healing")
	local basis = isHealing and "Healing" or basisLabel(entry, false)

	local baseRaw = entry["Base %"]
	local perRaw  = entry["Per Level %"]

	local baseN = toNum(baseRaw)
	local perN  = toNum(perRaw)

	local function baseIsPresent()
		if baseN ~= nil then
			return baseN ~= 0
		end
		if baseRaw ~= nil then
			local s = tostring(baseRaw)
			return (s ~= "" and s ~= "0" and s ~= "0.0" and s ~= "0.00")
		end
		return false
	end

	local baseText
	if baseIsPresent() then
		baseText = (baseN ~= nil) and (fmtNum(baseN) .. "%") or (tostring(baseRaw) .. "%")
	end

	if perN == nil or perN == 0 or not maxLevel or maxLevel <= 0 then
		return baseText and mw.text.nowiki(baseText .. " " .. basis) or nil
	end

	local series = {}
	for lv = 1, maxLevel do
		local perPart = perN * lv

		if baseText and baseN ~= nil then
			local total = baseN + perPart
			table.insert(series, string.format("%s%% %s", fmtNum(total), basis))
		elseif baseText then
			table.insert(series, string.format("%s + %s%% %s", baseText, fmtNum(perPart), basis))
		else
			table.insert(series, string.format("%s%% %s", fmtNum(perPart), basis))
		end
	end

	return dynSpan(series, level)
end

local function formatDamageList(list, maxLevel, level, includeTypePrefix)
	if type(list) ~= "table" or #list == 0 then
		return nil
	end

	local parts = {}
	for _, d in ipairs(list) do
		if type(d) == "table" then
			local txt = formatDamageEntry(d, maxLevel, level)
			if txt then
				if includeTypePrefix and d.Type and d.Type ~= "" then
					table.insert(parts, mw.text.nowiki(tostring(d.Type) .. ": ") .. txt)
				else
					table.insert(parts, txt)
				end
			end
		end
	end

	return (#parts > 0) and table.concat(parts, "<br />") or nil
end

----------------------------------------------------------------------
-- Users matching
----------------------------------------------------------------------

local function skillMatchesUser(rec, userName)
	if type(rec) ~= "table" or not userName or userName == "" then
		return false
	end

	local users = rec.Users
	if type(users) ~= "table" then
		return false
	end

	local userLower = mw.ustring.lower(userName)

	local function listHas(list)
		if type(list) ~= "table" then
			return false
		end
		for _, v in ipairs(list) do
			if type(v) == "string" and mw.ustring.lower(v) == userLower then
				return true
			end
		end
		return false
	end

	return listHas(users.Classes) or listHas(users.Summons) or listHas(users.Monsters) or listHas(users.Events)
end

----------------------------------------------------------------------
-- Hide Users on direct skill pages
----------------------------------------------------------------------

local function isDirectSkillPage(rec)
	if type(rec) ~= "table" then
		return false
	end

	local pageTitle = mw.title.getCurrentTitle()
	local pageName  = pageTitle and pageTitle.text or ""
	pageName = trim(pageName)
	if not pageName then
		return false
	end

	pageName = mw.ustring.lower(pageName)

	local ext = trim(rec["External Name"] or rec.Name or rec["Display Name"])
	local internal = trim(rec["Internal Name"] or rec.InternalName or rec.InternalID)

	return (ext and mw.ustring.lower(ext) == pageName) or (internal and mw.ustring.lower(internal) == pageName) or false
end

----------------------------------------------------------------------
-- Slot config (edit these tables only to rearrange layout)
----------------------------------------------------------------------

local HERO_BAR_SLOT_ASSIGNMENT = {
	[1] = "IconName",
	[2] = "SkillType",
}

local HERO_MODULE_SLOT_ASSIGNMENT = {
	[1] = "SourceType",
	[2] = "QuickStats",
	[3] = "SpecialMechanics",
	[4] = "LevelSelector", -- NEW
}

----------------------------------------------------------------------
-- Slot scaffolds
----------------------------------------------------------------------

local function heroBarBox(slot, extraClasses, innerHtml, isEmpty)
	local box = mw.html.create("div")
	box:addClass("hero-bar-module")
	box:addClass("hero-bar-module-" .. tostring(slot))
	box:attr("data-hero-bar-module", tostring(slot))

	-- Mark herobar slot 2 as "compact-spread target" (CSS does the rest)
	if slot == 2 then
		box:addClass("sv-herobar-compact")
	end

	if extraClasses then
		if type(extraClasses) == "string" then
			box:addClass(extraClasses)
		elseif type(extraClasses) == "table" then
			for _, c in ipairs(extraClasses) do box:addClass(c) end
		end
	end

	if isEmpty then
		box:addClass("hero-bar-module-empty")
	end

	local body = box:tag("div"):addClass("hero-bar-module-body")
	if innerHtml and innerHtml ~= "" then
		body:wikitext(innerHtml)
	end

	return tostring(box)
end

local function moduleBox(slot, extraClasses, innerHtml, isEmpty)
	local box = mw.html.create("div")
	box:addClass("hero-module")
	box:addClass("hero-module-" .. tostring(slot))
	box:attr("data-hero-module", tostring(slot))

	if extraClasses then
		if type(extraClasses) == "string" then
			box:addClass(extraClasses)
		elseif type(extraClasses) == "table" then
			for _, c in ipairs(extraClasses) do box:addClass(c) end
		end
	end

	if isEmpty then
		box:addClass("hero-module-empty")
	end

	local body = box:tag("div"):addClass("hero-module-body")
	if innerHtml and innerHtml ~= "" then
		body:wikitext(innerHtml)
	end

	return tostring(box)
end

----------------------------------------------------------------------
-- Shared helpers (Source + QuickStats + SpecialMechanics)
----------------------------------------------------------------------

local function formatScalingCompactLines(scaling)
	if type(scaling) ~= "table" then
		return {}
	end

	local list = scaling
	if #list == 0 then
		if scaling.Percent ~= nil or scaling["Scaling ID"] or scaling["Scaling Name"] then
			list = { scaling }
		else
			return {}
		end
	end

	local out = {}
	for _, s in ipairs(list) do
		if type(s) == "table" then
			local stat = s["Scaling Name"] or s["Scaling ID"] or "Unknown"
			local pct  = s.Percent
			local pctN = toNum(pct)

			if pctN ~= nil and pctN ~= 0 then
				table.insert(out, string.format("%s%% %s", fmtNum(pctN), stat))
			elseif pct ~= nil and tostring(pct) ~= "" and tostring(pct) ~= "0" then
				table.insert(out, string.format("%s%% %s", tostring(pct), stat))
			end
		end
	end

	return out
end

local function basisWordFromFlags(atkFlag, matkFlag)
	if atkFlag and matkFlag then
		return "Hybrid"
	elseif atkFlag then
		return "Attack"
	elseif matkFlag then
		return "Magic Attack"
	end
	return nil
end

local function legacyPercentAtLevel(entry, level)
	if type(entry) ~= "table" then
		return nil
	end

	local baseRaw = entry["Base %"]
	local perRaw  = entry["Per Level %"]
	local baseN   = toNum(baseRaw)
	local perN    = toNum(perRaw)

	if perN ~= nil and perN ~= 0 then
		local total = (baseN or 0) + (perN * level)
		return fmtNum(total) .. "%"
	end

	if baseN ~= nil then
		return fmtNum(baseN) .. "%"
	end
	if baseRaw ~= nil and tostring(baseRaw) ~= "" then
		return tostring(baseRaw) .. "%"
	end

	return nil
end

local function seriesFromValuePair(block, maxLevel)
	if type(block) ~= "table" then
		return nil
	end

	local base = block.Base
	local per  = block["Per Level"]

	local function pickUnit(v)
		if type(v) == "table" and v.Unit and v.Unit ~= "" then
			return v.Unit
		end
		return nil
	end
	local unit = pickUnit(base) or pickUnit(per)

	local function fmtAny(v)
		local t = formatUnitValue(v)
		return t and tostring(t) or (v ~= nil and tostring(v) or nil)
	end

	local series = {}

	-- Expanded per-level series (wikiprep)
	if type(per) == "table" and #per > 0 then
		for lv = 1, maxLevel do
			local raw = per[lv] or per[#per]
			local one = fmtAny(raw)
			if one == nil or isZeroish(raw) or isZeroish(one) then
				one = "—"
			end
			series[lv] = one
		end
		return series
	end

	-- Empty per-list -> base only
	if type(per) == "table" and #per == 0 then
		local one = fmtAny(base)
		if one == nil or isZeroish(base) or isZeroish(one) then
			one = "—"
		end
		for lv = 1, maxLevel do
			series[lv] = one
		end
		return series
	end

	-- Scalar per -> compute base + per*level (fallback)
	local baseN = toNum(base) or 0
	local perN  = toNum(per)

	if perN ~= nil then
		for lv = 1, maxLevel do
			local total = baseN + (perN * lv)
			local v = unit and { Value = total, Unit = unit } or total
			local one = fmtAny(v)
			if one == nil or total == 0 or isZeroish(one) then
				one = "—"
			end
			series[lv] = one
		end
		return series
	end

	-- Base-only scalar
	local raw = (base ~= nil) and base or per
	local one = fmtAny(raw)
	if one == nil then
		return nil
	end
	if isZeroish(raw) or isZeroish(one) then
		one = "—"
	end
	for lv = 1, maxLevel do
		series[lv] = one
	end
	return series
end

local function displayFromSeries(series, level)
	if type(series) ~= "table" or #series == 0 then
		return nil
	end

	local any = false
	for _, v in ipairs(series) do
		if v ~= "—" then
			any = true
			break
		end
	end
	if not any then
		return nil
	end

	if isFlatList(series) then
		return mw.text.nowiki(series[1])
	end
	return dynSpan(series, level)
end

local function formatAreaSize(area)
	if type(area) ~= "table" then
		return nil
	end

	local raw = area["Area Size"]
	if raw == nil then
		return nil
	end

	local name, num

	if type(raw) == "table" then
		name = raw.Name or raw.ID or raw.Value
		num  = raw.Value
		if raw.Name or raw.ID then
			name = raw.Name or raw.ID
		end
	elseif type(raw) == "string" then
		name = raw
	elseif type(raw) == "number" then
		num = raw
	end

	if num == nil then
		num = toNum(area["Area Value"]) or toNum(area["Area Size Value"]) or toNum(area["Area Number"]) or toNum(area["Area Radius"])
	end

	if name ~= nil then
		local s = mw.text.trim(tostring(name))
		if s == "" or isNoneLike(s) then
			return nil
		end
		if mw.ustring.find(s, "%(") then
			return mw.text.nowiki(s)
		end
		if num ~= nil and num ~= 0 then
			return mw.text.nowiki(string.format("%s (%s)", s, fmtNum(num)))
		end
		return mw.text.nowiki(s)
	end

	if num ~= nil and num ~= 0 then
		return mw.text.nowiki(string.format("(%s)", fmtNum(num)))
	end

	return nil
end

local function skillHasAnyDamage(rec, maxLevel)
	if type(rec.Source) == "table" then
		local s = seriesFromValuePair(rec.Source, maxLevel)
		if s then
			for _, v in ipairs(s) do
				if v ~= "—" then return true end
			end
		end
	end

	if type(rec.Damage) == "table" then
		local dmg = rec.Damage
		for _, key in ipairs({ "Main Damage", "Flat Damage", "Reflect Damage" }) do
			local lst = dmg[key]
			if type(lst) == "table" and #lst > 0 then
				return true
			end
		end
	end

	return false
end

local function computeDurationPromotion(rec, maxLevel)
	if type(rec) ~= "table" then return nil end
	if skillHasAnyDamage(rec, maxLevel) then return nil end

	local mech = (type(rec.Mechanics) == "table") and rec.Mechanics or {}
	local bt   = (type(mech["Basic Timings"]) == "table") and mech["Basic Timings"] or {}
	local durS = seriesFromValuePair(bt["Duration"], maxLevel)

	if durS ~= nil then
		local any = false
		for _, v in ipairs(durS) do
			if v ~= "—" then any = true break end
		end
		if any then
			return nil
		end
	end

	local apps = rec["Status Applications"]
	if type(apps) ~= "table" then return nil end

	for idx, app in ipairs(apps) do
		if type(app) == "table" and type(app.Duration) == "table" then
			local s = seriesFromValuePair(app.Duration, maxLevel)
			if s then
				for _, v in ipairs(s) do
					if v ~= "—" then
						return {
							durationBlock = app.Duration,
							suppressDurationIndex = idx,
						}
					end
				end
			end
		end
	end

	return nil
end

----------------------------------------------------------------------
-- Plug-ins
----------------------------------------------------------------------

local PLUGINS = {}

-- Hero Bar Slot 1: Icon + Name
function PLUGINS.IconName(rec, ctx)
	local icon  = rec.Icon
	local title = rec["External Name"] or rec.Name or rec["Internal Name"] or "Unknown Skill"

	local wrap = mw.html.create("div")
	wrap:addClass("sv-herobar-1-wrap")

	if icon and icon ~= "" then
		wrap:tag("div")
			:addClass("sv-herobar-icon")
			:wikitext(string.format("[[File:%s|80px|link=]]", icon))
	end

	wrap:tag("div")
		:addClass("spiritvale-infobox-title")
		:wikitext(title)

	return {
		inner = tostring(wrap),
		classes = "module-herobar-1",
	}
end

-- Reserved placeholder (kept for future)
function PLUGINS.ReservedInfo(rec, ctx)
	local wrap = mw.html.create("div")
	wrap:addClass("sv-herobar-2-wrap")
	return {
		inner = tostring(wrap),
		classes = "module-herobar-2",
	}
end

-- Module: Level Selector
function PLUGINS.LevelSelector(rec, ctx)
	local level = ctx.level or 1
	local maxLevel = ctx.maxLevel or 1

	local inner = mw.html.create("div")
	inner:addClass("sv-level-ui")

	inner:tag("div")
		:addClass("sv-level-label")
		:wikitext("Level <span class=\"sv-level-num\">" .. tostring(level) .. "</span> / " .. tostring(maxLevel))

	local slider = inner:tag("div"):addClass("sv-level-slider")

	if tonumber(maxLevel) and tonumber(maxLevel) > 1 then
		slider:tag("input")
			:attr("type", "range")
			:attr("min", "1")
			:attr("max", tostring(maxLevel))
			:attr("value", tostring(level))
			:addClass("sv-level-range")
			:attr("aria-label", "Skill level select")
	else
		inner:addClass("sv-level-ui-single")
		slider:addClass("sv-level-slider-single")
	end

	return {
		inner = tostring(inner),
		classes = "module-level-selector",
	}
end

-- Module: Skill Type
function PLUGINS.SkillType(rec, ctx)
	local typeBlock = (type(rec.Type) == "table") and rec.Type or {}
	local hideDamageAndElement = (ctx.nonDamaging == true)

	local function valName(x)
		if x == nil then return nil end
		if type(x) == "table" then
			if x.Name and x.Name ~= "" then return tostring(x.Name) end
			if x.ID and x.ID ~= "" then return tostring(x.ID) end
			if x.Value ~= nil then return tostring(x.Value) end
		end
		if type(x) == "string" and x ~= "" then
			return x
		end
		return nil
	end

	local grid = mw.html.create("div")
	grid:addClass("sv-type-grid")
	grid:addClass("sv-compact-root")

	local added = false
	local function addChunk(label, rawVal)
		local v = valName(rawVal)
		if not v or v == "" then return end
		added = true

		local chunk = grid:tag("div"):addClass("sv-type-chunk")
		chunk:tag("div"):addClass("sv-type-label"):wikitext(mw.text.nowiki(label))
		chunk:tag("div"):addClass("sv-type-value"):wikitext(mw.text.nowiki(v))
	end

	if not hideDamageAndElement then
		addChunk("Damage",  typeBlock.Damage  or typeBlock["Damage Type"])
		addChunk("Element", typeBlock.Element or typeBlock["Element Type"])
	end

	addChunk("Target", typeBlock.Target or typeBlock["Target Type"])
	addChunk("Cast",   typeBlock.Cast   or typeBlock["Cast Type"])

	return {
		inner = added and tostring(grid) or "",
		classes = "module-skill-type",
	}
end

-- Module: SourceType (Modifier + Source + Scaling)
function PLUGINS.SourceType(rec, ctx)
	local level = ctx.level or 1
	local maxLevel = ctx.maxLevel or 1

	local basisWord = nil
	local sourceKind = nil
	local sourceVal  = nil
	local scaling    = nil

	local function sourceValueForLevel(src)
		if type(src) ~= "table" then
			return nil
		end

		local per = src["Per Level"]
		if type(per) == "table" and #per > 0 then
			if isFlatList(per) then
				local one  = formatUnitValue(per[1]) or tostring(per[1])
				local show = formatUnitValue(src.Base) or one
				return show and mw.text.nowiki(show) or nil
			end

			local series = {}
			for _, v in ipairs(per) do
				table.insert(series, formatUnitValue(v) or tostring(v))
			end
			return dynSpan(series, level)
		end

		return valuePairDynamicValueOnly(src, maxLevel, level)
	end

	if type(rec.Source) == "table" then
		local src = rec.Source
		local atkFlag  = (src["ATK-Based"] == true)
		local matkFlag = (src["MATK-Based"] == true)
		basisWord = basisWordFromFlags(atkFlag, matkFlag)

		sourceKind = src.Type or ((src.Healing == true) and "Healing") or "Damage"
		sourceVal  = sourceValueForLevel(src)
		scaling    = src.Scaling
	end

	-- Fallback to legacy Damage lists if Source absent
	if (sourceVal == nil or sourceVal == "") and type(rec.Damage) == "table" then
		local dmg = rec.Damage
		scaling = scaling or dmg.Scaling

		local main = dmg["Main Damage"]
		local refl = dmg["Reflect Damage"]
		local flat = dmg["Flat Damage"]

		if type(main) == "table" and #main > 0 then
			local pick = nil
			for _, d in ipairs(main) do
				if type(d) == "table" and d.Type ~= "Healing" then
					pick = d
					break
				end
			end
			pick = pick or main[1]

			if type(pick) == "table" then
				local atkFlag  = (pick["ATK-Based"] == true)
				local matkFlag = (pick["MATK-Based"] == true)
				basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)

				sourceKind = (pick.Type == "Healing") and "Healing" or "Damage"
				sourceVal  = legacyPercentAtLevel(pick, level)
			end
		elseif type(refl) == "table" and #refl > 0 and type(refl[1]) == "table" then
			local pick = refl[1]
			local atkFlag  = (pick["ATK-Based"] == true)
			local matkFlag = (pick["MATK-Based"] == true)
			basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)

			sourceKind = "Reflect"
			sourceVal  = legacyPercentAtLevel(pick, level)
		elseif type(flat) == "table" and #flat > 0 and type(flat[1]) == "table" then
			local pick = flat[1]
			local atkFlag  = (pick["ATK-Based"] == true)
			local matkFlag = (pick["MATK-Based"] == true)
			basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)

			sourceKind = "Flat"
			sourceVal  = legacyPercentAtLevel(pick, level)
		end
	end

	local scalingLines = formatScalingCompactLines(scaling)
	local hasSource    = (sourceVal ~= nil and tostring(sourceVal) ~= "")
	local hasScaling   = (type(scalingLines) == "table" and #scalingLines > 0)

	if (not hasSource) and (not hasScaling) then
		return nil
	end

	local hasMod = (basisWord ~= nil and tostring(basisWord) ~= "")

	local extra = { "skill-source-module" }
	table.insert(extra, hasMod and "sv-has-mod" or "sv-no-mod")

	if hasSource and (not hasScaling) then
		table.insert(extra, "sv-only-source")
	elseif hasScaling and (not hasSource) then
		table.insert(extra, "sv-only-scaling")
	end

	local wrap = mw.html.create("div")
	wrap:addClass("sv-source-grid")
	wrap:addClass("sv-compact-root")

	if hasMod then
		local modCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-modifier")
		modCol:tag("div"):addClass("sv-source-pill"):wikitext("Modifier")
		modCol:tag("div"):addClass("sv-modifier-value"):wikitext(mw.text.nowiki(basisWord))
	end

	if hasSource then
		local sourceCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-main")
		sourceCol:tag("div"):addClass("sv-source-pill"):wikitext(mw.text.nowiki(sourceKind or "Source"))
		sourceCol:tag("div"):addClass("sv-source-value"):wikitext(sourceVal)
	end

	if hasScaling then
		local scalingCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-scaling")
		scalingCol:tag("div"):addClass("sv-source-pill"):wikitext("Scaling")

		local list = scalingCol:tag("div"):addClass("sv-scaling-list")
		for _, line in ipairs(scalingLines) do
			list:tag("div"):addClass("sv-scaling-item"):wikitext(mw.text.nowiki(line))
		end
	end

	return {
		inner = tostring(wrap),
		classes = extra,
	}
end

-- Module: Quick Stats (3x2)
function PLUGINS.QuickStats(rec, ctx)
	local level = ctx.level or 1
	local maxLevel = ctx.maxLevel or 1
	local promo = ctx.promo

	local mech = (type(rec) == "table" and type(rec.Mechanics) == "table") and rec.Mechanics or {}
	local bt   = (type(mech["Basic Timings"]) == "table") and mech["Basic Timings"] or {}
	local rc   = (type(mech["Resource Cost"]) == "table") and mech["Resource Cost"] or {}

	local function dash() return "—" end

	-- Range (0 => —)
	local rangeVal = nil
	if mech.Range ~= nil and not isNoneLike(mech.Range) then
		local n = toNum(mech.Range)
		if n ~= nil then
			if n ~= 0 then
				rangeVal = mw.text.nowiki(formatUnitValue(mech.Range) or tostring(mech.Range))
			end
		else
			local t = mw.text.trim(tostring(mech.Range))
			if t ~= "" and not isNoneLike(t) then
				rangeVal = mw.text.nowiki(t)
			end
		end
	end

	-- Area
	local areaVal = formatAreaSize(mech.Area)

	-- Timings
	local castVal = displayFromSeries(seriesFromValuePair(bt["Cast Time"], maxLevel), level)
	local cdVal   = displayFromSeries(seriesFromValuePair(bt["Cooldown"],  maxLevel), level)
	local durVal  = displayFromSeries(seriesFromValuePair(bt["Duration"],  maxLevel), level)

	-- Promote status duration if needed
	if (durVal == nil) and type(promo) == "table" and type(promo.durationBlock) == "table" then
		durVal = displayFromSeries(seriesFromValuePair(promo.durationBlock, maxLevel), level)
	end

	-- Cost: MP + HP
	local function labeledSeries(block, label)
		local s = seriesFromValuePair(block, maxLevel)
		if not s then return nil end
		local any = false
		for i, v in ipairs(s) do
			if v ~= "—" then
				s[i] = tostring(v) .. " " .. label
				any = true
			else
				s[i] = "—"
			end
		end
		return any and s or nil
	end

	local mpS = labeledSeries(rc["Mana Cost"], "MP")
	local hpS = labeledSeries(rc["Health Cost"], "HP")

	local costSeries = {}
	for lv = 1, maxLevel do
		local mp = mpS and mpS[lv] or "—"
		local hp = hpS and hpS[lv] or "—"

		if mp ~= "—" and hp ~= "—" then
			costSeries[lv] = mp .. " + " .. hp
		elseif mp ~= "—" then
			costSeries[lv] = mp
		elseif hp ~= "—" then
			costSeries[lv] = hp
		else
			costSeries[lv] = "—"
		end
	end

	local costVal = displayFromSeries(costSeries, level)

	local grid = mw.html.create("div")
	grid:addClass("sv-m4-grid")
	grid:addClass("sv-compact-root")

	local function addCell(label, val)
		local cell = grid:tag("div"):addClass("sv-m4-cell")
		cell:tag("div"):addClass("sv-m4-label"):wikitext(mw.text.nowiki(label))
		cell:tag("div"):addClass("sv-m4-value"):wikitext(val or dash())
	end

	addCell("Range",     rangeVal)
	addCell("Area",      areaVal)
	addCell("Cost",      costVal)
	addCell("Cast Time", castVal)
	addCell("Cooldown",  cdVal)
	addCell("Duration",  durVal)

	return {
		inner = tostring(grid),
		classes = "module-quick-stats",
	}
end

-- Module: Special Mechanics (Special Mechanics + Flags + Combo)
function PLUGINS.SpecialMechanics(rec, ctx)
	local level = ctx.level or 1
	local maxLevel = ctx.maxLevel or 1

	local mech = (type(rec) == "table" and type(rec.Mechanics) == "table") and rec.Mechanics or {}
	local effects = (type(mech.Effects) == "table") and mech.Effects or nil
	local combo   = (type(mech.Combo) == "table") and mech.Combo or nil
	local mods    = (type(rec.Modifiers) == "table") and rec.Modifiers or nil

	-- Collect flags as a flat, de-duped set
	local flagSet = {}

	local function addFlags(sub)
		if type(sub) ~= "table" then return end
		for k, v in pairs(sub) do
			if v then
				flagSet[tostring(k)] = true
			end
		end
	end

	if mods then
		addFlags(mods["Movement Modifiers"])
		addFlags(mods["Combat Modifiers"])
		addFlags(mods["Special Modifiers"])
		for k, v in pairs(mods) do
			if type(v) == "boolean" and v then
				flagSet[tostring(k)] = true
			end
		end
	end

	local flags = {}
	for k, _ in pairs(flagSet) do table.insert(flags, k) end
	table.sort(flags)

	-- Collect special mechanics into (label,value) items
	local items = {}

	if effects then
		local keys = {}
		for k, _ in pairs(effects) do table.insert(keys, k) end
		table.sort(keys)

		for _, name in ipairs(keys) do
			local block = effects[name]
			if type(block) == "table" then
				local disp = displayFromSeries(seriesFromValuePair(block, maxLevel), level)
				local t = trim(block.Type)

				local parts = {}
				if t and not isNoneLike(t) and mw.ustring.lower(t) ~= mw.ustring.lower(tostring(name)) then
					table.insert(parts, mw.text.nowiki(t))
				end
				if disp then
					table.insert(parts, disp)
				end

				local value = nil
				if #parts == 1 then
					value = parts[1]
				elseif #parts >= 2 then
					value = parts[1] .. ": " .. parts[2]
				end

				if value then
					table.insert(items, { label = tostring(name), value = value })
				end
			end
		end
	end

	-- Combo (append last)
	if combo then
		local typ = trim(combo.Type)
		if typ and not isNoneLike(typ) then
			local details = {}

			local pct = formatUnitValue(combo.Percent)
			if pct and not isZeroish(pct) then
				table.insert(details, mw.text.nowiki(pct))
			end

			local dur = formatUnitValue(combo.Duration)
			if dur and not isZeroish(dur) then
				table.insert(details, mw.text.nowiki(dur))
			end

			local comboText
			if #details > 0 then
				comboText = mw.text.nowiki(typ) .. " (" .. table.concat(details, ", ") .. ")"
			else
				comboText = mw.text.nowiki(typ)
			end

			table.insert(items, { label = "Combo", value = comboText })
		end
	end

	local hasAny = (#flags > 0) or (#items > 0)

	local root = mw.html.create("div")
	root:addClass("sv-sm-root")
	root:addClass("sv-compact-root")

	if not hasAny then
		root:tag("div")
			:addClass("sv-sm-empty")
			:wikitext("No Special Mechanics")
		return {
			inner = tostring(root),
			classes = "module-special-mechanics",
		}
	end

	local layout = root:tag("div"):addClass("sv-sm-layout")
	if #flags > 0 then
		layout:addClass("sv-sm-has-flags")
		local fcol = layout:tag("div"):addClass("sv-sm-flags")
		for _, f in ipairs(flags) do
			fcol:tag("div"):addClass("sv-sm-flag"):wikitext(mw.text.nowiki(f))
		end
	end

	local wrap = layout:tag("div"):addClass("sv-sm-items")
	for _, it in ipairs(items) do
		local one = wrap:tag("div"):addClass("sv-sm-item")
		one:tag("div"):addClass("sv-sm-label"):wikitext(mw.text.nowiki(it.label))
		one:tag("div"):addClass("sv-sm-value"):wikitext(it.value or "—")
	end

	return {
		inner = tostring(root),
		classes = "module-special-mechanics",
	}
end

----------------------------------------------------------------------
-- Generic slot renderers
----------------------------------------------------------------------

local function normalizeResult(res)
	if res == nil then return nil end
	if type(res) == "string" then
		return { inner = res, classes = nil }
	end
	if type(res) == "table" then
		local inner = res.inner
		if type(inner) ~= "string" then
			inner = (inner ~= nil) and tostring(inner) or ""
		end
		return { inner = inner, classes = res.classes }
	end
	return { inner = tostring(res), classes = nil }
end

local function safeCallPlugin(name, rec, ctx)
	local fn = PLUGINS[name]
	if type(fn) ~= "function" then
		return nil
	end
	local ok, out = pcall(fn, rec, ctx)
	if not ok then
		return nil
	end
	return normalizeResult(out)
end

local function renderHeroBarSlot(slotIndex, rec, ctx)
	local pluginName = HERO_BAR_SLOT_ASSIGNMENT[slotIndex]
	if not pluginName then
		return heroBarBox(slotIndex, nil, "", true)
	end

	local res = safeCallPlugin(pluginName, rec, ctx)
	if not res or not res.inner or res.inner == "" then
		return heroBarBox(slotIndex, nil, "", true)
	end

	return heroBarBox(slotIndex, res.classes, res.inner, false)
end

local function renderModuleSlot(slotIndex, rec, ctx)
	local pluginName = HERO_MODULE_SLOT_ASSIGNMENT[slotIndex]
	if not pluginName then
		return moduleBox(slotIndex, nil, "", true)
	end

	local res = safeCallPlugin(pluginName, rec, ctx)
	if not res or not res.inner or res.inner == "" then
		return moduleBox(slotIndex, nil, "", true)
	end

	return moduleBox(slotIndex, res.classes, res.inner, false)
end

----------------------------------------------------------------------
-- UI builders
----------------------------------------------------------------------

local function buildHeroBarUI(rec, ctx)
	local bar = mw.html.create("div")
	bar:addClass("hero-bar-grid")
	bar:wikitext(renderHeroBarSlot(1, rec, ctx))
	bar:wikitext(renderHeroBarSlot(2, rec, ctx))
	return tostring(bar)
end

local function buildHeroModulesUI(rec, ctx)
	local grid = mw.html.create("div")
	grid:addClass("hero-modules-grid")
	for slot = 1, 4 do
		grid:wikitext(renderModuleSlot(slot, rec, ctx))
	end
	return tostring(grid)
end

local function addHeroModulesRow(tbl, modulesUI)
	if not modulesUI or modulesUI == "" then
		return
	end

	local row = tbl:tag("tr")
	row:addClass("hero-modules-row")

	local cell = row:tag("td")
	cell:attr("colspan", 2)
	cell:addClass("hero-modules-cell")
	cell:wikitext(modulesUI)
end

----------------------------------------------------------------------
-- Infobox builder
----------------------------------------------------------------------

local function buildInfobox(rec, opts)
	opts = opts or {}
	local showUsers = (opts.showUsers ~= false)

	local maxLevel = tonumber(rec["Max Level"]) or 1
	if maxLevel < 1 then maxLevel = 1 end
	local level = clamp(maxLevel, 1, maxLevel)

	local ctx = {
		maxLevel = maxLevel,
		level = level,
		nonDamaging = false,
		promo = nil,
	}

	-- Non-damaging hides Damage/Element in SkillType
	do
		local dmgVal = nil
		if type(rec.Type) == "table" then
			dmgVal = rec.Type.Damage or rec.Type["Damage Type"]
			if type(dmgVal) == "table" then
				dmgVal = dmgVal.Name or dmgVal.ID or dmgVal.Value
			end
		end
		ctx.nonDamaging = isNoneLike(dmgVal) or (not skillHasAnyDamage(rec, maxLevel))
	end

	ctx.promo = computeDurationPromotion(rec, maxLevel)

	local root = mw.html.create("table")
	root:addClass("spiritvale-skill-infobox")
	root:addClass("sv-skill-card")
	root:attr("data-max-level", tostring(maxLevel))
	root:attr("data-level", tostring(level))

	if opts.inList then
		root:addClass("sv-skill-inlist")
	end

	local internalId = trim(rec["Internal Name"] or rec.InternalID or rec.ID)
	if internalId then
		root:attr("data-skill-id", internalId)
	end

	local desc  = rec.Description or ""

	-- Hero Title Bar
	local heroRow = root:tag("tr")
	heroRow:addClass("spiritvale-infobox-main")
	heroRow:addClass("sv-hero-title-row")
	heroRow:addClass("hero-title-bar")

	local heroCell = heroRow:tag("th")
	heroCell:attr("colspan", 2)
	heroCell:addClass("sv-hero-title-cell")
	heroCell:wikitext(buildHeroBarUI(rec, ctx))

	-- Description Bar
	if desc ~= "" then
		local descRow = root:tag("tr")
		descRow:addClass("spiritvale-infobox-main")
		descRow:addClass("sv-hero-desc-row")
		descRow:addClass("hero-description-bar")

		local descCell = descRow:tag("td")
		descCell:attr("colspan", 2)
		descCell:addClass("sv-hero-desc-cell")

		local descInner = descCell:tag("div")
		descInner:addClass("spiritvale-infobox-main-right-inner")

		descInner:tag("div")
			:addClass("spiritvale-infobox-description")
			:wikitext(string.format("''%s''", desc))
	end

	-- Modules row
	addHeroModulesRow(root, buildHeroModulesUI(rec, ctx))

	-- Users (hide on direct skill page)
	if showUsers then
		local users = rec.Users or {}
		addRow(root, "Classes",  listToText(users.Classes),  "sv-row-users", "Users.Classes")
		addRow(root, "Summons",  listToText(users.Summons),  "sv-row-users", "Users.Summons")
		addRow(root, "Monsters", listToText(users.Monsters), "sv-row-users", "Users.Monsters")
		addRow(root, "Events",   listToText(users.Events),   "sv-row-users", "Users.Events")
	end

	-- Requirements
	local req = rec.Requirements or {}
	local hasReq =
		(type(req["Required Skills"]) == "table" and #req["Required Skills"] > 0) or
		(type(req["Required Weapons"]) == "table" and #req["Required Weapons"] > 0) or
		(type(req["Required Stances"]) == "table" and #req["Required Stances"] > 0)

	if hasReq then
		if type(req["Required Skills"]) == "table" and #req["Required Skills"] > 0 then
			local skillParts = {}
			for _, rs in ipairs(req["Required Skills"]) do
				local nameReq = rs["Skill External Name"] or rs["Skill Internal Name"] or "Unknown"
				local lvlReq  = rs["Required Level"]
				if lvlReq then
					table.insert(skillParts, string.format("%s (Lv.%s)", nameReq, lvlReq))
				else
					table.insert(skillParts, nameReq)
				end
			end
			addRow(root, "Required Skills", table.concat(skillParts, ", "), "sv-row-req", "Requirements.Required Skills")
		end

		addRow(root, "Required Weapons", listToText(req["Required Weapons"]), "sv-row-req", "Requirements.Required Weapons")
		addRow(root, "Required Stances", listToText(req["Required Stances"]), "sv-row-req", "Requirements.Required Stances")
	end

	-- Mechanics (keep small extras only; Special Mechanics/Flags/Combo are now in the module)
	local mech = rec.Mechanics or {}
	if next(mech) ~= nil then
		if mech["Autocast Multiplier"] ~= nil then
			addRow(root, "Autocast Multiplier", tostring(mech["Autocast Multiplier"]), "sv-row-mech", "Mechanics.Autocast Multiplier")
		end
	end

	-- Legacy damage breakdown (only when Source absent)
	if type(rec.Source) ~= "table" then
		local dmg = rec.Damage or {}
		if next(dmg) ~= nil then
			local main = dmg["Main Damage"]
			local mainNonHeal, healOnly = {}, {}

			if type(main) == "table" then
				for _, d in ipairs(main) do
					if type(d) == "table" and d.Type == "Healing" then
						table.insert(healOnly, d)
					else
						table.insert(mainNonHeal, d)
					end
				end
			end

			addRow(root, "Main Damage",    formatDamageList(mainNonHeal, maxLevel, level, (#mainNonHeal > 1)), "sv-row-source", "Damage.Main Damage")
			addRow(root, "Flat Damage",    formatDamageList(dmg["Flat Damage"], maxLevel, level, false),        "sv-row-source", "Damage.Flat Damage")
			addRow(root, "Reflect Damage", formatDamageList(dmg["Reflect Damage"], maxLevel, level, false),     "sv-row-source", "Damage.Reflect Damage")
			addRow(root, "Healing",        formatDamageList(healOnly, maxLevel, level, false),                  "sv-row-source", "Damage.Healing")
		end
	end

	-- Status rows (unchanged)
	local function formatStatusApplications(list, suppressDurationIndex)
		if type(list) ~= "table" or #list == 0 then return nil end

		local parts = {}
		for idx, s in ipairs(list) do
			if type(s) == "table" then
				local typ  = s.Type or s.Scope or "Target"
				local name = s["Status External Name"] or s["Status Internal Name"] or "Unknown status"
				local seg = tostring(typ) .. " – " .. tostring(name)
				local detail = {}

				if idx ~= suppressDurationIndex and type(s.Duration) == "table" then
					local t = valuePairDynamicValueOnly(s.Duration, maxLevel, level)
					if t then table.insert(detail, "Duration: " .. t) end
				end

				if type(s.Chance) == "table" then
					local t = valuePairDynamicValueOnly(s.Chance, maxLevel, level)
					if t then table.insert(detail, "Chance: " .. t) end
				end

				if #detail > 0 then
					seg = seg .. " (" .. table.concat(detail, ", ") .. ")"
				end

				table.insert(parts, seg)
			end
		end

		return (#parts > 0) and table.concat(parts, "<br />") or nil
	end

	local function formatStatusRemoval(list)
		if type(list) ~= "table" or #list == 0 then return nil end

		local parts = {}
		for _, r in ipairs(list) do
			if type(r) == "table" then
				local names = r["Status External Name"]
				local label

				if type(names) == "table" then
					label = table.concat(names, ", ")
				elseif type(names) == "string" then
					label = names
				else
					label = "Status"
				end

				local amt = valuePairRawText(r)
				amt = amt and mw.text.nowiki(amt) or nil

				local seg = mw.text.nowiki(label)
				if amt then
					seg = seg .. " – " .. amt
				end
				table.insert(parts, seg)
			end
		end

		return (#parts > 0) and table.concat(parts, "<br />") or nil
	end

	local suppressIdx = (type(ctx.promo) == "table") and ctx.promo.suppressDurationIndex or nil
	local statusApps = formatStatusApplications(rec["Status Applications"], suppressIdx)
	local statusRem  = formatStatusRemoval(rec["Status Removal"])
	if statusApps or statusRem then
		addRow(root, "Applies", statusApps, "sv-row-status", "Status Applications")
		addRow(root, "Removes", statusRem,  "sv-row-status", "Status Removal")
	end

	-- Events
	local function formatEvents(list)
		if type(list) ~= "table" or #list == 0 then return nil end
		local parts = {}
		for _, ev in ipairs(list) do
			if type(ev) == "table" then
				local action = ev.Action or "On event"
				local name   = ev["Skill Internal Name"] or ev["Skill External Name"] or "Unknown skill"
				table.insert(parts, string.format("%s → %s", action, name))
			end
		end
		return (#parts > 0) and table.concat(parts, "<br />") or nil
	end

	local eventsText = formatEvents(rec.Events)
	if eventsText then
		addRow(root, "Triggers", eventsText, "sv-row-meta", "Events")
	end

	-- Notes
	if type(rec.Notes) == "table" and #rec.Notes > 0 then
		addRow(root, "Notes", table.concat(rec.Notes, "<br />"), "sv-row-meta", "Notes")
	end

	return tostring(root)
end

----------------------------------------------------------------------
-- Public: list all skills for a given user/class
----------------------------------------------------------------------

function p.listForUser(frame)
	local args = getArgs(frame)

	local userName = args.user or args[1]
	if not userName or userName == "" then
		userName = mw.title.getCurrentTitle().text
	end

	if not userName or userName == "" then
		return "<strong>No user name provided to Skill list.</strong>"
	end

	local dataset = getSkills()
	local matches = {}

	for _, rec in ipairs(dataset.records or {}) do
		if skillMatchesUser(rec, userName) then
			table.insert(matches, rec)
		end
	end

	if #matches == 0 then
		return string.format("<strong>No skills found for:</strong> %s", mw.text.nowiki(userName))
	end

	local root = mw.html.create("div")
	root:addClass("sv-skill-collection")

	for _, rec in ipairs(matches) do
		local item = root:tag("div"):addClass("sv-skill-item")
		item:wikitext(buildInfobox(rec, { showUsers = false, inList = true }))
	end

	return tostring(root)
end

----------------------------------------------------------------------
-- Public: single-skill or auto-list dispatcher
----------------------------------------------------------------------

function p.infobox(frame)
	local args = getArgs(frame)

	local raw1 = args[1]
	local name = args.name or raw1
	local id   = args.id

	local rec
	if name and name ~= "" then
		rec = findSkillByName(name)
	end
	if not rec and id and id ~= "" then
		rec = getSkillById(id)
	end

	if not rec then
		local pageTitle = mw.title.getCurrentTitle()
		local pageName  = pageTitle and pageTitle.text or ""

		local noExplicitArgs =
			(not raw1 or raw1 == "") and
			(not args.name or args.name == "") and
			(not id or id == "")

		if noExplicitArgs then
			return p.listForUser(frame)
		end

		if name and name ~= "" and name == pageName and (not id or id == "") then
			return p.listForUser(frame)
		end

		local label = name or id or "?"
		return string.format(
			"<strong>Unknown Skill:</strong> %s[[Category:Pages with unknown skill|%s]]",
			mw.text.nowiki(label),
			label
		)
	end

	local showUsers = not isDirectSkillPage(rec)
	return buildInfobox(rec, { showUsers = showUsers })
end

return p