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
 
(14 intermediate revisions by the same user not shown)
Line 1: Line 1:
-- Module:GameSkills
-- Module:GameSkills
--
--
-- Phase 6.5+ (Plug-in Slot Architecture + Context-Aware Rendering)
-- Phase 6.5+ (Plug-in Slot Architecture)
--
--
-- Standard Hero Layout:
-- Layout (Module 1–8):
--  1) hero-title-bar        (TOP BAR, 2 slots: herobar 1..2)
--  Row 1: Module 1 + Module 2   → Icon + Name, Skill Type strip
--  2) hero-description-bar  (description strip)
--  Row 2: Module 3 + Module 4  → Description (Module 3), open slot (Module 4)
--  3) hero-modules row      (4 slots: hero-module-1..4)
--  Row 3: Module 5 + Module 6  → Source Types, Quick Stats
--   Row 4: Module 7 + Module 8  → Special Mechanics, Level Selector
--
--
-- NEW: Plug-ins receive ctx:
-- Requires Common.js:
--  ctx.region = "herobar" | "modules"
--  - updates .sv-dyn spans via data-series
--  ctx.slot  = slot index within that region
--  - updates .sv-level-num + data-level on .sv-skill-card
--  ctx.level / ctx.maxLevel / ctx.nonDamaging / ctx.promo
--  - binds to input.sv-level-range inside each card


local GameData = require("Module:GameData")
local GameData = require("Module:GameData")
Line 23: Line 24:
local skillsCache
local skillsCache


-- getSkills: lazy-load + cache skill dataset from GameData.
local function getSkills()
local function getSkills()
if not skillsCache then
if not skillsCache then
Line 34: Line 36:
----------------------------------------------------------------------
----------------------------------------------------------------------


-- getArgs: read args from parent frame when invoked from a template.
local function getArgs(frame)
local function getArgs(frame)
local parent = frame:getParent()
local parent = frame:getParent()
Line 39: Line 42:
end
end


-- trim: normalize strings (nil if empty).
local function trim(s)
local function trim(s)
if type(s) ~= "string" then
if type(s) ~= "string" then
Line 47: Line 51:
end
end


-- toNum: convert common scalar/table forms to a Lua number.
local function toNum(v)
local function toNum(v)
if type(v) == "number" then
if type(v) == "number" then
Line 60: Line 65:
end
end


-- clamp: clamp a number into [lo, hi].
local function clamp(n, lo, hi)
local function clamp(n, lo, hi)
if type(n) ~= "number" then
if type(n) ~= "number" then
Line 69: Line 75:
end
end


-- fmtNum: consistent number formatting (trim trailing zeros).
local function fmtNum(n)
local function fmtNum(n)
if type(n) ~= "number" then
if type(n) ~= "number" then
Line 84: Line 91:
end
end


-- listToText: join an array into a readable string.
local function listToText(list, sep)
local function listToText(list, sep)
if type(list) ~= "table" or #list == 0 then
if type(list) ~= "table" or #list == 0 then
Line 91: Line 99:
end
end


-- isNoneLike: treat common "none" spellings as empty.
local function isNoneLike(v)
local function isNoneLike(v)
if v == nil then return true end
if v == nil then return true end
Line 99: Line 108:
end
end


local function ctxClone(base, extra)
-- addRow: add a standard <tr><th>Label</th><td>Value</td></tr> row.
local out = {}
if type(base) == "table" then
for k, v in pairs(base) do out[k] = v end
end
if type(extra) == "table" then
for k, v in pairs(extra) do out[k] = v end
end
return out
end
 
-- Add a labeled infobox row
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 118: Line 116:
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 129: Line 123:
end
end


-- Handles either a scalar OR { Value = ..., Unit = ... }
-- formatUnitValue: format {Value, Unit} blocks (or scalar) for display.
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 157: Line 151:
----------------------------------------------------------------------
----------------------------------------------------------------------


-- dynSpan: render a JS-updated span for a level series.
local function dynSpan(series, level)
local function dynSpan(series, level)
if type(series) ~= "table" or #series == 0 then
if type(series) ~= "table" or #series == 0 then
Line 172: Line 167:
end
end


-- isFlatList: true if all values in list are identical.
local function isFlatList(list)
local function isFlatList(list)
if type(list) ~= "table" or #list == 0 then
if type(list) ~= "table" or #list == 0 then
Line 185: Line 181:
end
end


-- isNonZeroScalar: detect if a value is present and not effectively zero.
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 205: Line 196:
end
end


-- isZeroish: aggressively treat common “zero” text forms as zero.
local function isZeroish(v)
local function isZeroish(v)
if v == nil then return true end
if v == nil then return true end
Line 211: Line 203:
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
Line 217: Line 210:
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
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:
-- valuePairRawText: render Base/Per Level blocks into readable text (fallback).
local function valuePairDynamicLines(name, block, maxLevel, level)
local function valuePairRawText(block)
if type(block) ~= "table" then
if type(block) ~= "table" then
return {}
return nil
end
end


Line 232: Line 226:
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


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)
-- valuePairDynamicValueOnly: render Base/Per Level blocks using dyn spans where possible.
local lines = valuePairDynamicLines(name, block, maxLevel, level)
local function valuePairDynamicValueOnly(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 281: Line 260:
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
-- getSkillById: locate a skill by internal ID.
local function getSkillById(id)
id = trim(id)
if not id then return nil end
local dataset = getSkills()
return (dataset.byId or {})[id]
end
end


local function valuePairDynamicValueOnly(block, maxLevel, level)
-- findSkillByName: locate a skill by external/display name.
if type(block) ~= "table" then
local function findSkillByName(name)
return nil
name = trim(name)
end
if not name then 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)
-- basisLabel: label ATK/MATK basis in legacy damage blocks.
id = trim(id)
local function basisLabel(entry, isHealing)
if not id then
if isHealing then
return nil
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
end
local dataset = getSkills()
 
return (dataset.byId or {})[id]
return "Damage"
end
end


local function findSkillByName(name)
-- formatDamageEntry: legacy percent damage formatting (dynamic by level).
name = trim(name)
local function formatDamageEntry(entry, maxLevel, level)
if not name then
if type(entry) ~= "table" then
return nil
return nil
end
end


local dataset = getSkills()
local isHealing = (entry.Type == "Healing")
local byName = dataset.byName or {}
local basis = isHealing and "Healing" or basisLabel(entry, false)
 
local baseRaw = entry["Base %"]
local perRaw  = entry["Per Level %"]


if byName[name] then
local baseN = toNum(baseRaw)
return byName[name]
local perN  = toNum(perRaw)
end


for _, rec in ipairs(dataset.records or {}) do
local function baseIsPresent()
if type(rec) == "table" then
if baseN ~= nil then
if rec["External Name"] == name or rec.Name == name or rec["Display Name"] == name then
return baseN ~= 0
return rec
end
end
if baseRaw ~= nil then
local s = tostring(baseRaw)
return (s ~= "" and s ~= "0" and s ~= "0.0" and s ~= "0.00")
end
end
return false
end
end


return nil
local baseText
end
if baseIsPresent() then
 
baseText = (baseN ~= nil) and (fmtNum(baseN) .. "%") or (tostring(baseRaw) .. "%")
----------------------------------------------------------------------
-- Formatting helpers
----------------------------------------------------------------------
 
local function basisLabel(entry, isHealing)
if isHealing then
return "Healing"
end
end


local atk  = entry and entry["ATK-Based"]
if perN == nil or perN == 0 or not maxLevel or maxLevel <= 0 then
local matk = entry and entry["MATK-Based"]
return baseText and mw.text.nowiki(baseText .. " " .. basis) or nil
 
if atk and matk then
return "Attack/Magic Attack"
elseif atk then
return "Attack"
elseif matk then
return "Magic Attack"
end
end


return "Damage"
local series = {}
end
for lv = 1, maxLevel do
local perPart = perN * lv


local function formatDamageEntry(entry, maxLevel, level)
if baseText and baseN ~= nil then
if type(entry) ~= "table" then
local total = baseN + perPart
return nil
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
end


local isHealing = (entry.Type == "Healing")
return dynSpan(series, level)
local basis = isHealing and "Healing" or basisLabel(entry, false)
end


local baseRaw = entry["Base %"]
-- formatDamageList: render a list of legacy damage entries into <br/> blocks.
local perRaw  = entry["Per Level %"]
local function formatDamageList(list, maxLevel, level, includeTypePrefix)
if type(list) ~= "table" or #list == 0 then
return nil
end


local baseN = toNum(baseRaw)
local parts = {}
local perN  = toNum(perRaw)
for _, d in ipairs(list) do
 
if type(d) == "table" then
local function baseIsPresent()
local txt = formatDamageEntry(d, maxLevel, level)
if baseN ~= nil then
if txt then
return baseN ~= 0
if includeTypePrefix and d.Type and d.Type ~= "" then
end
table.insert(parts, mw.text.nowiki(tostring(d.Type) .. ": ") .. txt)
if baseRaw ~= nil then
else
local s = tostring(baseRaw)
table.insert(parts, txt)
return (s ~= "" and s ~= "0" and s ~= "0.0" and s ~= "0.00")
end
end
end
end
return false
end
end


local baseText
return (#parts > 0) and table.concat(parts, "<br />") or nil
if baseIsPresent() then
end
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
-- Users matching
----------------------------------------------------------------------
 
-- skillMatchesUser: check if a skill is used by a specific class/monster/summon/event.
local function skillMatchesUser(rec, userName)
if type(rec) ~= "table" or not userName or userName == "" then
return false
end
end


local series = {}
local users = rec.Users
for lv = 1, maxLevel do
if type(users) ~= "table" then
local perPart = perN * lv
return false
 
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
end


return dynSpan(series, level)
local userLower = mw.ustring.lower(userName)
end


local function formatDamageList(list, maxLevel, level, includeTypePrefix)
local function listHas(list)
if type(list) ~= "table" or #list == 0 then
if type(list) ~= "table" then
return nil
return false
end
end
 
for _, v in ipairs(list) do
local parts = {}
if type(v) == "string" and mw.ustring.lower(v) == userLower then
for _, d in ipairs(list) do
return true
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
end
return false
end
end


return (#parts > 0) and table.concat(parts, "<br />") or nil
return listHas(users.Classes) or listHas(users.Summons) or listHas(users.Monsters) or listHas(users.Events)
end
end


local function formatCombo(combo)
----------------------------------------------------------------------
if type(combo) ~= "table" then
-- Hide Users on direct skill pages
return nil
----------------------------------------------------------------------
end


local parts = {}
-- isDirectSkillPage: hide Users rows when viewing the skill page itself.
local function isDirectSkillPage(rec)
if type(rec) ~= "table" then
return false
end


if combo.Type then
local pageTitle = mw.title.getCurrentTitle()
table.insert(parts, "Type: " .. mw.text.nowiki(tostring(combo.Type)))
local pageName  = pageTitle and pageTitle.text or ""
pageName = trim(pageName)
if not pageName then
return false
end
end


local durText = formatUnitValue(combo.Duration)
pageName = mw.ustring.lower(pageName)
if durText then
table.insert(parts, "Duration: " .. mw.text.nowiki(durText))
end


if combo.Percent ~= nil then
local ext = trim(rec["External Name"] or rec.Name or rec["Display Name"])
local pctText = formatUnitValue(combo.Percent)
local internal = trim(rec["Internal Name"] or rec.InternalName or rec.InternalID)
if pctText then
table.insert(parts, "Bonus: " .. mw.text.nowiki(pctText))
end
end


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


local function formatMechanicEffects(effects, maxLevel, level)
----------------------------------------------------------------------
if type(effects) ~= "table" then
-- Slot config (edit these tables only to rearrange layout)
return nil
----------------------------------------------------------------------
end


local keys = {}
-- Module row order (see layout notes above).
for k, _ in pairs(effects) do
local MODULE_SLOT_ASSIGNMENT = {
table.insert(keys, k)
        [1] = "IconName",
end
        [2] = "SkillType", -- Damage/Element/Hits/Target/Cast/Combo strip
table.sort(keys)
        [3] = "Description",
        [4] = nil, -- placeholder / intentionally open
        [5] = "SourceType",
        [6] = "QuickStats",
        [7] = "SpecialMechanics",
        [8] = "LevelSelector",
}


local parts = {}
local MODULE_GRID_PAIRS = {
        { 3, 4 },
        { 5, 6 },
        { 7, 8 },
}


local function effectAmount(block)
----------------------------------------------------------------------
if type(block) ~= "table" then
-- Slot scaffolds
return nil
----------------------------------------------------------------------
end


local per = block["Per Level"]
-- heroBarBox: wrapper for hero-bar slot modules.
if type(per) == "table" and #per > 0 then
local function heroBarBox(slot, extraClasses, innerHtml, isEmpty)
if isFlatList(per) then
        local box = mw.html.create("div")
return mw.text.nowiki(formatUnitValue(per[1]) or tostring(per[1]))
        box:addClass("hero-bar-module")
end
        box:addClass("hero-bar-module-" .. tostring(slot))
local series = {}
        box:addClass("sv-module-slot")
for _, v in ipairs(per) do
        box:addClass("sv-module-slot-" .. tostring(slot))
table.insert(series, formatUnitValue(v) or tostring(v))
        box:attr("data-hero-bar-module", tostring(slot))
end
        box:attr("data-module-slot", tostring(slot))
return dynSpan(series, level)
end


local txt = valuePairRawText(block)
if slot == 2 then
return txt and mw.text.nowiki(txt) or nil
box:addClass("sv-herobar-compact")
end
end


for _, name in ipairs(keys) do
if extraClasses then
local block = effects[name]
if type(extraClasses) == "string" then
if type(block) == "table" then
box:addClass(extraClasses)
local t = block.Type
elseif type(extraClasses) == "table" then
 
for _, c in ipairs(extraClasses) do box:addClass(c) end
if t ~= nil and tostring(t) ~= "" then
local amt = effectAmount(block)
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
end
end


return (#parts > 0) and table.concat(parts, "<br />") or nil
if isEmpty then
end
box:addClass("hero-bar-module-empty")
end


local function formatModifiers(mods)
local body = box:tag("div"):addClass("hero-bar-module-body")
if type(mods) ~= "table" then
if innerHtml and innerHtml ~= "" then
return nil
body:wikitext(innerHtml)
end
end


local parts = {}
return tostring(box)
end


local function collect(label, sub)
-- moduleBox: wrapper for hero-module (2x2 grid) slot modules.
if type(sub) ~= "table" then
local function moduleBox(slot, extraClasses, innerHtml, isEmpty)
return
        local box = mw.html.create("div")
end
        box:addClass("hero-module")
        box:addClass("hero-module-" .. tostring(slot))
        box:addClass("sv-module-slot")
        box:addClass("sv-module-slot-" .. tostring(slot))
        box:attr("data-hero-module", tostring(slot))
        box:attr("data-module-slot", tostring(slot))


local flags = {}
if extraClasses then
for k, v in pairs(sub) do
if type(extraClasses) == "string" then
if v then
box:addClass(extraClasses)
table.insert(flags, k)
elseif type(extraClasses) == "table" then
end
for _, c in ipairs(extraClasses) do box:addClass(c) end
end
end
table.sort(flags)
end


if #flags > 0 then
if isEmpty then
table.insert(parts, string.format("%s: %s", label, table.concat(flags, ", ")))
box:addClass("hero-module-empty")
end
end
end


collect("Movement", mods["Movement Modifiers"])
local body = box:tag("div"):addClass("hero-module-body")
collect("Combat",  mods["Combat Modifiers"])
if innerHtml and innerHtml ~= "" then
collect("Special",  mods["Special Modifiers"])
body:wikitext(innerHtml)
end


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


local function formatStatusApplications(list, maxLevel, level, suppressDurationIndex)
----------------------------------------------------------------------
if type(list) ~= "table" or #list == 0 then
-- Shared helpers (Source + QuickStats + SpecialMechanics)
return nil
----------------------------------------------------------------------
 
-- formatScalingCompactLines: build compact “Scaling” lines for SourceType.
local function formatScalingCompactLines(scaling)
if type(scaling) ~= "table" then
return {}
end
end


local parts = {}
local list = scaling
for idx, s in ipairs(list) do
if #list == 0 then
if type(s) == "table" then
if scaling.Percent ~= nil or scaling["Scaling ID"] or scaling["Scaling Name"] then
local typ  = s.Type or s.Scope or "Target"
list = { scaling }
local name = s["Status External Name"] or s["Status Internal Name"] or "Unknown status"
else
 
return {}
local seg = tostring(typ) .. " – " .. tostring(name)
local detail = {}
 
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
end


return (#parts > 0) and table.concat(parts, "<br />") or nil
local out = {}
end
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)


local function formatStatusRemoval(list, maxLevel, level)
if pctN ~= nil and pctN ~= 0 then
if type(list) ~= "table" or #list == 0 then
table.insert(out, string.format("%s%% %s", fmtNum(pctN), stat))
return nil
elseif pct ~= nil and tostring(pct) ~= "" and tostring(pct) ~= "0" then
end
table.insert(out, string.format("%s%% %s", tostring(pct), stat))
 
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
end
local amt
if type(r["Per Level"]) == "table" and #r["Per Level"] > 0 and not isFlatList(r["Per Level"]) then
local series = {}
for _, v in ipairs(r["Per Level"]) do
table.insert(series, formatUnitValue(v) or tostring(v))
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
end


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


local function formatEvents(list)
-- basisWordFromFlags: compute “Attack/Magic/Hybrid” from ATK/MATK booleans.
if type(list) ~= "table" or #list == 0 then
local function basisWordFromFlags(atkFlag, matkFlag)
return nil
if atkFlag and matkFlag then
return "Hybrid"
elseif atkFlag then
return "Attack"
elseif matkFlag then
return "Magic Attack"
end
end
return nil
end


local parts = {}
-- legacyPercentAtLevel: compute “Base% + PerLevel%*level” for legacy entries.
for _, ev in ipairs(list) do
local function legacyPercentAtLevel(entry, level)
if type(ev) == "table" then
if type(entry) ~= "table" then
local action = ev.Action or "On event"
return nil
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
end


return (#parts > 0) and table.concat(parts, "<br />") or nil
local baseRaw = entry["Base %"]
end
local perRaw  = entry["Per Level %"]
local baseN  = toNum(baseRaw)
local perN    = toNum(perRaw)


----------------------------------------------------------------------
if perN ~= nil and perN ~= 0 then
-- User matching (for auto lists on class pages)
local total = (baseN or 0) + (perN * level)
----------------------------------------------------------------------
return fmtNum(total) .. "%"
end


local function skillMatchesUser(rec, userName)
if baseN ~= nil then
if type(rec) ~= "table" or not userName or userName == "" then
return fmtNum(baseN) .. "%"
return false
end
if baseRaw ~= nil and tostring(baseRaw) ~= "" then
return tostring(baseRaw) .. "%"
end
end


local users = rec.Users
return nil
if type(users) ~= "table" then
end
return false
 
-- seriesFromValuePair: normalize Base/Per Level blocks into a level-indexed series.
local function seriesFromValuePair(block, maxLevel)
if type(block) ~= "table" then
return nil
end
end


local userLower = mw.ustring.lower(userName)
local base = block.Base
local per  = block["Per Level"]


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


return listHas(users.Classes) or listHas(users.Summons) or listHas(users.Monsters) or listHas(users.Events)
local function fmtAny(v)
end
local t = formatUnitValue(v)
return t and tostring(t) or (v ~= nil and tostring(v) or nil)
end


----------------------------------------------------------------------
local series = {}
-- Direct page detection (hide Users on the skill's own page)
----------------------------------------------------------------------


local function isDirectSkillPage(rec)
-- Expanded per-level series (wikiprep)
if type(rec) ~= "table" then
if type(per) == "table" and #per > 0 then
return false
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
end


local pageTitle = mw.title.getCurrentTitle()
-- Empty per-list -> base only
local pageName  = pageTitle and pageTitle.text or ""
if type(per) == "table" and #per == 0 then
pageName = trim(pageName)
local one = fmtAny(base)
if not pageName then
if one == nil or isZeroish(base) or isZeroish(one) then
return false
one = ""
end
for lv = 1, maxLevel do
series[lv] = one
end
return series
end
end


pageName = mw.ustring.lower(pageName)
-- Scalar per -> compute base + per*level (fallback)
local baseN = toNum(base) or 0
local perN  = toNum(per)


local ext = trim(rec["External Name"] or rec.Name or rec["Display Name"])
if perN ~= nil then
local internal = trim(rec["Internal Name"] or rec.InternalName or rec.InternalID)
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


return (ext and mw.ustring.lower(ext) == pageName) or (internal and mw.ustring.lower(internal) == pageName) or false
-- 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
end


----------------------------------------------------------------------
-- displayFromSeries: render a series as fixed text or dynSpan (nil if all “—”).
-- Slot config (edit these only to rearrange layout)
local function displayFromSeries(series, level)
----------------------------------------------------------------------
if type(series) ~= "table" or #series == 0 then
 
return nil
local HERO_BAR_SLOT_ASSIGNMENT = {
[1] = "IconName",
[2] = "SkillType",
}
 
local HERO_MODULE_SLOT_ASSIGNMENT = {
[1] = "SourceType",
[2] = "QuickStats",
[3] = "ReservedInfo",
[4] = "LevelSelector",
}
 
----------------------------------------------------------------------
-- Slot scaffolds
----------------------------------------------------------------------
 
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))
box:attr("data-region", "herobar")
box:attr("data-slot", tostring(slot))
if pluginName then
box:attr("data-plugin", tostring(pluginName))
end
end


if extraClasses then
local any = false
if type(extraClasses) == "string" then
for _, v in ipairs(series) do
box:addClass(extraClasses)
if v ~= "" then
elseif type(extraClasses) == "table" then
any = true
for _, c in ipairs(extraClasses) do
break
box:addClass(c)
end
end
end
end
end
 
if not any then
if isEmpty then
return nil
box:addClass("hero-bar-module-empty")
end
end


local body = box:tag("div"):addClass("hero-bar-module-body")
if isFlatList(series) then
if innerHtml and innerHtml ~= "" then
return mw.text.nowiki(series[1])
body:wikitext(innerHtml)
end
end
 
return dynSpan(series, level)
return tostring(box)
end
end


local function moduleBox(slot, pluginName, extraClasses, innerHtml, isEmpty)
-- formatAreaSize: human readable area sizing for QuickStats.
local box = mw.html.create("div")
-- Shows: "<Area Size> (<number>)" e.g. "Medium (4)"
box:addClass("hero-module")
local function formatAreaSize(area, maxLevel, level)
box:addClass("hero-module-" .. tostring(slot))
if type(area) ~= "table" then
box:attr("data-hero-module", tostring(slot))
return nil
box:attr("data-region", "modules")
box:attr("data-slot", tostring(slot))
if pluginName then
box:attr("data-plugin", tostring(pluginName))
end
end


if extraClasses then
-- Helper: pull a number from scalar/unit/valuepair-ish things.
if type(extraClasses) == "string" then
local function extractNumber(v)
box:addClass(extraClasses)
if v == nil then return nil end
elseif type(extraClasses) == "table" then
 
for _, c in ipairs(extraClasses) do
-- Unit block {Value, Unit}
box:addClass(c)
if type(v) == "table" and v.Value ~= nil then
local n = toNum(v.Value)
return n
end
 
-- ValuePair {Base, Per Level} -> prefer Base at current level if series exists
if type(v) == "table" and (v.Base ~= nil or v["Per Level"] ~= nil) then
local s = seriesFromValuePair(v, maxLevel or 1)
if type(s) == "table" and #s > 0 then
local idx = clamp(level or 1, 1, #s)
local txt = s[idx]
if txt and txt ~= "—" then
-- try parse numeric from string (e.g. "4 tiles" -> 4)
local num = tonumber((mw.ustring.gsub(tostring(txt), "[^0-9%.%-]", "")))
return num
end
end
end
return nil
end
-- Plain scalar
if type(v) == "number" then return v end
if type(v) == "string" then
local num = tonumber((mw.ustring.gsub(mw.text.trim(v), "[^0-9%.%-]", "")))
return num
end
end
return nil
end
end


if isEmpty then
-- 1) Read Area Size label/name
box:addClass("hero-module-empty")
local rawSize = area["Area Size"]
if rawSize == nil then
return nil
end
 
local sizeName = nil
if type(rawSize) == "table" then
sizeName = rawSize.Name or rawSize.ID or rawSize.Value
elseif type(rawSize) == "string" then
sizeName = rawSize
elseif type(rawSize) == "number" then
-- uncommon; treat as numeric-only label
sizeName = tostring(rawSize)
end
end


local body = box:tag("div"):addClass("hero-module-body")
sizeName = sizeName and mw.text.trim(tostring(sizeName)) or nil
if innerHtml and innerHtml ~= "" then
if not sizeName or sizeName == "" or isNoneLike(sizeName) then
body:wikitext(innerHtml)
return nil
end
end


return tostring(box)
-- 2) Find the numeric “exact number” to append
end
-- Prefer the explicit Area Distance block, then fall back to other known numeric keys.
local num = nil


----------------------------------------------------------------------
local dist = area["Area Distance"]
-- Shared helpers used by plug-ins
if type(dist) == "table" then
----------------------------------------------------------------------
-- Prefer Effective Distance if present and non-zero, else Base
num = extractNumber(dist["Effective Distance"]) or extractNumber(dist.Effective) or extractNumber(dist["Effective"])
if not num or num == 0 then
num = extractNumber(dist.Base) or extractNumber(dist["Base"])
end
end


local function formatScalingCompactLines(scaling)
if not num or num == 0 then
if type(scaling) ~= "table" then
num =
return {}
extractNumber(area["Area Value"]) or
extractNumber(area["Area Size Value"]) or
extractNumber(area["Area Number"]) or
extractNumber(area["Area Radius"])
end
end


local list = scaling
-- 3) Render
if #list == 0 then
-- If size already contains parentheses, assume it already includes the numeric.
if scaling.Percent ~= nil or scaling["Scaling ID"] or scaling["Scaling Name"] then
if mw.ustring.find(sizeName, "%(") then
list = { scaling }
return mw.text.nowiki(sizeName)
else
return {}
end
end
end


local out = {}
if num and num ~= 0 then
for _, s in ipairs(list) do
return mw.text.nowiki(string.format("%s (%s)", sizeName, fmtNum(num)))
if type(s) == "table" then
end
local stat = s["Scaling Name"] or s["Scaling ID"] or "Unknown"
 
local pct  = s.Percent
return mw.text.nowiki(sizeName)
local pctN = toNum(pct)
end


if pctN ~= nil and pctN ~= 0 then
-- skillHasAnyDamage: determine if a skill has any meaningful damage (for non-damaging rules).
table.insert(out, string.format("%s%% %s", fmtNum(pctN), stat))
local function skillHasAnyDamage(rec, maxLevel)
elseif pct ~= nil and tostring(pct) ~= "" and tostring(pct) ~= "0" then
if type(rec.Source) == "table" then
table.insert(out, string.format("%s%% %s", tostring(pct), stat))
local s = seriesFromValuePair(rec.Source, maxLevel)
if s then
for _, v in ipairs(s) do
if v ~= "—" then return true end
end
end
end
end
end
end


return out
if type(rec.Damage) == "table" then
end
local dmg = rec.Damage
 
for _, key in ipairs({ "Main Damage", "Flat Damage", "Reflect Damage" }) do
local function basisWordFromFlags(atkFlag, matkFlag)
local lst = dmg[key]
if atkFlag and matkFlag then
if type(lst) == "table" and #lst > 0 then
return "Hybrid"
return true
elseif atkFlag then
end
return "Attack"
end
elseif matkFlag then
return "Magic Attack"
end
end
return nil
 
return false
end
end


local function sourceValueForLevel(src, maxLevel, level)
-- computeDurationPromotion: promote status-duration into QuickStats when a skill is non-damaging.
if type(src) ~= "table" then
local function computeDurationPromotion(rec, maxLevel)
return nil
if type(rec) ~= "table" then return nil end
end
if skillHasAnyDamage(rec, maxLevel) then return nil end


local per = src["Per Level"]
local mech = (type(rec.Mechanics) == "table") and rec.Mechanics or {}
if type(per) == "table" and #per > 0 then
local bt  = (type(mech["Basic Timings"]) == "table") and mech["Basic Timings"] or {}
if isFlatList(per) then
local durS = seriesFromValuePair(bt["Duration"], maxLevel)
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 = {}
if durS ~= nil then
for _, v in ipairs(per) do
local any = false
table.insert(series, formatUnitValue(v) or tostring(v))
for _, v in ipairs(durS) do
if v ~= "—" then any = true break end
end
if any then
return nil
end
end
return dynSpan(series, level)
end
end


return valuePairDynamicValueOnly(src, maxLevel, level)
local apps = rec["Status Applications"]
end
if type(apps) ~= "table" then return nil end


local function legacyPercentAtLevel(entry, level)
for idx, app in ipairs(apps) do
if type(entry) ~= "table" then
if type(app) == "table" and type(app.Duration) == "table" then
return nil
local s = seriesFromValuePair(app.Duration, maxLevel)
end
if s then
 
for _, v in ipairs(s) do
local baseRaw = entry["Base %"]
if v ~= "—" then
local perRaw  = entry["Per Level %"]
return {
local baseN  = toNum(baseRaw)
durationBlock = app.Duration,
local perN    = toNum(perRaw)
suppressDurationIndex = idx,
 
}
if perN ~= nil and perN ~= 0 then
end
local total = (baseN or 0) + (perN * level)
end
return fmtNum(total) .. "%"
end
end
end
 
if baseN ~= nil then
return fmtNum(baseN) .. "%"
end
if baseRaw ~= nil and tostring(baseRaw) ~= "" then
return tostring(baseRaw) .. "%"
end
end


Line 914: Line 903:
end
end


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


local base = block.Base
-- PLUGIN: IconName (Hero Bar Slot 1) - icon + name.
local per  = block["Per Level"]
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 function pickUnit(v)
local wrap = mw.html.create("div")
if type(v) == "table" and v.Unit and v.Unit ~= "" then
wrap:addClass("sv-herobar-1-wrap")
return v.Unit
end
return nil
end
local unit = pickUnit(base) or pickUnit(per)


local function fmtAny(v)
if icon and icon ~= "" then
local t = formatUnitValue(v)
wrap:tag("div")
return t and tostring(t) or (v ~= nil and tostring(v) or nil)
:addClass("sv-herobar-icon")
:wikitext(string.format("[[File:%s|80px|link=]]", icon))
end
end


local series = {}
wrap:tag("div")
:addClass("spiritvale-infobox-title")
:wikitext(title)
 
return {
inner = tostring(wrap),
classes = "module-herobar-1",
}
end


if type(per) == "table" and #per > 0 then
-- PLUGIN: SkillType (Hero Bar Slot 2) - 2 rows x 3 cells (desktop + mobile).
for lv = 1, maxLevel do
-- Rules:
local raw = per[lv] or per[#per]
--  - If skill is non-damaging, hide Damage/Element/Hits.
local one = fmtAny(raw)
--  - If Hits is empty, hide Hits.
if one == nil or isZeroish(raw) or isZeroish(one) then
--  - If Combo is empty, hide Combo.
one = "—"
-- Ordering:
end
--  - Desktop: Damage, Element, Hits, Target, Cast, Combo
series[lv] = one
--  - Mobile:  Damage, Element, Target, Cast, Hits, Combo (CSS reorder)
end
function PLUGINS.SkillType(rec, ctx)
return series
local typeBlock = (type(rec.Type) == "table") and rec.Type or {}
end
local mech      = (type(rec.Mechanics) == "table") and rec.Mechanics or {}


if type(per) == "table" and #per == 0 then
local level    = ctx.level or 1
local one = fmtAny(base)
local maxLevel = ctx.maxLevel or 1
if one == nil or isZeroish(base) or isZeroish(one) then
 
one = "—"
local hideDamageBundle = (ctx.nonDamaging == true)
 
-- valName: extract a display string from typical {Name/ID/Value} objects.
-- NOTE: Includes number support so Hits=2 (number) doesn't get dropped.
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) == "number" then
return tostring(x)
end
end
for lv = 1, maxLevel do
if type(x) == "string" and x ~= "" then
series[lv] = one
return x
end
end
return series
return nil
end
end


local baseN = toNum(base) or 0
-- hitsDisplay: find + render Hits from multiple possible structured locations.
local perN  = toNum(per)
local function hitsDisplay()
local effects = (type(mech.Effects) == "table") and mech.Effects or {}
 
local h =
typeBlock.Hits or typeBlock["Hits"] or typeBlock["Hit Count"] or typeBlock["Hits Count"] or
mech.Hits or mech["Hits"] or mech["Hit Count"] or mech["Hits Count"] or
effects.Hits or effects["Hits"] or effects["Hit Count"] or effects["Hits Count"] or
rec.Hits or rec["Hits"]
 
if h == nil or isNoneLike(h) then
return nil
end


if perN ~= nil then
-- ValuePair-style table (Base/Per Level) => dynamic series
for lv = 1, maxLevel do
if type(h) == "table" then
local total = baseN + (perN * lv)
if h.Base ~= nil or h["Per Level"] ~= nil or type(h["Per Level"]) == "table" then
local v = unit and { Value = total, Unit = unit } or total
return displayFromSeries(seriesFromValuePair(h, maxLevel), level)
local one = fmtAny(v)
end
if one == nil or total == 0 or isZeroish(one) then
 
one = ""
-- Unit block {Value, Unit}
if h.Value ~= nil then
local t = formatUnitValue(h)
return t and mw.text.nowiki(t) or nil
end
 
-- Fallback name extraction
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) == "number" then return tostring(x) end
if type(x) == "string" and x ~= "" then return x end
return nil
end
 
local vn = valName(h)
if vn and not isNoneLike(vn) then
return mw.text.nowiki(vn)
end
end
series[lv] = one
end
end
return series
end


local raw = (base ~= nil) and base or per
-- Scalar number/string
local one = fmtAny(raw)
if type(h) == "number" then
if one == nil then
return mw.text.nowiki(fmtNum(h))
end
if type(h) == "string" then
local t = trim(h)
return (t and not isNoneLike(t)) and mw.text.nowiki(t) or nil
end
 
return nil
return nil
end
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)
-- comboDisplay: render Combo as a compact text block (Type (+ details)).
if type(series) ~= "table" or #series == 0 then
local function comboDisplay()
return nil
local c = (type(mech.Combo) == "table") and mech.Combo or nil
end
if not c then return nil end
 
local typ = trim(c.Type)
if not typ or isNoneLike(typ) then
return nil
end
 
local details = {}
 
local pct = formatUnitValue(c.Percent)
if pct and not isZeroish(pct) then
table.insert(details, mw.text.nowiki(pct))
end


local any = false
local dur = formatUnitValue(c.Duration)
for _, v in ipairs(series) do
if dur and not isZeroish(dur) then
if v ~= "—" then
table.insert(details, mw.text.nowiki(dur))
any = true
break
end
end
end
if not any then
return nil
end


if isFlatList(series) then
if #details > 0 then
return mw.text.nowiki(series[1])
return mw.text.nowiki(typ) .. " (" .. table.concat(details, ", ") .. ")"
end
return mw.text.nowiki(typ)
end
end
return dynSpan(series, level)
end


local function formatAreaSize(area)
local grid = mw.html.create("div")
if type(area) ~= "table" then
grid:addClass("sv-type-grid")
return nil
grid:addClass("sv-compact-root")
end
 
local added = false
 
-- addChunk: add one labeled value cell (key drives CSS ordering).
local function addChunk(key, label, valueHtml)
if valueHtml == nil or valueHtml == "" then return end
added = true


local raw = area["Area Size"]
local chunk = grid:tag("div")
if raw == nil then
:addClass("sv-type-chunk")
return nil
:addClass("sv-type-" .. tostring(key))
end
:attr("data-type-key", tostring(key))


local name, num
chunk:tag("div")
:addClass("sv-type-label")
:wikitext(mw.text.nowiki(label))


if type(raw) == "table" then
chunk:tag("div")
name = raw.Name or raw.ID or raw.Value
:addClass("sv-type-value")
num  = raw.Value
:wikitext(valueHtml)
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
end


if num == nil then
-- Damage + Element + Hits bundle (hidden when non-damaging)
num = toNum(area["Area Value"]) or toNum(area["Area Size Value"]) or toNum(area["Area Number"]) or toNum(area["Area Radius"])
if not hideDamageBundle then
end
local dmg  = valName(typeBlock.Damage or typeBlock["Damage Type"])
local ele  = valName(typeBlock.Element or typeBlock["Element Type"])
local hits = hitsDisplay()


if name ~= nil then
if dmg and not isNoneLike(dmg) then
local s = mw.text.trim(tostring(name))
addChunk("damage", "Damage", mw.text.nowiki(dmg))
if s == "" or isNoneLike(s) then
return nil
end
end
if mw.ustring.find(s, "%(") then
if ele and not isNoneLike(ele) then
return mw.text.nowiki(s)
addChunk("element", "Element", mw.text.nowiki(ele))
end
end
if num ~= nil and num ~= 0 then
if hits then
return mw.text.nowiki(string.format("%s (%s)", s, fmtNum(num)))
addChunk("hits", "Hits", hits)
end
end
return mw.text.nowiki(s)
end
end


if num ~= nil and num ~= 0 then
-- Target + Cast
return mw.text.nowiki(string.format("(%s)", fmtNum(num)))
local tgt = valName(typeBlock.Target or typeBlock["Target Type"])
local cst = valName(typeBlock.Cast  or typeBlock["Cast Type"])
 
if tgt and not isNoneLike(tgt) then
addChunk("target", "Target", mw.text.nowiki(tgt))
end
if cst and not isNoneLike(cst) then
addChunk("cast", "Cast", mw.text.nowiki(cst))
end
end


return nil
-- Combo
local combo = comboDisplay()
if combo then
addChunk("combo", "Combo", combo)
end
 
return {
inner = added and tostring(grid) or "",
classes = "module-skill-type",
}
end
end


local function skillHasAnyDamage(rec, maxLevel)
function PLUGINS.Description(rec, ctx)
if type(rec.Source) == "table" then
        local desc = trim(rec.Description)
local s = seriesFromValuePair(rec.Source, maxLevel)
        if not desc then
if s then
                return nil
for _, v in ipairs(s) do
        end
if v ~= "—" then return true end
 
end
        local wrapper = mw.html.create("div")
end
        wrapper:addClass("sv-module-description")
end
        wrapper:wikitext(string.format("''%s''", desc))
 
 
if type(rec.Damage) == "table" then
        return {
local dmg = rec.Damage
                inner = tostring(wrapper),
for _, key in ipairs({ "Main Damage", "Flat Damage", "Reflect Damage" }) do
                classes = "module-description",
local lst = dmg[key]
        }
if type(lst) == "table" and #lst > 0 then
return true
end
end
end
 
return false
end
end


local function computeDurationPromotion(rec, maxLevel)
-- PLUGIN: SourceType (Hero Module Slot 1) - Modifier + Source + Scaling.
if type(rec) ~= "table" then return nil end
function PLUGINS.SourceType(rec, ctx)
if skillHasAnyDamage(rec, maxLevel) then return nil end
local level = ctx.level or 1
local maxLevel = ctx.maxLevel or 1


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


if durS ~= nil then
-- sourceValueForLevel: dynamic formatting for structured Source blocks.
local any = false
local function sourceValueForLevel(src)
for _, v in ipairs(durS) do
if type(src) ~= "table" then
if v ~= "" then any = true break end
end
if any then
return nil
return nil
end
end
end


local apps = rec["Status Applications"]
local per = src["Per Level"]
if type(apps) ~= "table" then return nil end
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


for idx, app in ipairs(apps) do
local series = {}
if type(app) == "table" and type(app.Duration) == "table" then
for _, v in ipairs(per) do
local s = seriesFromValuePair(app.Duration, maxLevel)
table.insert(series, formatUnitValue(v) or tostring(v))
if s then
end
for _, v in ipairs(s) do
return dynSpan(series, level)
if v ~= "—" then
return {
durationBlock = app.Duration,
suppressDurationIndex = idx,
}
end
end
end
end
end
return valuePairDynamicValueOnly(src, maxLevel, level)
end
end


return nil
if type(rec.Source) == "table" then
end
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"
-- Plug-ins
sourceVal  = sourceValueForLevel(src)
----------------------------------------------------------------------
scaling    = src.Scaling
end


local PLUGINS = {}
-- 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


function PLUGINS.IconName(rec, ctx)
local main = dmg["Main Damage"]
local icon  = rec.Icon
local refl = dmg["Reflect Damage"]
local title = rec["External Name"] or rec.Name or rec["Internal Name"] or "Unknown Skill"
local flat = dmg["Flat Damage"]


local wrap = mw.html.create("div")
if type(main) == "table" and #main > 0 then
wrap:addClass("sv-herobar-1-wrap")
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 icon and icon ~= "" then
if type(pick) == "table" then
wrap:tag("div")
local atkFlag  = (pick["ATK-Based"] == true)
:addClass("sv-herobar-icon")
local matkFlag = (pick["MATK-Based"] == true)
:wikitext(string.format("[[File:%s|80px|link=]]", icon))
basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)
end


wrap:tag("div")
sourceKind = (pick.Type == "Healing") and "Healing" or "Damage"
:addClass("spiritvale-infobox-title")
sourceVal  = legacyPercentAtLevel(pick, level)
:wikitext(title)
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)


return {
sourceKind = "Reflect"
inner = tostring(wrap),
sourceVal  = legacyPercentAtLevel(pick, level)
classes = "module-herobar-1",
elseif type(flat) == "table" and #flat > 0 and type(flat[1]) == "table" then
}
local pick = flat[1]
end
local atkFlag  = (pick["ATK-Based"] == true)
local matkFlag = (pick["MATK-Based"] == true)
basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)


function PLUGINS.ReservedInfo(rec, ctx)
sourceKind = "Flat"
local wrap = mw.html.create("div")
sourceVal  = legacyPercentAtLevel(pick, level)
wrap:addClass("sv-herobar-2-wrap")
end
return {
end
inner = tostring(wrap),
classes = "module-herobar-2",
}
end


function PLUGINS.LevelSelector(rec, ctx)
local scalingLines = formatScalingCompactLines(scaling)
local level = ctx.level or 1
local hasSource    = (sourceVal ~= nil and tostring(sourceVal) ~= "")
local maxLevel = ctx.maxLevel or 1
local hasScaling  = (type(scalingLines) == "table" and #scalingLines > 0)


local inner = mw.html.create("div")
if (not hasSource) and (not hasScaling) then
inner:addClass("sv-level-ui")
return nil
end


inner:tag("div")
local hasMod = (basisWord ~= nil and tostring(basisWord) ~= "")
: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")
local extra = { "skill-source-module" }
table.insert(extra, hasMod and "sv-has-mod" or "sv-no-mod")


if tonumber(maxLevel) and tonumber(maxLevel) > 1 then
if hasSource and (not hasScaling) then
slider:tag("input")
table.insert(extra, "sv-only-source")
:attr("type", "range")
elseif hasScaling and (not hasSource) then
:attr("min", "1")
table.insert(extra, "sv-only-scaling")
: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
end


return {
local wrap = mw.html.create("div")
inner = tostring(inner),
wrap:addClass("sv-source-grid")
classes = "module-level-selector",
wrap:addClass("sv-compact-root")
}
end


function PLUGINS.SkillType(rec, ctx)
if hasMod then
local typeBlock = (type(rec.Type) == "table") and rec.Type or {}
local modCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-modifier")
local hideDamageAndElement = (ctx.nonDamaging == true)
modCol:tag("div"):addClass("sv-source-pill"):wikitext("Modifier")
modCol:tag("div"):addClass("sv-modifier-value"):wikitext(mw.text.nowiki(basisWord))
end


local function valName(x)
if hasSource then
if x == nil then return nil end
local sourceCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-main")
if type(x) == "table" then
sourceCol:tag("div"):addClass("sv-source-pill"):wikitext(mw.text.nowiki(sourceKind or "Source"))
if x.Name and x.Name ~= "" then return tostring(x.Name) end
sourceCol:tag("div"):addClass("sv-source-value"):wikitext(sourceVal)
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
end


local grid = mw.html.create("div")
if hasScaling then
grid:addClass("sv-type-grid")
local scalingCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-scaling")
scalingCol:tag("div"):addClass("sv-source-pill"):wikitext("Scaling")


local added = false
local list = scalingCol:tag("div"):addClass("sv-scaling-list")
local function addChunk(label, rawVal)
for _, line in ipairs(scalingLines) do
local v = valName(rawVal)
list:tag("div"):addClass("sv-scaling-item"):wikitext(mw.text.nowiki(line))
if not v or v == "" then return end
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
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 {
return {
inner = added and tostring(grid) or "",
inner = tostring(wrap),
classes = "module-skill-type",
classes = extra,
}
}
end
end


function PLUGINS.SourceType(rec, ctx)
-- PLUGIN: QuickStats (Hero Module Slot 2) - 3x2 grid (range/area/cost/cast/cd/duration).
-- NOTE: Hits does NOT live here (it lives in SkillType).
function PLUGINS.QuickStats(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 promo = ctx.promo


local basisWord = nil
local mech = (type(rec) == "table" and type(rec.Mechanics) == "table") and rec.Mechanics or {}
local sourceKind = nil
local bt  = (type(mech["Basic Timings"]) == "table") and mech["Basic Timings"] or {}
local sourceVal  = nil
local rc  = (type(mech["Resource Cost"]) == "table") and mech["Resource Cost"] or {}
local scaling    = nil
 
local function dash() return "—" end


if type(rec.Source) == "table" then
-- Range (0 => —)
local src = rec.Source
local rangeVal = nil
local atkFlag  = (src["ATK-Based"] == true)
if mech.Range ~= nil and not isNoneLike(mech.Range) then
local matkFlag = (src["MATK-Based"] == true)
local n = toNum(mech.Range)
basisWord = basisWordFromFlags(atkFlag, matkFlag)
if n ~= nil then
 
if n ~= 0 then
sourceKind = src.Type or ((src.Healing == true) and "Healing") or "Damage"
rangeVal = mw.text.nowiki(formatUnitValue(mech.Range) or tostring(mech.Range))
sourceVal  = sourceValueForLevel(src, maxLevel, level)
end
scaling    = src.Scaling
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


if (sourceVal == nil or sourceVal == "") and type(rec.Damage) == "table" then
-- Area
local dmg = rec.Damage
local areaVal = formatAreaSize(mech.Area, maxLevel, level)
scaling = scaling or dmg.Scaling


local main = dmg["Main Damage"]
-- Timings
local refl = dmg["Reflect Damage"]
local castVal = displayFromSeries(seriesFromValuePair(bt["Cast Time"], maxLevel), level)
local flat = dmg["Flat Damage"]
local cdVal  = displayFromSeries(seriesFromValuePair(bt["Cooldown"],  maxLevel), level)
local durVal  = displayFromSeries(seriesFromValuePair(bt["Duration"],  maxLevel), level)


if type(main) == "table" and #main > 0 then
-- Promote status duration if needed
local pick = nil
if (durVal == nil) and type(promo) == "table" and type(promo.durationBlock) == "table" then
for _, d in ipairs(main) do
durVal = displayFromSeries(seriesFromValuePair(promo.durationBlock, maxLevel), level)
if type(d) == "table" and d.Type ~= "Healing" then
end
pick = d
 
break
-- Cost: MP + HP
end
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
pick = pick or main[1]
end
return any and s or nil
end


if type(pick) == "table" then
local mpS = labeledSeries(rc["Mana Cost"], "MP")
local atkFlag  = (pick["ATK-Based"] == true)
local hpS = labeledSeries(rc["Health Cost"], "HP")
local matkFlag = (pick["MATK-Based"] == true)
basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)


sourceKind = (pick.Type == "Healing") and "Healing" or "Damage"
local costSeries = {}
sourceVal  = legacyPercentAtLevel(pick, level)
for lv = 1, maxLevel do
end
local mp = mpS and mpS[lv] or ""
elseif type(refl) == "table" and #refl > 0 and type(refl[1]) == "table" then
local hp = hpS and hpS[lv] or ""
local pick = refl[1]
local atkFlag  = (pick["ATK-Based"] == true)
local matkFlag = (pick["MATK-Based"] == true)
basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)


sourceKind = "Reflect"
if mp ~= "—" and hp ~= "" then
sourceVal  = legacyPercentAtLevel(pick, level)
costSeries[lv] = mp .. " + " .. hp
elseif type(flat) == "table" and #flat > 0 and type(flat[1]) == "table" then
elseif mp ~= "" then
local pick = flat[1]
costSeries[lv] = mp
local atkFlag  = (pick["ATK-Based"] == true)
elseif hp ~= "" then
local matkFlag = (pick["MATK-Based"] == true)
costSeries[lv] = hp
basisWord = basisWord or basisWordFromFlags(atkFlag, matkFlag)
else
 
costSeries[lv] = ""
sourceKind = "Flat"
sourceVal  = legacyPercentAtLevel(pick, level)
end
end
end
end


local scalingLines = formatScalingCompactLines(scaling)
local costVal = displayFromSeries(costSeries, level)
local hasSource    = (sourceVal ~= nil and tostring(sourceVal) ~= "")
 
local hasScaling  = (type(scalingLines) == "table" and #scalingLines > 0)
local grid = mw.html.create("div")
grid:addClass("sv-m4-grid")
grid:addClass("sv-compact-root")


if (not hasSource) and (not hasScaling) then
local function addCell(label, val)
return nil
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


local hasMod = (basisWord ~= nil and tostring(basisWord) ~= "")
addCell("Range",    rangeVal)
addCell("Area",      areaVal)
addCell("Cost",      costVal)
addCell("Cast Time", castVal)
addCell("Cooldown",  cdVal)
addCell("Duration",  durVal)


local extra = { "skill-source-module" }
return {
table.insert(extra, hasMod and "sv-has-mod" or "sv-no-mod")
inner = tostring(grid),
classes = "module-quick-stats",
}
end
 
-- PLUGIN: SpecialMechanics (Hero Module Slot 3)
-- Shows:
--  - Flags (deduped)
--   - Special mechanics (mech.Effects)
-- NOTE: Combo lives in SkillType (Hero Bar Slot 2).
function PLUGINS.SpecialMechanics(rec, ctx)
local level = ctx.level or 1
local maxLevel = ctx.maxLevel or 1


if hasSource and (not hasScaling) then
local mech    = (type(rec) == "table" and type(rec.Mechanics) == "table") and rec.Mechanics or {}
table.insert(extra, "sv-only-source")
local effects = (type(mech.Effects) == "table") and mech.Effects or nil
elseif hasScaling and (not hasSource) then
local mods    = (type(rec.Modifiers) == "table") and rec.Modifiers or nil
table.insert(extra, "sv-only-scaling")
 
------------------------------------------------------------------
-- Hits guard (we want Hits ONLY in SkillType)
------------------------------------------------------------------
local function isHitsKey(name)
if not name then return false end
local k = mw.ustring.lower(mw.text.trim(tostring(name)))
return (
k == "hit" or
k == "hits" or
k == "hit count" or
k == "hits count" or
k == "hitcount" or
k == "hitscount"
)
end
end


local wrap = mw.html.create("div")
------------------------------------------------------------------
wrap:addClass("sv-source-grid")
-- Flags (flat, de-duped)
------------------------------------------------------------------
local flagSet = {}
 
local denyFlags = {
["self centered"] = true,
["self-centred"] = true,
["bond"] = true,
["combo"] = true,
        ["hybrid"] = true,
 
-- hits variants
["hit"] = true,
["hits"] = true,
["hit count"] = true,
["hits count"] = true,
["hitcount"] = true,
["hitscount"] = true,
}


if hasMod then
local function allowFlag(name)
local modCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-modifier")
if not name then return false end
modCol:tag("div"):addClass("sv-source-pill"):wikitext("Modifier")
local k = mw.ustring.lower(mw.text.trim(tostring(name)))
modCol:tag("div"):addClass("sv-modifier-value"):wikitext(mw.text.nowiki(basisWord))
if k == "" then return false end
if denyFlags[k] then return false end
return true
end
end


if hasSource then
local function addFlags(sub)
local sourceCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-main")
if type(sub) ~= "table" then return end
sourceCol:tag("div"):addClass("sv-source-pill"):wikitext(mw.text.nowiki(sourceKind or "Source"))
for k, v in pairs(sub) do
sourceCol:tag("div"):addClass("sv-source-value"):wikitext(sourceVal)
if v and allowFlag(k) then
flagSet[tostring(k)] = true
end
end
end
end


if hasScaling then
if mods then
local scalingCol = wrap:tag("div"):addClass("sv-source-col"):addClass("sv-source-scaling")
addFlags(mods["Movement Modifiers"])
scalingCol:tag("div"):addClass("sv-source-pill"):wikitext("Scaling")
addFlags(mods["Combat Modifiers"])
 
addFlags(mods["Special Modifiers"])
local list = scalingCol:tag("div"):addClass("sv-scaling-list")
for k, v in pairs(mods) do
for _, line in ipairs(scalingLines) do
if type(v) == "boolean" and v and allowFlag(k) then
list:tag("div"):addClass("sv-scaling-item"):wikitext(mw.text.nowiki(line))
flagSet[tostring(k)] = true
end
end
end
end
end


return {
local flags = {}
inner = tostring(wrap),
for k, _ in pairs(flagSet) do table.insert(flags, k) end
classes = extra,
table.sort(flags)
}
 
end
------------------------------------------------------------------
-- Special mechanics (name => value)
------------------------------------------------------------------
local mechItems = {}
 
if effects then
local keys = {}
for k, _ in pairs(effects) do table.insert(keys, k) end
table.sort(keys)


-- QuickStats:
for _, name in ipairs(keys) do
-- - In modules row: classic 3x2 grid (.sv-m4-grid)
-- Skip Hits completely (it belongs in SkillType)
-- - In hero bar: compact strip wrapper (.sv-qs-strip) so CSS can "flatten" on mobile
if not isHitsKey(name) then
function PLUGINS.QuickStats(rec, ctx)
local block = effects[name]
local level = ctx.level or 1
if type(block) == "table" then
local maxLevel = ctx.maxLevel or 1
-- Also skip if the block's Type is "Hits" (some data may encode it that way)
local promo = ctx.promo
if not isHitsKey(block.Type) then
local disp = displayFromSeries(seriesFromValuePair(block, maxLevel), level)
local t = trim(block.Type)


local mech = (type(rec) == "table" and type(rec.Mechanics) == "table") and rec.Mechanics or {}
local value = disp
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
-- If Type exists and is distinct, prefix it.
if t and not isNoneLike(t) and mw.ustring.lower(t) ~= mw.ustring.lower(tostring(name)) then
if value then
value = mw.text.nowiki(t) .. ": " .. value
else
value = mw.text.nowiki(t)
end
end


local rangeVal = nil
if value then
if mech.Range ~= nil and not isNoneLike(mech.Range) then
table.insert(mechItems, { label = tostring(name), value = value })
local n = toNum(mech.Range)
end
if n ~= nil then
end
if n ~= 0 then
end
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


local areaVal = formatAreaSize(mech.Area)
local hasFlags = (#flags > 0)
local hasMech  = (#mechItems > 0)
 
if (not hasFlags) and (not hasMech) then
local root = mw.html.create("div")
root:addClass("sv-sm-root")
root:addClass("sv-compact-root")
root:tag("div"):addClass("sv-sm-empty"):wikitext("No Special Mechanics")
 
return {
inner = tostring(root),
classes = "module-special-mechanics",
}
end
 
local count = 0
if hasFlags then count = count + 1 end
if hasMech  then count = count + 1 end
 
local root = mw.html.create("div")
root:addClass("sv-sm-root")
root:addClass("sv-compact-root")


local castSeries = seriesFromValuePair(bt["Cast Time"], maxLevel)
local layout = root:tag("div"):addClass("sv-sm-layout")
local cdSeries  = seriesFromValuePair(bt["Cooldown"],  maxLevel)
layout:addClass("sv-sm-count-" .. tostring(count))
local durSeries  = seriesFromValuePair(bt["Duration"],  maxLevel)


local castVal = displayFromSeries(castSeries, level)
-- Column 1: Flags
local cdVal  = displayFromSeries(cdSeries, level)
if hasFlags then
local durVal  = displayFromSeries(durSeries, level)
local fcol = layout:tag("div"):addClass("sv-sm-col"):addClass("sv-sm-col-flags")
for _, f in ipairs(flags) do
fcol:tag("div"):addClass("sv-sm-flag"):wikitext(mw.text.nowiki(f))
end
end


if (durVal == nil) and type(promo) == "table" and type(promo.durationBlock) == "table" then
-- Column 2: Special Mechanics (stacked)
durSeries = seriesFromValuePair(promo.durationBlock, maxLevel)
if hasMech then
durVal = displayFromSeries(durSeries, level)
local mcol = layout:tag("div"):addClass("sv-sm-col"):addClass("sv-sm-col-mech")
for _, it in ipairs(mechItems) do
local one = mcol:tag("div"):addClass("sv-sm-mech")
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
end
end


local function labeledSeries(block, label)
return {
local s = seriesFromValuePair(block, maxLevel)
inner = tostring(root),
if not s then return nil end
classes = "module-special-mechanics",
local any = false
}
for i, v in ipairs(s) do
end
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")
-- PLUGIN: LevelSelector (Hero Module Slot 4) - JS level slider.
local hpS = labeledSeries(rc["Health Cost"], "HP")
function PLUGINS.LevelSelector(rec, ctx)
local level = ctx.level or 1
local maxLevel = ctx.maxLevel or 1


local costSeries = {}
local inner = mw.html.create("div")
for lv = 1, maxLevel do
inner:addClass("sv-level-ui")
local mp = mpS and mpS[lv] or ""
local hp = hpS and hpS[lv] or ""


if mp ~= "" and hp ~= "—" then
inner:tag("div")
costSeries[lv] = mp .. " + " .. hp
:addClass("sv-level-label")
elseif mp ~= "" then
:wikitext("Level <span class=\"sv-level-num\">" .. tostring(level) .. "</span> / " .. tostring(maxLevel))
costSeries[lv] = mp
elseif hp ~= "" then
costSeries[lv] = hp
else
costSeries[lv] = "—"
end
end


local costVal = displayFromSeries(costSeries, level)
local slider = inner:tag("div"):addClass("sv-level-slider")


local inHeroBar = (type(ctx) == "table" and ctx.region == "herobar")
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


local wrap = mw.html.create("div")
return {
wrap:addClass(inHeroBar and "sv-qs-strip" or "sv-m4-grid")
inner = tostring(inner),
 
classes = "module-level-selector",
local function addCell(label, val)
local cell = wrap: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",      castVal)
addCell("CD",        cdVal)
addCell("Dur",      durVal)
 
local classes = { "module-quick-stats" }
if inHeroBar then
table.insert(classes, "sv-qs-in-herobar")
end
 
return {
inner = tostring(wrap),
classes = classes,
}
}
end
-- Alias plug-in name you can assign in slots:
-- HERO_BAR_SLOT_ASSIGNMENT[2] = "Mechanics"
function PLUGINS.Mechanics(rec, ctx)
local res = PLUGINS.QuickStats(rec, ctx)
if type(res) == "table" then
local cls = res.classes
if type(cls) == "string" then
cls = { cls }
elseif type(cls) ~= "table" then
cls = {}
end
table.insert(cls, "module-mechanics")
res.classes = cls
end
return res
end
end


Line 1,484: Line 1,587:
----------------------------------------------------------------------
----------------------------------------------------------------------


-- normalizeResult: normalize plugin return values into {inner, classes}.
local function normalizeResult(res)
local function normalizeResult(res)
if res == nil then return nil end
if res == nil then return nil end
Line 1,499: Line 1,603:
end
end


-- safeCallPlugin: pcall wrapper to prevent infobox failure on plugin errors.
local function safeCallPlugin(name, rec, ctx)
local function safeCallPlugin(name, rec, ctx)
local fn = PLUGINS[name]
local fn = PLUGINS[name]
Line 1,511: Line 1,616:
end
end


-- renderHeroBarSlot: render a hero-bar slot by plugin assignment.
local function renderHeroBarSlot(slotIndex, rec, ctx)
local function renderHeroBarSlot(slotIndex, rec, ctx)
local pluginName = HERO_BAR_SLOT_ASSIGNMENT[slotIndex]
        local pluginName = MODULE_SLOT_ASSIGNMENT[slotIndex]
if not pluginName then
        if not pluginName then
return heroBarBox(slotIndex, nil, nil, "", true)
                return heroBarBox(slotIndex, nil, "", true)
end
        end


local ctxSlot = ctxClone(ctx, { region = "herobar", slot = slotIndex })
        local res = safeCallPlugin(pluginName, rec, ctx)
local res = safeCallPlugin(pluginName, rec, ctxSlot)
        if not res or not res.inner or res.inner == "" then
if not res or not res.inner or res.inner == "" then
                return heroBarBox(slotIndex, nil, "", true)
return heroBarBox(slotIndex, pluginName, nil, "", true)
        end
end


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


local function renderModuleSlot(slotIndex, rec, ctx)
-- isEmptyModuleContent: true when a module slot has no meaningful content.
local pluginName = HERO_MODULE_SLOT_ASSIGNMENT[slotIndex]
local function isEmptyModuleContent(inner)
if not pluginName then
        if inner == nil then return true end
return moduleBox(slotIndex, nil, nil, "", true)
 
end
        local asString = tostring(inner)
 
        if mw.ustring.find(asString, "sv%-dyn") or mw.ustring.find(asString, "data%-series") then
                return false
        end


local ctxSlot = ctxClone(ctx, { region = "modules", slot = slotIndex })
        local trimmed = mw.text.trim(asString)
local res = safeCallPlugin(pluginName, rec, ctxSlot)
        if trimmed == "" or trimmed == "" then
if not res or not res.inner or res.inner == "" then
                return true
return moduleBox(slotIndex, pluginName, nil, "", true)
        end
end


return moduleBox(slotIndex, pluginName, res.classes, res.inner, false)
        local withoutTags = mw.text.trim(mw.ustring.gsub(trimmed, "<[^>]+>", ""))
        return (withoutTags == "" or withoutTags == "—")
end
 
-- mergeClasses: merge string/table classes with an optional extra class.
local function mergeClasses(base, extra)
        local list = {}
 
        local function add(item)
                if type(item) == "string" then
                        for cls in mw.ustring.gmatch(item, "[^%s]+") do
                                table.insert(list, cls)
                        end
                elseif type(item) == "table" then
                        for _, c in ipairs(item) do
                                add(c)
                        end
                end
        end
 
        add(base)
        add(extra)
 
        if #list == 0 then
                return nil
        elseif #list == 1 then
                return list[1]
        end
 
        return list
end
 
-- renderModuleSlot: render a hero-module slot by plugin assignment.
local function renderModuleSlot(slotIndex, rec, ctx)
        local pluginName = MODULE_SLOT_ASSIGNMENT[slotIndex]
        if not pluginName then
                return nil
        end
 
        local res = safeCallPlugin(pluginName, rec, ctx)
        if not res or isEmptyModuleContent(res.inner) then
                return nil
        end
 
        return {
                inner = res.inner,
                classes = res.classes,
        }
end
end


Line 1,545: Line 1,700:
----------------------------------------------------------------------
----------------------------------------------------------------------


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


local function buildHeroModulesUI(rec, ctx)
-- buildModuleGridUI: build the lower module rows (Modules 3–8, 3 rows).
local grid = mw.html.create("div")
local function buildModuleGridUI(rec, ctx)
grid:addClass("hero-modules-grid")
        local grid = mw.html.create("div")
        grid:addClass("hero-modules-grid")
        grid:addClass("sv-modules-grid")
 
        local slots = {}
        for _, pair in ipairs(MODULE_GRID_PAIRS) do
                for _, slot in ipairs(pair) do
                        slots[slot] = renderModuleSlot(slot, rec, ctx)
                end
        end
 
        local hasModules = false
        for _, pair in ipairs(MODULE_GRID_PAIRS) do
                local left  = slots[pair[1]]
                local right = slots[pair[2]]
 
                if left or right then
                        if left and right then
                                grid:wikitext(moduleBox(pair[1], left.classes, left.inner, false))
                                grid:wikitext(moduleBox(pair[2], right.classes, right.inner, false))
                        elseif left then
                                grid:wikitext(moduleBox(pair[1], mergeClasses(left.classes, "hero-module-full"), left.inner, false))
                        elseif right then
                                grid:wikitext(moduleBox(pair[2], mergeClasses(right.classes, "hero-module-full"), right.inner, false))
                        end
 
                        hasModules = true
                end
        end


for slot = 1, 4 do
        if not hasModules then
grid:wikitext(renderModuleSlot(slot, rec, ctx))
                return ""
end
        end


return tostring(grid)
        return tostring(grid)
end
end


local function addHeroModulesRow(tbl, modulesUI)
-- addModuleGridRow: add the lower module grid into the infobox table.
if not modulesUI or modulesUI == "" then
local function addModuleGridRow(tbl, modulesUI)
return
        if not modulesUI or modulesUI == "" then
end
                return
        end


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


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


Line 1,584: Line 1,767:
----------------------------------------------------------------------
----------------------------------------------------------------------


-- buildInfobox: render a single skill infobox.
local function buildInfobox(rec, opts)
local function buildInfobox(rec, opts)
opts = opts or {}
opts = opts or {}
Line 1,599: Line 1,783:
}
}


-- Non-damaging hides Damage/Element/Hits in SkillType
do
do
local dmgVal = nil
local dmgVal = nil
Line 1,627: Line 1,812:
end
end


local desc  = rec.Description or ""
        -- Module 1–2 (Icon + Skill Type)
 
        local heroRow = root:tag("tr")
local heroRow = root:tag("tr")
        heroRow:addClass("spiritvale-infobox-main")
heroRow:addClass("spiritvale-infobox-main")
        heroRow:addClass("sv-hero-title-row")
heroRow:addClass("sv-hero-title-row")
        heroRow:addClass("hero-title-bar")
heroRow:addClass("hero-title-bar")


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


if desc ~= "" then
        -- Module grid (rows 2–4)
local descRow = root:tag("tr")
        addModuleGridRow(root, buildModuleGridUI(rec, ctx))
descRow:addClass("spiritvale-infobox-main")
descRow:addClass("sv-hero-desc-row")
descRow:addClass("hero-description-bar")


local descCell = descRow:tag("td")
-- Users (hide on direct skill page)
descCell:attr("colspan", 2)
if showUsers then
descCell:addClass("sv-hero-desc-cell")
local users = rec.Users or {}
 
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
 
local modulesUI = buildHeroModulesUI(rec, ctx)
addHeroModulesRow(root, modulesUI)
 
if showUsers then
local users = rec.Users or {}
addRow(root, "Classes",  listToText(users.Classes),  "sv-row-users", "Users.Classes")
addRow(root, "Classes",  listToText(users.Classes),  "sv-row-users", "Users.Classes")
addRow(root, "Summons",  listToText(users.Summons),  "sv-row-users", "Users.Summons")
addRow(root, "Summons",  listToText(users.Summons),  "sv-row-users", "Users.Summons")
Line 1,668: Line 1,835:
end
end


-- Requirements
local req = rec.Requirements or {}
local req = rec.Requirements or {}
local hasReq =
local hasReq =
Line 1,693: Line 1,861:
end
end


-- Mechanics (keep small extras only)
local mech = rec.Mechanics or {}
local mech = rec.Mechanics or {}
if next(mech) ~= nil then
if next(mech) ~= nil then
Line 1,698: Line 1,867:
addRow(root, "Autocast Multiplier", tostring(mech["Autocast Multiplier"]), "sv-row-mech", "Mechanics.Autocast Multiplier")
addRow(root, "Autocast Multiplier", tostring(mech["Autocast Multiplier"]), "sv-row-mech", "Mechanics.Autocast Multiplier")
end
end
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


-- Legacy damage breakdown (only when Source absent)
if type(rec.Source) ~= "table" then
if type(rec.Source) ~= "table" then
local dmg = rec.Damage or {}
local dmg = rec.Damage or {}
Line 1,718: Line 1,885:
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, "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, "Flat Damage",    formatDamageList(dmg["Flat Damage"], 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, "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")
addRow(root, "Healing",        formatDamageList(healOnly, maxLevel, level, false),                 "sv-row-source", "Damage.Healing")
end
end
end
end


local modsText = formatModifiers(rec.Modifiers)
-- Status rows
if modsText then
local function formatStatusApplications(list, suppressDurationIndex)
addRow(root, "Flags", modsText, "sv-row-meta", "Modifiers")
if type(list) ~= "table" or #list == 0 then return nil end
end


local suppressIdx = (type(ctx.promo) == "table") and ctx.promo.suppressDurationIndex or nil
local parts = {}
local statusApps = formatStatusApplications(rec["Status Applications"], maxLevel, level, suppressIdx)
for idx, s in ipairs(list) do
local statusRem  = formatStatusRemoval(rec["Status Removal"], maxLevel, level)
if type(s) == "table" then
if statusApps or statusRem then
local typ  = s.Type or s.Scope or "Target"
addRow(root, "Applies", statusApps, "sv-row-status", "Status Applications")
local name = s["Status External Name"] or s["Status Internal Name"] or "Unknown status"
addRow(root, "Removes", statusRem,  "sv-row-status", "Status Removal")
local seg = tostring(typ) .. " " .. tostring(name)
end
local detail = {}


local eventsText = formatEvents(rec.Events)
if idx ~= suppressDurationIndex and type(s.Duration) == "table" then
if eventsText then
local t = valuePairDynamicValueOnly(s.Duration, maxLevel, level)
addRow(root, "Triggers", eventsText, "sv-row-meta", "Events")
if t then table.insert(detail, "Duration: " .. t) end
end
end


if type(rec.Notes) == "table" and #rec.Notes > 0 then
if type(s.Chance) == "table" then
addRow(root, "Notes", table.concat(rec.Notes, "<br />"), "sv-row-meta", "Notes")
local t = valuePairDynamicValueOnly(s.Chance, maxLevel, level)
end
if t then table.insert(detail, "Chance: " .. t) end
end


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


----------------------------------------------------------------------
table.insert(parts, seg)
-- Public: list all skills for a given user/class
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)
function p.listForUser(frame)
local args = getArgs(frame)
local args = getArgs(frame)
 
 
local userName = args.user or args[1]
local userName = args.user or args[1]
if not userName or userName == "" then
if not userName or userName == "" then
userName = mw.title.getCurrentTitle().text
userName = mw.title.getCurrentTitle().text
end
end
 
 
if not userName or userName == "" then
if not userName or userName == "" then
return "<strong>No user name provided to Skill list.</strong>"
return "<strong>No user name provided to Skill list.</strong>"
end
end
 
 
local dataset = getSkills()
local dataset = getSkills()
local matches = {}
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 out = {}
 
for _, rec in ipairs(matches) do
local title = rec["External Name"] or rec.Name or rec["Internal Name"] or "Unknown Skill"


for _, rec in ipairs(dataset.records or {}) do
-- List mode: emit a raw H3 heading before each standalone card so TOC/anchors work.
if skillMatchesUser(rec, userName) then
table.insert(out, string.format("=== %s ===", title))
table.insert(matches, rec)
end
end


if #matches == 0 then
-- List mode cards are independent (no single wrapper container).
return string.format("<strong>No skills found for:</strong> %s", mw.text.nowiki(userName))
table.insert(out, buildInfobox(rec, { showUsers = false, inList = true }))
end
end


local root = mw.html.create("div")
return table.concat(out, "\n")
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
end



Latest revision as of 01:53, 20 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
Combo
Ready (4s)
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
No Special Mechanics
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
Combo
Ready (4s)
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
No Special Mechanics
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)
--
-- Layout (Module 1–8):
--   Row 1: Module 1 + Module 2   → Icon + Name, Skill Type strip
--   Row 2: Module 3 + Module 4   → Description (Module 3), open slot (Module 4)
--   Row 3: Module 5 + Module 6   → Source Types, Quick Stats
--   Row 4: Module 7 + Module 8   → Special Mechanics, Level Selector
--
-- 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

-- getSkills: lazy-load + cache skill dataset from GameData.
local function getSkills()
	if not skillsCache then
		skillsCache = GameData.loadSkills()
	end
	return skillsCache
end

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

-- getArgs: read args from parent frame when invoked from a template.
local function getArgs(frame)
	local parent = frame:getParent()
	return (parent and parent.args) or frame.args
end

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

-- toNum: convert common scalar/table forms to a Lua number.
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

-- clamp: clamp a number into [lo, hi].
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

-- fmtNum: consistent number formatting (trim trailing zeros).
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

-- listToText: join an array into a readable string.
local function listToText(list, sep)
	if type(list) ~= "table" or #list == 0 then
		return nil
	end
	return table.concat(list, sep or ", ")
end

-- isNoneLike: treat common "none" spellings as empty.
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

-- addRow: add a standard <tr><th>Label</th><td>Value</td></tr> row.
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

-- formatUnitValue: format {Value, Unit} blocks (or scalar) for display.
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)
----------------------------------------------------------------------

-- dynSpan: render a JS-updated span for a level series.
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

-- isFlatList: true if all values in list are identical.
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

-- isNonZeroScalar: detect if a value is present and not effectively zero.
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

-- isZeroish: aggressively treat common “zero” text forms as zero.
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

-- valuePairRawText: render Base/Per Level blocks into readable text (fallback).
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

-- valuePairDynamicValueOnly: render Base/Per Level blocks using dyn spans where possible.
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
----------------------------------------------------------------------

-- getSkillById: locate a skill by internal ID.
local function getSkillById(id)
	id = trim(id)
	if not id then return nil end
	local dataset = getSkills()
	return (dataset.byId or {})[id]
end

-- findSkillByName: locate a skill by external/display name.
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
----------------------------------------------------------------------

-- basisLabel: label ATK/MATK basis in legacy damage blocks.
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

-- formatDamageEntry: legacy percent damage formatting (dynamic by level).
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

-- formatDamageList: render a list of legacy damage entries into <br/> blocks.
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
----------------------------------------------------------------------

-- skillMatchesUser: check if a skill is used by a specific class/monster/summon/event.
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
----------------------------------------------------------------------

-- isDirectSkillPage: hide Users rows when viewing the skill page itself.
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)
----------------------------------------------------------------------

-- Module row order (see layout notes above).
local MODULE_SLOT_ASSIGNMENT = {
        [1] = "IconName",
        [2] = "SkillType", -- Damage/Element/Hits/Target/Cast/Combo strip
        [3] = "Description",
        [4] = nil, -- placeholder / intentionally open
        [5] = "SourceType",
        [6] = "QuickStats",
        [7] = "SpecialMechanics",
        [8] = "LevelSelector",
}

local MODULE_GRID_PAIRS = {
        { 3, 4 },
        { 5, 6 },
        { 7, 8 },
}

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

-- heroBarBox: wrapper for hero-bar slot modules.
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:addClass("sv-module-slot")
        box:addClass("sv-module-slot-" .. tostring(slot))
        box:attr("data-hero-bar-module", tostring(slot))
        box:attr("data-module-slot", tostring(slot))

	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

-- moduleBox: wrapper for hero-module (2x2 grid) slot modules.
local function moduleBox(slot, extraClasses, innerHtml, isEmpty)
        local box = mw.html.create("div")
        box:addClass("hero-module")
        box:addClass("hero-module-" .. tostring(slot))
        box:addClass("sv-module-slot")
        box:addClass("sv-module-slot-" .. tostring(slot))
        box:attr("data-hero-module", tostring(slot))
        box:attr("data-module-slot", 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)
----------------------------------------------------------------------

-- formatScalingCompactLines: build compact “Scaling” lines for SourceType.
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

-- basisWordFromFlags: compute “Attack/Magic/Hybrid” from ATK/MATK booleans.
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

-- legacyPercentAtLevel: compute “Base% + PerLevel%*level” for legacy entries.
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

-- seriesFromValuePair: normalize Base/Per Level blocks into a level-indexed series.
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

-- displayFromSeries: render a series as fixed text or dynSpan (nil if all “—”).
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

-- formatAreaSize: human readable area sizing for QuickStats.
-- Shows: "<Area Size> (<number>)" e.g. "Medium (4)"
local function formatAreaSize(area, maxLevel, level)
	if type(area) ~= "table" then
		return nil
	end

	-- Helper: pull a number from scalar/unit/valuepair-ish things.
	local function extractNumber(v)
		if v == nil then return nil end

		-- Unit block {Value, Unit}
		if type(v) == "table" and v.Value ~= nil then
			local n = toNum(v.Value)
			return n
		end

		-- ValuePair {Base, Per Level} -> prefer Base at current level if series exists
		if type(v) == "table" and (v.Base ~= nil or v["Per Level"] ~= nil) then
			local s = seriesFromValuePair(v, maxLevel or 1)
			if type(s) == "table" and #s > 0 then
				local idx = clamp(level or 1, 1, #s)
				local txt = s[idx]
				if txt and txt ~= "—" then
					-- try parse numeric from string (e.g. "4 tiles" -> 4)
					local num = tonumber((mw.ustring.gsub(tostring(txt), "[^0-9%.%-]", "")))
					return num
				end
			end
			return nil
		end

		-- Plain scalar
		if type(v) == "number" then return v end
		if type(v) == "string" then
			local num = tonumber((mw.ustring.gsub(mw.text.trim(v), "[^0-9%.%-]", "")))
			return num
		end

		return nil
	end

	-- 1) Read Area Size label/name
	local rawSize = area["Area Size"]
	if rawSize == nil then
		return nil
	end

	local sizeName = nil
	if type(rawSize) == "table" then
		sizeName = rawSize.Name or rawSize.ID or rawSize.Value
	elseif type(rawSize) == "string" then
		sizeName = rawSize
	elseif type(rawSize) == "number" then
		-- uncommon; treat as numeric-only label
		sizeName = tostring(rawSize)
	end

	sizeName = sizeName and mw.text.trim(tostring(sizeName)) or nil
	if not sizeName or sizeName == "" or isNoneLike(sizeName) then
		return nil
	end

	-- 2) Find the numeric “exact number” to append
	-- Prefer the explicit Area Distance block, then fall back to other known numeric keys.
	local num = nil

	local dist = area["Area Distance"]
	if type(dist) == "table" then
		-- Prefer Effective Distance if present and non-zero, else Base
		num = extractNumber(dist["Effective Distance"]) or extractNumber(dist.Effective) or extractNumber(dist["Effective"])
		if not num or num == 0 then
			num = extractNumber(dist.Base) or extractNumber(dist["Base"])
		end
	end

	if not num or num == 0 then
		num =
			extractNumber(area["Area Value"]) or
			extractNumber(area["Area Size Value"]) or
			extractNumber(area["Area Number"]) or
			extractNumber(area["Area Radius"])
	end

	-- 3) Render
	-- If size already contains parentheses, assume it already includes the numeric.
	if mw.ustring.find(sizeName, "%(") then
		return mw.text.nowiki(sizeName)
	end

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

	return mw.text.nowiki(sizeName)
end

-- skillHasAnyDamage: determine if a skill has any meaningful damage (for non-damaging rules).
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

-- computeDurationPromotion: promote status-duration into QuickStats when a skill is non-damaging.
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 = {}

-- PLUGIN: IconName (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

-- PLUGIN: SkillType (Hero Bar Slot 2) - 2 rows x 3 cells (desktop + mobile).
-- Rules:
--   - If skill is non-damaging, hide Damage/Element/Hits.
--   - If Hits is empty, hide Hits.
--   - If Combo is empty, hide Combo.
-- Ordering:
--   - Desktop: Damage, Element, Hits, Target, Cast, Combo
--   - Mobile:  Damage, Element, Target, Cast, Hits, Combo (CSS reorder)
function PLUGINS.SkillType(rec, ctx)
	local typeBlock = (type(rec.Type) == "table") and rec.Type or {}
	local mech      = (type(rec.Mechanics) == "table") and rec.Mechanics or {}

	local level    = ctx.level or 1
	local maxLevel = ctx.maxLevel or 1

	local hideDamageBundle = (ctx.nonDamaging == true)

	-- valName: extract a display string from typical {Name/ID/Value} objects.
	-- NOTE: Includes number support so Hits=2 (number) doesn't get dropped.
	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) == "number" then
			return tostring(x)
		end
		if type(x) == "string" and x ~= "" then
			return x
		end
		return nil
	end

	-- hitsDisplay: find + render Hits from multiple possible structured locations.
	local function hitsDisplay()
		local effects = (type(mech.Effects) == "table") and mech.Effects or {}

		local h =
			typeBlock.Hits or typeBlock["Hits"] or typeBlock["Hit Count"] or typeBlock["Hits Count"] or
			mech.Hits or mech["Hits"] or mech["Hit Count"] or mech["Hits Count"] or
			effects.Hits or effects["Hits"] or effects["Hit Count"] or effects["Hits Count"] or
			rec.Hits or rec["Hits"]

		if h == nil or isNoneLike(h) then
			return nil
		end

		-- ValuePair-style table (Base/Per Level) => dynamic series
		if type(h) == "table" then
			if h.Base ~= nil or h["Per Level"] ~= nil or type(h["Per Level"]) == "table" then
				return displayFromSeries(seriesFromValuePair(h, maxLevel), level)
			end

			-- Unit block {Value, Unit}
			if h.Value ~= nil then
				local t = formatUnitValue(h)
				return t and mw.text.nowiki(t) or nil
			end

			-- Fallback name extraction
			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) == "number" then return tostring(x) end
				if type(x) == "string" and x ~= "" then return x end
				return nil
			end

			local vn = valName(h)
			if vn and not isNoneLike(vn) then
				return mw.text.nowiki(vn)
			end
		end

		-- Scalar number/string
		if type(h) == "number" then
			return mw.text.nowiki(fmtNum(h))
		end
		if type(h) == "string" then
			local t = trim(h)
			return (t and not isNoneLike(t)) and mw.text.nowiki(t) or nil
		end

		return nil
	end

	-- comboDisplay: render Combo as a compact text block (Type (+ details)).
	local function comboDisplay()
		local c = (type(mech.Combo) == "table") and mech.Combo or nil
		if not c then return nil end

		local typ = trim(c.Type)
		if not typ or isNoneLike(typ) then
			return nil
		end

		local details = {}

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

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

		if #details > 0 then
			return mw.text.nowiki(typ) .. " (" .. table.concat(details, ", ") .. ")"
		end
		return mw.text.nowiki(typ)
	end

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

	local added = false

	-- addChunk: add one labeled value cell (key drives CSS ordering).
	local function addChunk(key, label, valueHtml)
		if valueHtml == nil or valueHtml == "" then return end
		added = true

		local chunk = grid:tag("div")
			:addClass("sv-type-chunk")
			:addClass("sv-type-" .. tostring(key))
			:attr("data-type-key", tostring(key))

		chunk:tag("div")
			:addClass("sv-type-label")
			:wikitext(mw.text.nowiki(label))

		chunk:tag("div")
			:addClass("sv-type-value")
			:wikitext(valueHtml)
	end

	-- Damage + Element + Hits bundle (hidden when non-damaging)
	if not hideDamageBundle then
		local dmg  = valName(typeBlock.Damage or typeBlock["Damage Type"])
		local ele  = valName(typeBlock.Element or typeBlock["Element Type"])
		local hits = hitsDisplay()

		if dmg and not isNoneLike(dmg) then
			addChunk("damage", "Damage", mw.text.nowiki(dmg))
		end
		if ele and not isNoneLike(ele) then
			addChunk("element", "Element", mw.text.nowiki(ele))
		end
		if hits then
			addChunk("hits", "Hits", hits)
		end
	end

	-- Target + Cast
	local tgt = valName(typeBlock.Target or typeBlock["Target Type"])
	local cst = valName(typeBlock.Cast   or typeBlock["Cast Type"])

	if tgt and not isNoneLike(tgt) then
		addChunk("target", "Target", mw.text.nowiki(tgt))
	end
	if cst and not isNoneLike(cst) then
		addChunk("cast", "Cast", mw.text.nowiki(cst))
	end

	-- Combo
	local combo = comboDisplay()
	if combo then
		addChunk("combo", "Combo", combo)
	end

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

function PLUGINS.Description(rec, ctx)
        local desc = trim(rec.Description)
        if not desc then
                return nil
        end

        local wrapper = mw.html.create("div")
        wrapper:addClass("sv-module-description")
        wrapper:wikitext(string.format("''%s''", desc))

        return {
                inner = tostring(wrapper),
                classes = "module-description",
        }
end

-- PLUGIN: SourceType (Hero Module Slot 1) - 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

	-- sourceValueForLevel: dynamic formatting for structured Source blocks.
	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

-- PLUGIN: QuickStats (Hero Module Slot 2) - 3x2 grid (range/area/cost/cast/cd/duration).
-- NOTE: Hits does NOT live here (it lives in SkillType).
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, maxLevel, level)

	-- 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

-- PLUGIN: SpecialMechanics (Hero Module Slot 3)
-- Shows:
--   - Flags (deduped)
--   - Special mechanics (mech.Effects)
-- NOTE: Combo lives in SkillType (Hero Bar Slot 2).
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 mods    = (type(rec.Modifiers) == "table") and rec.Modifiers or nil

	------------------------------------------------------------------
	-- Hits guard (we want Hits ONLY in SkillType)
	------------------------------------------------------------------
	local function isHitsKey(name)
		if not name then return false end
		local k = mw.ustring.lower(mw.text.trim(tostring(name)))
		return (
			k == "hit" or
			k == "hits" or
			k == "hit count" or
			k == "hits count" or
			k == "hitcount" or
			k == "hitscount"
		)
	end

	------------------------------------------------------------------
	-- Flags (flat, de-duped)
	------------------------------------------------------------------
	local flagSet = {}

	local denyFlags = {
		["self centered"] = true,
		["self-centred"] = true,
		["bond"] = true,
		["combo"] = true,
        ["hybrid"] = true,

		-- hits variants
		["hit"] = true,
		["hits"] = true,
		["hit count"] = true,
		["hits count"] = true,
		["hitcount"] = true,
		["hitscount"] = true,
	}

	local function allowFlag(name)
		if not name then return false end
		local k = mw.ustring.lower(mw.text.trim(tostring(name)))
		if k == "" then return false end
		if denyFlags[k] then return false end
		return true
	end

	local function addFlags(sub)
		if type(sub) ~= "table" then return end
		for k, v in pairs(sub) do
			if v and allowFlag(k) 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 and allowFlag(k) then
				flagSet[tostring(k)] = true
			end
		end
	end

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

	------------------------------------------------------------------
	-- Special mechanics (name => value)
	------------------------------------------------------------------
	local mechItems = {}

	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
			-- Skip Hits completely (it belongs in SkillType)
			if not isHitsKey(name) then
				local block = effects[name]
				if type(block) == "table" then
					-- Also skip if the block's Type is "Hits" (some data may encode it that way)
					if not isHitsKey(block.Type) then
						local disp = displayFromSeries(seriesFromValuePair(block, maxLevel), level)
						local t = trim(block.Type)

						local value = disp

						-- If Type exists and is distinct, prefix it.
						if t and not isNoneLike(t) and mw.ustring.lower(t) ~= mw.ustring.lower(tostring(name)) then
							if value then
								value = mw.text.nowiki(t) .. ": " .. value
							else
								value = mw.text.nowiki(t)
							end
						end

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

	local hasFlags = (#flags > 0)
	local hasMech  = (#mechItems > 0)

	if (not hasFlags) and (not hasMech) then
		local root = mw.html.create("div")
		root:addClass("sv-sm-root")
		root:addClass("sv-compact-root")
		root:tag("div"):addClass("sv-sm-empty"):wikitext("No Special Mechanics")

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

	local count = 0
	if hasFlags then count = count + 1 end
	if hasMech  then count = count + 1 end

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

	local layout = root:tag("div"):addClass("sv-sm-layout")
	layout:addClass("sv-sm-count-" .. tostring(count))

	-- Column 1: Flags
	if hasFlags then
		local fcol = layout:tag("div"):addClass("sv-sm-col"):addClass("sv-sm-col-flags")
		for _, f in ipairs(flags) do
			fcol:tag("div"):addClass("sv-sm-flag"):wikitext(mw.text.nowiki(f))
		end
	end

	-- Column 2: Special Mechanics (stacked)
	if hasMech then
		local mcol = layout:tag("div"):addClass("sv-sm-col"):addClass("sv-sm-col-mech")
		for _, it in ipairs(mechItems) do
			local one = mcol:tag("div"):addClass("sv-sm-mech")
			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
	end

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

-- PLUGIN: LevelSelector (Hero Module Slot 4) - JS level slider.
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

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

-- normalizeResult: normalize plugin return values into {inner, classes}.
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

-- safeCallPlugin: pcall wrapper to prevent infobox failure on plugin errors.
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

-- renderHeroBarSlot: render a hero-bar slot by plugin assignment.
local function renderHeroBarSlot(slotIndex, rec, ctx)
        local pluginName = MODULE_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

-- isEmptyModuleContent: true when a module slot has no meaningful content.
local function isEmptyModuleContent(inner)
        if inner == nil then return true end

        local asString = tostring(inner)

        if mw.ustring.find(asString, "sv%-dyn") or mw.ustring.find(asString, "data%-series") then
                return false
        end

        local trimmed = mw.text.trim(asString)
        if trimmed == "" or trimmed == "—" then
                return true
        end

        local withoutTags = mw.text.trim(mw.ustring.gsub(trimmed, "<[^>]+>", ""))
        return (withoutTags == "" or withoutTags == "—")
end

-- mergeClasses: merge string/table classes with an optional extra class.
local function mergeClasses(base, extra)
        local list = {}

        local function add(item)
                if type(item) == "string" then
                        for cls in mw.ustring.gmatch(item, "[^%s]+") do
                                table.insert(list, cls)
                        end
                elseif type(item) == "table" then
                        for _, c in ipairs(item) do
                                add(c)
                        end
                end
        end

        add(base)
        add(extra)

        if #list == 0 then
                return nil
        elseif #list == 1 then
                return list[1]
        end

        return list
end

-- renderModuleSlot: render a hero-module slot by plugin assignment.
local function renderModuleSlot(slotIndex, rec, ctx)
        local pluginName = MODULE_SLOT_ASSIGNMENT[slotIndex]
        if not pluginName then
                return nil
        end

        local res = safeCallPlugin(pluginName, rec, ctx)
        if not res or isEmptyModuleContent(res.inner) then
                return nil
        end

        return {
                inner = res.inner,
                classes = res.classes,
        }
end

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

-- buildHeroBarUI: build the top hero bar (2 slots).
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

-- buildModuleGridUI: build the lower module rows (Modules 3–8, 3 rows).
local function buildModuleGridUI(rec, ctx)
        local grid = mw.html.create("div")
        grid:addClass("hero-modules-grid")
        grid:addClass("sv-modules-grid")

        local slots = {}
        for _, pair in ipairs(MODULE_GRID_PAIRS) do
                for _, slot in ipairs(pair) do
                        slots[slot] = renderModuleSlot(slot, rec, ctx)
                end
        end

        local hasModules = false
        for _, pair in ipairs(MODULE_GRID_PAIRS) do
                local left  = slots[pair[1]]
                local right = slots[pair[2]]

                if left or right then
                        if left and right then
                                grid:wikitext(moduleBox(pair[1], left.classes, left.inner, false))
                                grid:wikitext(moduleBox(pair[2], right.classes, right.inner, false))
                        elseif left then
                                grid:wikitext(moduleBox(pair[1], mergeClasses(left.classes, "hero-module-full"), left.inner, false))
                        elseif right then
                                grid:wikitext(moduleBox(pair[2], mergeClasses(right.classes, "hero-module-full"), right.inner, false))
                        end

                        hasModules = true
                end
        end

        if not hasModules then
                return ""
        end

        return tostring(grid)
end

-- addModuleGridRow: add the lower module grid into the infobox table.
local function addModuleGridRow(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
----------------------------------------------------------------------

-- buildInfobox: render a single skill infobox.
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/Hits 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

        -- Module 1–2 (Icon + Skill Type)
        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))

        -- Module grid (rows 2–4)
        addModuleGridRow(root, buildModuleGridUI(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)
	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
	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 out = {}

	for _, rec in ipairs(matches) do
		local title = rec["External Name"] or rec.Name or rec["Internal Name"] or "Unknown Skill"

		-- List mode: emit a raw H3 heading before each standalone card so TOC/anchors work.
		table.insert(out, string.format("=== %s ===", title))

		-- List mode cards are independent (no single wrapper container).
		table.insert(out, buildInfobox(rec, { showUsers = false, inList = true }))
	end

	return table.concat(out, "\n")
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