Vés al contingut

Mòdul:Infotaula animanga

De Viki.cat



local p = {}

----------------------------------------------------------
-- REQUERIMENTS I CONSTANTS
----------------------------------------------------------

local wikidades = require("Mòdul:Wikidades")
local getArgs = require("Mòdul:Arguments").getArgs

local qid_labels = {
    publicacio   = "Q732577",
    estrena      = "Q204854",
    emissio      = "Q109507868",
    distribuidor = "Q12540664",
    genere       = "Q483394",
    revista      = "Q41298",
}

----------------------------------------------------------
-- FUNCIONS BÀSIQUES
----------------------------------------------------------

local function formatarData(iso)
    if not iso or iso == "" then return "" end
    local clean = iso:match("^%+?(%d%d%d%d%-%d%d%-%d%d)")
    if not clean then return iso end

    local any, m, d = clean:match("^(%d+)%-(%d+)%-(%d+)")
    if not any then return iso end

    local lang = mw.language.getContentLanguage()

    if m == "00" then return any end
    if d == "00" then
        local fake = any .. "-" .. m .. "-01"
        return lang:formatDate("F Y", fake)
    end

    return lang:formatDate("j F Y", clean)
end

local function netejaNomFitxer(raw)
    local nom = tostring(raw):gsub("[%[%]]",""):gsub("^[Ff]it[xz]er:",""):gsub("^[Ff]ile:","")
    if nom:find("|") then nom = nom:match("^([^|]+)") or nom end
    return nom
end

local function midaImatge(nom, max_w, max_h)
    local ext = nom:lower()
    if ext:match("%.svg$") or ext:match("%.gif$") then
        return max_w .. "px"
    else
        return max_w .. "x" .. max_h .. "px"
    end
end

local function obtenirImatge(item_id, args, prop, param)
    prop = prop or "P18"
    param = param or "imatge"

    if args[param] == "NONE" then
        return { nom = nil, peu = nil }
    end

    if args[param] and args[param] ~= "" then
        return { nom = netejaNomFitxer(args[param]), peu = args["peu"] or nil }
    end

    local raw = wikidades.claim{
        item = item_id, property = prop,
        formatting = "raw", list = false
    }

    if not raw or raw == "" then
        return { nom = nil, peu = nil }
    end

    local nom = netejaNomFitxer(raw)
    local peu = args["peu"]

    if not peu or peu == "" then
        local raw_caption = wikidades.claim{
            item = item_id, property = prop,
            qualifier = "P2096", formatting = "raw", list = false
        }
        if raw_caption and raw_caption ~= "" then peu = raw_caption end
    end

    return { nom = nom, peu = peu }
end

----------------------------------------------------------
-- ICONES EXTERNES
----------------------------------------------------------

local function getIconaPropieta(prop)
    local entity = mw.wikibase.getEntity(prop)
    if not entity or not entity.claims then return nil end

    local function millor_claim(prop_id)
        local claims = entity.claims[prop_id]
        if not claims then return nil end

        local preferent, normal = nil, nil

        for _, claim in ipairs(claims) do
            local rank = claim.rank
            local val  = claim.mainsnak.datavalue
                         and claim.mainsnak.datavalue.value
            local nom = val and (type(val)=="string" and val or val.text or val.id)

            if nom and nom ~= "" then
                if rank=="preferred" and not preferent then preferent = nom
                elseif rank=="normal" and not normal then normal = nom end
            end
        end

        return preferent or normal
    end

    return millor_claim("P8972") or millor_claim("P2910")
end

local external_link_props = {
    "P1984", "P1985", "P4983", "P4947", "P345",
}

local function generarIconesExternes(item_id)
    local html = {}

    for _, prop in ipairs(external_link_props) do
        local val = wikidades.claim{
            item = item_id, property = prop,
            formatting = "raw", list = false
        }

        if val and val ~= "" then
            local formatter = wikidades.claim{
                item = prop, property = "P1630",
                formatting = "raw", list = false
            }
            local label = mw.wikibase.getLabel(prop) or prop
            local icon  = getIconaPropieta(prop)

            if formatter and formatter ~= "" and icon then
                local url = formatter:gsub("%$1", val)
                table.insert(html,
                    string.format(
                        '[[Fitxer:%s|middle|link=%s|class=notpageimage|%s]] ',
                        icon, url, label
                    )
                )
            end
        end
    end

    return table.concat(html, "")
end

----------------------------------------------------------
-- LABELS UNIFICATS (PUNT 1)
----------------------------------------------------------

local function getLabelData(qid)
    local label, lang = nil, nil

    for _, l in ipairs({"ca","mul","en","ja","ko","zh"}) do
        local t = mw.wikibase.getLabelByLang(qid, l)
        if t and t ~= "" then
            label = t
            lang = l
            break
        end
    end

    if not label then
        label = qid
        lang = nil
    end

    return label, lang
end

local function wdLink(qid, label_override)
    if label_override and label_override ~= "" then
        return "[[d:" .. qid .. "|" .. label_override .. "]]"
    end

    local label, lang = getLabelData(qid)
    local sitelink = wikidades.getSiteLink{qid}

    local link = sitelink
        and ("[[" .. sitelink .. "|" .. label .. "]]")
        or  ("[[d:" .. qid .. "|" .. label .. "]]")

    if lang and lang ~= "ca" and lang ~= "mul" then
        link = link
            .. " <sup>(" .. lang .. ")</sup>"
            .. " [[Fitxer:Noun Project label icon 1116097 cc mirror.svg|10px|baseline|class=skin-invert|"
            .. mw.message.new("Translate-taction-translate"):inLanguage("ca"):plain()
            .. "|link=https://www.wikidata.org/wiki/" .. qid .. "?uselang=ca]]"
    end

    return link
end

----------------------------------------------------------
-- CLAIMS UNIFICATS (PUNT 1)
----------------------------------------------------------

local function getClaims(item_id, prop_id, only_qids)
    if not item_id then return {} end

    local raw = wikidades.claim{
        item = item_id,
        property = prop_id,
        formatting = "raw",
        list = true,
        separator = "/·/"
    }

    if not raw or raw == "" then return {} end

    local result = {}

    for v in raw:gmatch("[^/·/]+") do
        if only_qids then
            local q = v:match("^(Q%d+)$")
            if q then table.insert(result, q) end
        else
            if v:match("^Q%d+$") then
                table.insert(result, wdLink(v))
            else
                table.insert(result, v)
            end
        end
    end

    return result
end


----------------------------------------------------------
-- NETEJA DE GÈNERE UNIFICADA (PUNT 1)
----------------------------------------------------------

local APO = "['’`´ʼ‛]"

local GEN_PREFIX = {
    "^manga i anime%s+d" .. APO .. "%s*",
    "^anime i manga%s+d" .. APO .. "%s*",
    "^manga%s+d" .. APO .. "%s*",
    "^anime%s+d" .. APO .. "%s*",
    "^manga i anime%s+de%s+",
    "^anime i manga%s+de%s+",
    "^manga%s+de%s+",
    "^anime%s+de%s+",
    "^manga i anime%s+",
    "^anime i manga%s+",
    "^manga%s+",
    "^anime%s+",
}

local function netejarGenere(label)
    local lower = label:lower()

    for _, pat in ipairs(GEN_PREFIX) do
        local resta = lower:gsub(pat, "")
        if resta ~= lower then
            label = label:gsub(pat, "")
            break
        end
    end

    label = label:gsub("%s*%b()", "")
    label = label:gsub("^d[^a-zà-üA-ZÀ-Ü]+", "")
    label = label:gsub("%s+$", "")

    return label:sub(1,1):upper() .. label:sub(2)
end

----------------------------------------------------------
-- TIPUS I MAPES
----------------------------------------------------------

local tipus_def = {
    ["Curtmetratge"]                  = { mode = "pelicula",    qids = { "Q24862" } },
    ["Franquícia"]                    = { mode = "franquicia",  qids = { "Q196600" } },
    ["Sèrie cinematogràfica d'anime"] = { mode = "pelicula",    qids = { "Q29982285" } },
    ["Curtmetratge animat"]           = { mode = "pelicula",    qids = { "Q17517379" } },
    ["Vídeo musical"]                 = { mode = "audiovisual", qids = { "Q193977", "Q55960075", "Q64100970" } },
    ["Pel·lícula anime"]              = { mode = "pelicula",    qids = { "Q20650540" } },
    ["Sèrie cinematogràfica"]         = { mode = "pelicula",    qids = { "Q24856" } },
    ["Sèrie de videojocs"]            = { mode = "videojoc",    qids = { "Q7058673" } },
    ["Pel·lícula"]                    = { mode = "pelicula",    qids = { "Q229390", "Q11424" } },
    ["Pel·lícula d'animació"]         = { mode = "pelicula",    qids = { "Q29168811", "Q202866" } },
    ["Sèrie d'animació"]              = { mode = "audiovisual", qids = { "Q581714" } },
    ["Anime"]                         = { mode = "audiovisual", qids = { "Q63952888", "Q11086742", "Q100269041", "Q104640199" } },
    ["Radioteatre"]                   = { mode = "audiovisual", qids = { "Q2635894" } },
    ["OVA"]                           = { mode = "audiovisual", qids = { "Q220898" } },
    ["Sèrie OVA"]                     = { mode = "audiovisual", qids = { "Q113687694" } },
    ["Musical"]                       = { mode = "pelicula", 	qids = { "Q58483083" } }, --potser cridar infotaula arts escèniques, ara és pelicula per "estrena"
    ["One-shot"]                      = { mode = "llibre",      qids = { "Q933530", "Q21202185" } },
    ["OAD"]                           = { mode = "audiovisual", qids = { "oad" } },
    ["Sèrie ONA"]                     = { mode = "audiovisual", qids = { "Q113671041" } },
    ["ONA"]                           = { mode = "audiovisual", qids = { "Q1047299" } },
    ["Dorama"]                        = { mode = "audiovisual", qids = { "Q399811" } },
    ["Especial"]                      = { mode = "audiovisual", qids = { "Q1261214" } },
    ["Imatge en directe"]             = { mode = nil,           qids = { "live action" } },
    ["Novel·la visual"]               = { mode = "videojoc",    qids = { "Q689445" } },
    ["Joc"]                           = { mode = nil,           qids = { "Q11410" } },
    ["Novel·la"]                      = { mode = "llibre",      qids = { "Q747381" } },
    ["Sèrie de novel·les"]            = { mode = "llibre",      qids = { "Q104213567" } },
    ["Videojoc"]                      = { mode = "videojoc",    qids = { "Q7889" } },
    ["Dōjinshi"]                      = { mode = "llibre",      qids = { "Q668711" } },
    ["Sèrie manga"]                   = { mode = "llibre",      qids = { "Q21198342" } },
    ["Manga"]                         = { mode = "llibre",      qids = { "Q8274" } },
    ["Anunci"]                        = { mode = "audiovisual", qids = { "Q11796892", "Q854995" } },
    ["CD drama"]                      = { mode = "audiovisual", qids = { "Q244351" } },
    ["Pel·lícula de manga"]           = { mode = "pelicula",    qids = { "Q116790751" } },
    ["Còmic"]                         = { mode = "llibre",      qids = { "Q1004" } },
    ["Sèrie de TV"]                   = { mode = "audiovisual", qids = { "Q5398426", "Q21191019" } },
    ["Websèrie"]                      = { mode = "audiovisual", qids = { "Q526877" } },
    ["Webtoon"]                       = { mode = "llibre",      qids = { "Q7978994" } },
    ["Sèrie manhwa"]                  = { mode = "llibre",      qids = { "Q74262765" } },
    ["Manhua"]                        = { mode = "llibre",      qids = { "Q754669" } },
    ["Pel·lícula en directe"]         = { mode = "pelicula",    qids = { "pel·lícula live action" } },
    ["Novel·la lleugera"]             = { mode = "llibre",      qids = {} },
}

local tipus_map = {}
local tipus_a_mode = {}

for tipus, def in pairs(tipus_def) do
    tipus_a_mode[tipus] = def.mode
    for _, qid in ipairs(def.qids) do
        tipus_map[qid] = tipus
    end
end

local link_desti = {
    ["Sèrie manga"] = "Manga",
    ["Franquícia"] = "Franquícia de mitjans",
}

local function majusculaInicial(s)
    if not s or s == "" then return s end
    return mw.ustring.upper(mw.ustring.sub(s, 1, 1)) .. mw.ustring.sub(s, 2)
end

local function etiquetaProp(pid)
    local label = mw.wikibase.getLabel(pid)
    return majusculaInicial(label or "")
end

local function obtenirTipusText(tipus_param, item_id)
    local val = (tipus_param and tipus_param ~= "") and string.lower(tipus_param) or ""
    local map = tipus_map

    if val == "" and item_id then
        local ids = getClaims(item_id, "P31", true)
        if #ids == 0 then return "Altres" end
        local primer = ids[1]
        for _, id in ipairs(ids) do
            if map[id] then
                val = id
                break
            end
        end
        if val == "" then val = primer end
    end

    local function linkSiExisteix(t, desti)
        local target = desti or t
        local title = mw.title.new(target)
        if title and title.exists then return "[[" .. target .. "|" .. t .. "]]" end
        return t
    end

    if map[val] then
        return linkSiExisteix(map[val], link_desti[map[val]])
    end

    local label, _ = getLabelData(val)  
    return label and majusculaInicial(label) or "Altres"
end

local function netejarWikilink(text)
    return text
        :gsub("%[%[[^|]+|([^%]]+)%]%]", "%1")
        :gsub("%[%[([^%]]+)%]%]", "%1")
end

----------------------------------------------------------
-- UTILITATS DIVERSES
----------------------------------------------------------

local function linkEditicon(item_id)
    return "<span class='ita-edit-icon' style='margin-left:4px;'>[[Fitxer:OOjs UI icon edit-ltr-progressive.svg|middle|class=notpageimage|link=d:"
        .. item_id .. "|Edita a Wikidata]]</span>"
end

local function es_no_llati(s)
    local te_no_llati = mw.ustring.find(s, "[^A-Za-zÀ-ÖØ-öø-ÿĀ-ſ0-9%s%p]") ~= nil
    if te_no_llati then
        return "font-weight:normal;"
    else
        return "font-style:italic;"
    end
end

----------------------------------------------------------
-- TRANSLITERACIÓ (qualificadors de P1476)
----------------------------------------------------------

local PROPS_TRANSLIT = {
    "P2440", -- transliteració o transcripció (genèric)
    "P2125", -- Hepburn revisat (japonès)
    "P1942", -- McCune–Reischauer (coreà)
    "P2001", -- Romanització revisada (coreà)
    "P5139", -- Möllendorff (coreà)
    "P1721", -- Hanyu Pinyin (xinès)
}

local function obtenirTransliteracio(item_id)
    local entity = mw.wikibase.getEntity(item_id)
    if not entity or not entity.claims or not entity.claims.P1476 then return nil end

    for _, claim in ipairs(entity.claims.P1476) do
        if claim.qualifiers then
            for _, pid in ipairs(PROPS_TRANSLIT) do
                local quals = claim.qualifiers[pid]
                if quals then
                    for _, q in ipairs(quals) do
                        local val = q.datavalue and q.datavalue.value
                        if val then
                            local t = type(val) == "string" and val or val.text
                            if t and t ~= "" then return t end
                        end
                    end
                end
            end
        end
    end

    return nil
end

local function obtenirTitolOriginal(item_id, titol_catala, es_capcalera)
    if not item_id then return "" end

    local text = wikidades.claim{
        item       = item_id,
        property   = "P1476",
        formatting = "table",
        colformat0 = "text",
        list       = false,
        rowformat  = "$0",
        editicon   = false,
    }

    if not text or text == "" or text == titol_catala then
        return ""
    end

    local lang = wikidades.claim{
        item       = item_id,
        property   = "P1476",
        formatting = "$language",
        list       = false,
        editicon   = false,
    }

    if lang == "" then lang = nil end

    local estil_text = es_no_llati(text)

    local prefix_lang = ""
    if es_capcalera and lang then
        prefix_lang = "<sup><span style='font-weight:normal; font-style:normal;'>(" .. lang .. ")</span></sup> "
    end

local tooltip_html = ""
if estil_text == "font-weight:normal;" then
    local translit = obtenirTransliteracio(item_id)
    if translit then
        tooltip_html =
            '<span class="ita-translit-wrap" tabindex="0">' ..
            '<sup class="ita-translit-icon">ⓘ</sup>' ..
            '<span class="ita-translit-tip">' .. translit:gsub("'", "&#39;") .. '</span>' ..
            '</span>'
    end
end

return "<span style='font-size:90%; display:block;'>"
    .. prefix_lang
    .. "<span style='" .. estil_text .. "'>" .. text .. "</span>"
    .. tooltip_html
    .. "</span>"
end

local function obtenirDurada(item_id)
    local raw = wikidades.claim{
        item = item_id,
        property = "P2047",
        formatting = "raw",
        list = false
    }

    if not raw or raw == "" then return nil end

    local amount =
        raw:match('"amount"%s*:%s*"(%+?[%d%.%-]+)"') or
        raw:match('^%+?(%d+)$') or
        raw:match('(%d+)[^%d]*$')

    if not amount then return nil end
    amount = tonumber(amount)
    if not amount then return nil end

    local unit =
        raw:match('"unit"%s*:%s*"http://www%.wikidata%.org/entity/(Q%d+)"') or
        raw:match('"unit"%s*:%s*"(Q%d+)"')

    if not unit then
        return amount .. " min"
    end

    local unit_map = {
        Q7727  = "min",
        Q11574 = "s",
        Q23387 = "h",
        Q25235 = "dies"
    }

    local u = unit_map[unit]
    if not u then return amount end

    if u == "s" then
        amount = math.floor(amount / 60)
        u = "min"
    elseif u == "h" then
        amount = amount * 60
        u = "min"
    elseif u == "dies" then
        amount = amount * 24 * 60
        u = "min"
    end

    return amount .. " " .. u
end

local function obtenirDataOrdenacio(item_id)
    if not item_id then return "9999-99-99" end

    local function primera(prop_id)
        local raw = wikidades.claim{
            item = item_id,
            property = prop_id,
            formatting = "raw",
            list = true,
            separator = "/·/"
        }
        if not raw or raw == "" then return nil end

        local any, mes, dia = raw:match("%+(%d%d%d%d)%-(%d%d)%-(%d%d)T")
        if not any then return nil end

        if mes == "00" then mes = "01" end
        if dia == "00" then dia = "01" end

        return string.format("%s-%s-%s", any, mes, dia)
    end

    return primera("P580")
        or primera("P577")
        or primera("P571")
        or "9999-99-99"
end

local function getListSitelinkFromProp(item_id, prop_id)
    local qid = getClaims(item_id, prop_id, true)[1]
    if not qid then return "" end
    return wikidades.getSiteLink{qid} or ("d:" .. qid)
end

----------------------------------------------------------
-- EDITORIALS
----------------------------------------------------------

local function obtenirEditorialsWikibase(qid)
    local entity = mw.wikibase.getEntity(qid)
    if not entity or not entity.claims or not entity.claims.P123 or #entity.claims.P123 == 0 then
        return nil
    end

    local preferent
    local primer_trobat = nil
    local catalanes = {}

    for _, claim in ipairs(entity.claims.P123) do
        local ed_qid = claim.mainsnak.datavalue and claim.mainsnak.datavalue.value.id
        if ed_qid then
            local label = wdLink(ed_qid)

            local lang_label = nil
            local es_cat = false

            if claim.qualifiers and claim.qualifiers.P407 then
                for _, qv in ipairs(claim.qualifiers.P407) do
                    if qv.datavalue.value.id == "Q7026" then
                        es_cat = true
                        break
                    end
                end

                if es_cat then
                    lang_label, _ = getLabelData("Q7026")
                else
                    local qid_lang = claim.qualifiers.P407[1].datavalue.value.id
                    lang_label, _ = getLabelData(qid_lang)
                end
            end

            local text = label
            if lang_label then
                text = text .. " (" .. lang_label .. ")"   
            end

            if es_cat then
                table.insert(catalanes, text)
            else
                if not primer_trobat then primer_trobat = text end
                if claim.rank == "preferred" and not preferent then
                    preferent = text
                end
            end
        end
    end

    preferent = preferent or primer_trobat

    if not preferent and #catalanes == 0 then return nil end

    local resultat = {}
    if preferent then table.insert(resultat, preferent) end
    for _, c in ipairs(catalanes) do
        if c ~= preferent then table.insert(resultat, c) end
    end

    return table.concat(resultat, "<br />")
end

----------------------------------------------------------
-- FILTRAR PER P31
----------------------------------------------------------

local function filtrarPerP31(llista, qid_tipus)
    local coincideixen, resta = {}, {}

    for _, q in ipairs(llista) do
        local trobat = false
        for _, classe in ipairs(getClaims(q, "P31", true)) do
            if classe == qid_tipus then
                trobat = true
                break
            end
        end
        table.insert(trobat and coincideixen or resta, q)
    end

    return coincideixen, resta
end

----------------------------------------------------------
-- CSS
----------------------------------------------------------

local CSS = {
    HEADER    = "ita-header",
    SUBHEADER = "ita-subheader",
    TIPUS     = "ita-tipus",
    CELL_L    = "ita-cell-l",
    CELL_R    = "ita-cell-r",
    ICON_CELL = "ita-icon-cell",
    ICON_CELL_R = "ita-icon-cell-r",
    CELL_FULL = "ita-cell-full",
}

local function filaEtiquetaValor(contenidor, label, valor, collapsible)
    local fila = contenidor:tag("tr")
    if collapsible then
        fila:addClass("mw-collapsible-content")
    end
    fila:tag("td"):addClass(CSS.CELL_L):wikitext(label)
    fila:tag("td"):addClass(CSS.CELL_R):wikitext(valor)
    return fila
end


----------------------------------------------------------
-- GENERAR NUCLI (VERSIÓ COMPLETA, OPCIÓ B)
----------------------------------------------------------

local function generarNucli(item_id, args, es_grup, id_pare, te_genere_pare)
    if not item_id or not mw.wikibase.isValidEntityId(item_id) then
        return ""
    end

    local html = mw.html.create()

    ------------------------------------------------------
    -- NOM BASE + IDIOMA
    ------------------------------------------------------
    local nom_base, nom_base_lang = getLabelData(item_id)

    local ret_lang_subheader = ""
    local ret_icon_subheader = ""

    if nom_base_lang and nom_base_lang ~= "ca" and nom_base_lang ~= "mul" then
        ret_lang_subheader =
            " <span style='font-weight:normal'><sup>(" .. nom_base_lang .. ")</sup></span>"

        ret_icon_subheader =
            " [[Fitxer:Noun Project label icon 1116097 cc mirror.svg|10px|baseline|class=skin-invert|" ..
            mw.message.new("Translate-taction-translate"):inLanguage("ca"):plain() ..
            "|link=https://www.wikidata.org/wiki/" .. item_id .. "?uselang=ca]]"
    end

    ------------------------------------------------------
    -- TIPUS
    ------------------------------------------------------
    local tipus_text = obtenirTipusText(args.tipus, item_id)
    local tipus_net = netejarWikilink(tipus_text)

    local mode = tipus_a_mode[tipus_net] or ""

    ------------------------------------------------------
    -- SUBHEADER (si és grup)
    ------------------------------------------------------
    if es_grup then
        local estil_sub = es_no_llati(nom_base)
        local sitelink = wikidades.getSiteLink{item_id}

        local dest_link = sitelink
            and ("[[" .. sitelink .. "|" .. nom_base .. "]]")
            or  ("[[d:" .. item_id .. "|" .. nom_base .. "]]")

        local text =
            "<span style='" .. estil_sub .. "'>" .. dest_link .. "</span>" ..
            ret_lang_subheader ..
            ret_icon_subheader ..
            obtenirTitolOriginal(item_id, nom_base, false)

        local fila_sh = html:tag("tr")
        fila_sh:addClass("mw-collapsible-content")
        fila_sh:tag("td")
            :attr("colspan", "2")
            :addClass(CSS.SUBHEADER)
            :wikitext(text)
    end

------------------------------------------------------
-- FILA TIPUS + ICONES (VERSIÓ SENSE TAULA INTERNA)
------------------------------------------------------
local fila_tipus = html:tag("tr")
fila_tipus:addClass("mw-collapsible-content ita-row-tipus")

-- Cel·la esquerra (tipus)
fila_tipus:tag("td")
    :addClass(CSS.TIPUS)
    :wikitext(tipus_text)

local td_icones = fila_tipus:tag("td")
td_icones:addClass(CSS.CELL_R .. " ita-icons-flex")

local wrapper = td_icones:tag("div")
wrapper:addClass("ita-icons-wrapper")

local td_esq = wrapper:tag("div")
td_esq:addClass("ita-icons-left " .. CSS.ICON_CELL)

local td_dre = wrapper:tag("div")
td_dre:addClass("ita-icons-right " .. CSS.ICON_CELL_R)

    ------------------------------------------------------
    -- ETIQUETA PERÍODE (funció interna)
    ------------------------------------------------------
    local function _obtenirEtiquetaPeriode_local(qid, tipus_str)
        local t = mw.ustring.lower(tipus_str or "")
        local m = tipus_a_mode[majusculaInicial(t)] or ""

		if m == "franquicia" then
        	return etiquetaProp("P2348")
    	end

        if m == "llibre" or m == "videojoc" then
            return etiquetaProp(qid_labels.publicacio)
        end

        if m == "pelicula" then
            local te_p577 = wikidades.claim{item=qid, property="P577", list=false}
            local te_p582 = wikidades.claim{item=qid, property="P582", list=false}

            if te_p577 and te_p577 ~= "" then
                return etiquetaProp(qid_labels.estrena)
            elseif te_p582 and te_p582 ~= "" then
                return etiquetaProp(qid_labels.emissio)
            else
                return etiquetaProp(qid_labels.estrena)
            end
        end

        return etiquetaProp(qid_labels.emissio)
    end

------------------------------------------------------
    -- ICONA DURADA (P2047)
    ------------------------------------------------------
    local text_durada = obtenirDurada(item_id)
    if text_durada then
        td_esq:wikitext("[[file:Hourglass icon.png|middle|class=notpageimage|link=|Durada]] " .. text_durada .. " ")
    end

    ------------------------------------------------------
    -- ICONA DE LLISTA (P31)
    ------------------------------------------------------
    local p31_qid = getClaims(item_id, "P31", true)[1] or ""

    if p31_qid == "Q24856" or p31_qid == "Q7058673" or p31_qid == "Q29982285" then
        local link = getListSitelinkFromProp(item_id, "P2354")
        if link == "" then
            link = wikidades.getSiteLink{item_id} or ("d:" .. item_id)
        end
        td_esq:wikitext("[[file:Font Awesome 5 regular list-alt.svg|middle|class=notpageimage|link=" .. link .. "]] ")
    end

    ------------------------------------------------------
    -- ICONA VOLUMS / PEL·LÍCULES (P2635)
    ------------------------------------------------------
    local raw_volums = wikidades.claim{
        item = item_id,
        property = "P2635",
        formatting = "raw",
        list = false
    }

    if raw_volums and raw_volums ~= "" then
        local quant = tostring(raw_volums):gsub("%+","")
        if p31_qid == "Q29982285" then
            td_esq:wikitext(
                "[[file:Tabler-icons_movie.svg|middle|class=notpageimage|link=" ..
                getListSitelinkFromProp(item_id,"P2354") ..
                "|Pel·lícules]] " .. quant .. " pel·lícules "
            )
        else
            td_esq:wikitext(
                "[[file:OpenMoji-black 1F4DA.svg|middle|class=notpageimage|link=" ..
                getListSitelinkFromProp(item_id,"P2354") ..
                "|Volums]] " .. quant .. " vol. "
            )
        end
    end

    ------------------------------------------------------
    -- ICONA EPISODIS (P1113)
    ------------------------------------------------------
    local text_ep = ""
    local raw_ep = wikidades.claim{
        item = item_id,
        property = "P1113",
        formatting = "raw",
        list = false
    }

    if raw_ep and raw_ep ~= "" then
        text_ep = tostring(raw_ep):gsub("%+","")
    end

    if text_ep ~= "" then
        local link_ep = getListSitelinkFromProp(item_id,"P1811")
        if link_ep == "" then
            link_ep = getListSitelinkFromProp(item_id,"P2354")
        end

        td_esq:wikitext(
            "<span style='display:inline-block;width:1px;'></span>[[file:Noun TV Episodes 3303322.svg|middle|class=notpageimage|link=" ..
            link_ep .. "|Episodis]] " .. text_ep .. " "
        )
    end

    ------------------------------------------------------
    -- ICONES EXTERNES
    ------------------------------------------------------
    td_dre:wikitext(generarIconesExternes(item_id) .. linkEditicon(item_id))

    ------------------------------------------------------
    -- PROPIETATS SECUNDÀRIES (FILES NORMALS)
    ------------------------------------------------------
    local propietats = {
        "P144","P4970","P50","P110","P178","P58","P287","P86","P57","P162",
        "P136","P400","P272","P275","P449","P123","P2360","P1433"
    }

    for _, pid in ipairs(propietats) do
        local admetre = true

        if pid == "P144" then
            local qid_p144 = getClaims(item_id, "P144", true)[1]
            if qid_p144 and (qid_p144 == item_id or qid_p144 == id_pare) then
                admetre = false
            end
        end

        if pid == "P136" and es_grup and te_genere_pare then
            admetre = false
        end

        if admetre then
            local label = etiquetaProp(pid)

            if pid == "P123" and (mode == "videojoc" or mode == "audiovisual") then
                label = etiquetaProp(qid_labels.distribuidor)
            end

            if pid == "P272" and (mode == "pelicula" or mode == "audiovisual") then
                label = "Estudi"
            end

            if pid == "P2360" then
                label = "Demografia"
            end

            if pid == "P136" then
                label = etiquetaProp(qid_labels.genere)
            end

            if pid == "P1433" and (tipus_net == "Manga" or tipus_net == "Sèrie manga" or tipus_net == "One-shot") then
                label = etiquetaProp(qid_labels.revista)
            end

            if pid == "P449" and mode == "audiovisual" then
                label = "Canal"
            end

            --------------------------------------------------
            -- GÈNERE (neteja unificada)
            --------------------------------------------------
            if pid == "P136" then
                local valors = {}
                for i, qid in ipairs(getClaims(item_id, "P136", true)) do
                    local label_qid = getLabelData(qid)
                    local text_net = netejarGenere(label_qid)
                    if i > 1 then
                        text_net = text_net:sub(1,1):lower() .. text_net:sub(2)
                    end

                    local sitelink = wikidades.getSiteLink{qid}
                    if sitelink and sitelink ~= "" then
                        table.insert(valors, "[[" .. sitelink .. "|" .. text_net .. "]]")
                    else
                        table.insert(valors, "[[d:" .. qid .. "|" .. text_net .. "]]")
                    end
                end

                if #valors > 0 then
    			filaEtiquetaValor(html, label, '<span>' .. table.concat(valors, ", ") .. '</span>', true)
				end

            --------------------------------------------------
            -- EDITORIALS
            --------------------------------------------------
            elseif pid == "P123" then
                local valors = obtenirEditorialsWikibase(item_id)
                if valors then
    			filaEtiquetaValor(html, label, valors, true)
				end

            --------------------------------------------------
            -- ALTRES PROP.
            --------------------------------------------------
            else
                local valors = getClaims(item_id, pid, false)
                if valors and #valors > 0 then
    			filaEtiquetaValor(html, label, '<span>' .. table.concat(valors, ", ") .. '</span>', true)
				end
            end
        end
    end

    ------------------------------------------------------
    -- DATES (P580 / P577 / P582)
    ------------------------------------------------------
    local data_inici_p580 = getClaims(item_id, "P580", false)[1]

    if data_inici_p580 then
        local label_data = _obtenirEtiquetaPeriode_local(item_id, tipus_net)
        local data_fi = getClaims(item_id, "P582", false)[1]
        local text_data = formatarData(data_inici_p580)

        if data_fi then
            text_data = text_data .. " – " .. formatarData(data_fi)
        end

        filaEtiquetaValor(html, label_data, text_data, true)

else
        --------------------------------------------------
        -- CAS AMB P577 (pot tenir múltiples dates)
        --------------------------------------------------
        local entity = mw.wikibase.getEntity(item_id)
        local claims_p577 = entity and entity.claims and entity.claims.P577 or {}

        if #claims_p577 > 0 then
            local label_data = _obtenirEtiquetaPeriode_local(item_id, tipus_net)
            local linies = {}

            for _, claim in ipairs(claims_p577) do
                local dv = claim.mainsnak and claim.mainsnak.datavalue
                if dv then
                    local iso = dv.value and dv.value.time or ""
                    local data_fmt = formatarData(iso)
                    local quals = {}

                    if claim.qualifiers then
                        if claim.qualifiers.P291 then
                            for _, q in ipairs(claim.qualifiers.P291) do
                                local qid = q.datavalue and q.datavalue.value and q.datavalue.value.id
                                if qid then
                                    table.insert(quals, wdLink(qid))
                                end
                            end
                        end
                        if claim.qualifiers.P400 then
                            for _, q in ipairs(claim.qualifiers.P400) do
                                local qid = q.datavalue and q.datavalue.value and q.datavalue.value.id
                                if qid then
                                    table.insert(quals, wdLink(qid))
                                end
                            end
                        end
                    end

                    local linia = data_fmt
                    if #quals > 0 then
                        linia = linia .. " (" .. table.concat(quals, ", ") .. ")"
                    end

                    table.insert(linies, linia)
                end
            end

            if #linies > 0 then
                if #linies == 1 then
                    filaEtiquetaValor(html, label_data, linies[1], true)
                else
                    local ocultes = {}
                    for i = 2, #linies do
                        table.insert(ocultes, linies[i])
                    end

                    local text_final =
                        '<table class="mw-collapsible mw-collapsed" style="width:100%; border-spacing:0;">' ..
                        '<tr><th colspan="2" style="text-align:left; font-weight:normal;">' .. linies[1] .. '</th></tr>' ..
                        '<tr><td>' .. table.concat(ocultes, "<br>") .. '</td></tr>' ..
                        '</table>'

                    filaEtiquetaValor(html, label_data, text_final, true)
                end
            end
        end
    end

	    ------------------------------------------------------
    -- RETORNAR EL RESULTAT
    ------------------------------------------------------
    return tostring(html)
end


----------------------------------------------------------
-- p.infotaula
----------------------------------------------------------

local LIMIT_VISIBLE = 4

function p.infotaula(frame)
    local args = getArgs(frame, {wrappers = "Plantilla:Infotaula animanga"})
    local item_id = (args.item and args.item ~= "") and args.item
        or mw.wikibase.getEntityIdForCurrentPage()

    if not item_id then
        return "<span class='error'>Error: No s'ha trobat cap element de Wikidata vinculat.</span>"
    end

    ---------------------------------------------------------
    -- SELECCIONATS
    ---------------------------------------------------------
    local seleccionats_raw = args.seleccionats or ""
    local seleccionats = {}
    if seleccionats_raw ~= "" then
        for qid in seleccionats_raw:gmatch("Q%d+") do
            seleccionats[qid] = true
        end
    end

    ---------------------------------------------------------
    -- DELEGACIÓ SI NO ÉS GRUP / FRANQUÍCIA
    ---------------------------------------------------------
    local parts = getClaims(item_id, "P527", true)
    local derivades = getClaims(item_id, "P4969", true)

    if #parts == 0 and #derivades == 0 then
        local tipus = netejarWikilink(obtenirTipusText(args.tipus, item_id))
		local mode = tipus_a_mode[tipus]

        if mode == "pelicula" then
            return frame:expandTemplate{
                title = "infotaula de pel·lícula",
                args = { item = item_id, nom = args.nom }
            }

        elseif mode == "llibre" then
            return frame:expandTemplate{
                title = "Infotaula llibre",
                args = { item = item_id, titol = args.nom, manga = "y" }
            }

        elseif mode == "videojoc" then
            return frame:expandTemplate{
                title = "Infotaula videojoc",
                args = { item = item_id, nom = args.nom }
            }

        elseif mode == "audiovisual" then
            return frame:expandTemplate{
                title = "Infotaula programa audiovisual",
                args = { item = item_id, nom = args.nom }
            }
        end
    end

    ---------------------------------------------------------
    -- MODE FRANQUÍCIA
    ---------------------------------------------------------
    local res = mw.html.create("table")
        :addClass("infobox")
        :addClass("infotaula-animanga")

    local titol = args.nom
        or getLabelData(item_id)
        or mw.title.getCurrentTitle().text

res:tag("caption")
    :addClass(CSS.HEADER)
    :wikitext(
        '<div style="display:flex; align-items:center;">' ..
        '<div style="flex:0 0 30px; min-width:30px;">' ..
        '<span style="position:relative; left:2px;">[[Fitxer:Anime manga japanese characters icon.svg|30px|Infotaula animanga|class=skin-invert notpageimage]]</span>' ..
        '</div>' ..
        '<div style="flex:1 1 auto;">' ..
        '<span style="font-weight:bold; font-style:italic;">' .. titol .. '</span>' ..
        obtenirTitolOriginal(item_id, titol, true) ..
        '</div>' ..
        '<div style="flex:0 0 30px; min-width:30px;"></div>' ..
        '</div>'
    )

---------------------------------------------------------
-- IMATGE PRINCIPAL (amb fallback a logo P154)
---------------------------------------------------------
local img = obtenirImatge(item_id, args, "P18", "imatge")
local logo = obtenirImatge(item_id, args, "P154", "logo")

local mostrar_logo_apart = true

if img.nom then
    local mida = midaImatge(img.nom, 250, 350)
    local td_img = res:tag("tr"):tag("td")
        :attr("colspan","2")
		:addClass("ita-img-cell")

    td_img:wikitext("[[Fitxer:" .. img.nom .. "|" .. mida .. "|center]]")

    if img.peu and img.peu ~= "" then
        td_img:tag("span")
            :addClass("ita-img-caption")
            :wikitext(img.peu)
    end

elseif logo.nom then
    -- Fallback: no hi ha P18, però sí P154 → l'usem com a imatge principal
    local mida = midaImatge(logo.nom, 250, 250)
    res:tag("tr"):tag("td")
        :attr("colspan","2")
        :addClass("ita-img-cell")
        :wikitext("[[Fitxer:" .. logo.nom .. "|" .. mida .. "|center]]")

    mostrar_logo_apart = false

else
    res:wikitext("[[Categoria:Articles manganime que necessiten una imatge]]")
end

---------------------------------------------------------
-- LOGO (P154) — només si NO s'ha usat ja com a fallback
---------------------------------------------------------
if logo.nom and mostrar_logo_apart then
    local mida = midaImatge(logo.nom, 250, 250)
    res:tag("tr"):tag("td")
        :attr("colspan","2")
        :addClass("ita-img-cell")
        :wikitext("[[Fitxer:" .. logo.nom .. "|" .. mida .. "|center]]")
end

    ---------------------------------------------------------
    -- NUCLI PRINCIPAL DEL PARE
    ---------------------------------------------------------
    local pare_te_genere = (#getClaims(item_id, "P136", true) > 0)

    res:wikitext(generarNucli(item_id, args, false, item_id, false))

    ---------------------------------------------------------
    -- FORMAT PER (P527)
    ---------------------------------------------------------
    local elements_valids = {}
    local exclos_p527 = {
        Q125632018=true, Q3464665=true,
        Q102364578=true, Q21191270=true
    }

    for _, tid in ipairs(parts) do
        if next(seleccionats) ~= nil and not seleccionats[tid] then
            -- exclòs per selecció
        else
            local exclos = false
            for _, p31id in ipairs(getClaims(tid, "P31", true)) do
                if exclos_p527[p31id] then
                    exclos = true
                    break
                end
            end
            if not exclos then
                table.insert(elements_valids, tid)
            end
        end
    end

    table.sort(elements_valids, function(a,b)
        return obtenirDataOrdenacio(a) < obtenirDataOrdenacio(b)
    end)

    ---------------------------------------------------------
    -- ARCS NARRATIUS (Q2620972)
    ---------------------------------------------------------
    local arcs_narratius
    arcs_narratius, elements_valids = filtrarPerP31(elements_valids, "Q2620972")

    ---------------------------------------------------------
    -- ARTICLES DE LLISTA (Q13406463) dins P527
    ---------------------------------------------------------
    local llistes_p527
    llistes_p527, elements_valids = filtrarPerP31(elements_valids, "Q13406463")

    ---------------------------------------------------------
    -- OBRA DERIVADA (P4969)
    ---------------------------------------------------------
    local ids_der_raw = derivades

    local ids_der_filtrats = {}
    for _, tid in ipairs(ids_der_raw) do
        if next(seleccionats) == nil or seleccionats[tid] then
            table.insert(ids_der_filtrats, tid)
        end
    end

    local llistes_der, ids_der = filtrarPerP31(ids_der_filtrats, "Q13406463")

    table.sort(ids_der, function(a,b)
        return obtenirDataOrdenacio(a) < obtenirDataOrdenacio(b)
    end)

    ---------------------------------------------------------
    -- ARCS NARRATIUS (render)
    ---------------------------------------------------------
    if #arcs_narratius > 0 then
        res:tag("tr"):tag("td")
            :attr("colspan", "2")
            :addClass(CSS.SUBHEADER)
            :wikitext(majusculaInicial(getLabelData("Q2620972")) .. linkEditicon(item_id))

        local td_llista = res:tag("tr"):tag("td")
            :attr("colspan", "2")
        local ul = td_llista:tag("ul")

        for _, q in ipairs(arcs_narratius) do
            local nom = getLabelData(q)
            ul:tag("li"):wikitext(wdLink(q, nom))
        end
    end

---------------------------------------------------------
    -- FUNCIONS AUXILIARS PER LLISTES
    ---------------------------------------------------------
    local function mostrarLlistes(llistes, contenidor)
        for _, q_llista in ipairs(llistes) do
            local nom_llista = getLabelData(q_llista)

            contenidor:tag("tr"):tag("td")
                :attr("colspan", "2")
                :addClass(CSS.SUBHEADER)
                :wikitext(majusculaInicial(nom_llista) .. " " .. linkEditicon(q_llista))

            local membres = getClaims(q_llista, "P527", true)
            if #membres > 0 then
                if #membres > 5 then
                    -- Llista desplegable
                    local taula_col = contenidor:tag("tr"):tag("td")
    :attr("colspan","2")
    :addClass("ita-mes-td")
    :tag("table")
        :addClass("mw-collapsible mw-collapsed ita-mes-collapsible")

taula_col:tag("tr"):tag("th")
    :attr("colspan","2")
    :addClass(CSS.SUBHEADER)
    :wikitext(tostring(#membres) .. " elements")

local ul_membres = taula_col:tag("tr"):tag("td")
    :attr("colspan","2")
    :tag("ul")

                    for _, m in ipairs(membres) do
                        ul_membres:tag("li"):wikitext(wdLink(m))
                    end
                else
                    local ul_membres = contenidor:tag("tr"):tag("td")
                        :attr("colspan", "2")
                        :tag("ul")

                    for _, m in ipairs(membres) do
                        ul_membres:tag("li"):wikitext(wdLink(m))
                    end
                end
            end
        end
    end

---------------------------------------------------------
-- MOSTRAR FORMAT PER + OBRA DERIVADA (amb límit)
---------------------------------------------------------
local total = #elements_valids + #ids_der

if total > LIMIT_VISIBLE then
    local visibles_p527 = math.min(#elements_valids, LIMIT_VISIBLE)
    local visibles_der  = math.min(#ids_der, math.max(0, LIMIT_VISIBLE - visibles_p527))

    -----------------------------------------------------
    -- PRIMERA PART: ELEMENTS VISIBLES NORMALS
    -----------------------------------------------------
    if visibles_p527 > 0 then
        res:tag("tr"):tag("td")
            :attr("colspan","2")
            :addClass(CSS.SUBHEADER)
            :wikitext(etiquetaProp("P527"))

        for i = 1, visibles_p527 do
            res:wikitext(generarNucli(elements_valids[i], {}, true, item_id, pare_te_genere))
        end
    end

    mostrarLlistes(llistes_p527, res)

    if visibles_der > 0 then
        res:tag("tr"):tag("td")
            :attr("colspan","2")
            :addClass(CSS.SUBHEADER)
            :wikitext("Obres derivades")

        for i = 1, visibles_der do
            res:wikitext(generarNucli(ids_der[i], {}, true, item_id, pare_te_genere))
        end
    end

    mostrarLlistes(llistes_der, res)

---------------------------------------------------------
-- BLOC PLEGABLE "MÉS" (contenidor taula necessari)
---------------------------------------------------------
local taula_col = res:tag("tr"):tag("td")
    :attr("colspan","2")
	:addClass("ita-mes-td")
    :tag("table")
        :addClass("mw-collapsible mw-collapsed ita-mes-collapsible")

-- capçalera "Més"
taula_col:tag("tr"):tag("th")
    :attr("colspan","2")
    :addClass(CSS.SUBHEADER)
    :wikitext('<span class="ita-mes-text">Més</span>')

local resta_p527 = visibles_p527 < #elements_valids
local resta_der  = visibles_der  < #ids_der
local ambdues    = resta_p527 and resta_der

---------------------------------------------------------
-- CONTINGUT PLEGABLE: P527
---------------------------------------------------------
if resta_p527 then
    if ambdues then
        taula_col:tag("tr"):tag("td")
            :attr("colspan","2")
            :addClass(CSS.SUBHEADER)
            :wikitext(etiquetaProp("P527"))
    end

    for i = visibles_p527 + 1, #elements_valids do
        taula_col:wikitext(generarNucli(elements_valids[i], {}, true, item_id, pare_te_genere))
    end
end

---------------------------------------------------------
-- CONTINGUT PLEGABLE: OBRES DERIVADES
---------------------------------------------------------
if resta_der then
    if ambdues then
        taula_col:tag("tr"):tag("td")
            :attr("colspan","2")
            :addClass(CSS.SUBHEADER)
            :wikitext("Obres derivades")
    end

    for i = visibles_der + 1, #ids_der do
        taula_col:wikitext(generarNucli(ids_der[i], {}, true, item_id, pare_te_genere))
    end
end


else
    -----------------------------------------------------
    -- CAS SENSE PLEGABLE
    -----------------------------------------------------
    if #elements_valids > 0 then
        res:tag("tr"):tag("td")
            :attr("colspan","2")
            :addClass(CSS.SUBHEADER)
            :wikitext(etiquetaProp("P527"))

        for _, tid in ipairs(elements_valids) do
            res:wikitext(generarNucli(tid, {}, true, item_id, pare_te_genere))
        end
    end

    mostrarLlistes(llistes_p527, res)

    if #ids_der > 0 then
        res:tag("tr"):tag("td")
            :attr("colspan","2")
            :addClass(CSS.SUBHEADER)
            :wikitext("Obres derivades")

        for _, tid in ipairs(ids_der) do
            res:wikitext(generarNucli(tid, {}, true, item_id, pare_te_genere))
        end
    end

    mostrarLlistes(llistes_der, res)
end


---------------------------------------------------------
-- ALTRES (P5940)
---------------------------------------------------------
local ids_p5940 = getClaims(item_id, "P5940", true)

if #ids_p5940 > 0 then
    -- Capçalera "Altres"
    res:tag("tr"):tag("td")
        :attr("colspan","2")
        :addClass(CSS.SUBHEADER)
        :wikitext("Altres")

    -- Obtenim l'entitat UNA sola vegada
    local entity = mw.wikibase.getEntity(item_id)
    local claims_p5940 = entity and entity.claims and entity.claims.P5940 or {}

    -- Indexem els claims per QID per evitar bucles interns
    local claims_index = {}
    for _, claim in ipairs(claims_p5940) do
        local snak = claim.mainsnak
        local q = snak and snak.datavalue and snak.datavalue.value and snak.datavalue.value.id
        if q then
            claims_index[q] = claim
        end
    end

    -- Construïm la llista i la mostrem en punts
    local td_llista = res:tag("tr"):tag("td")
        :attr("colspan", "2")
    local ul = td_llista:tag("ul")

    for _, qid in ipairs(ids_p5940) do
        local text = wdLink(qid)
        local claim = claims_index[qid]

        if claim and claim.qualifiers and claim.qualifiers.P3831 then
            local qual = claim.qualifiers.P3831[1]
            local q_val = qual.datavalue and qual.datavalue.value and qual.datavalue.value.id
            if q_val then
                text = text .. " (" .. wdLink(q_val) .. ")"
            end
        end

        ul:tag("li"):wikitext(text)
    end
end

    ---------------------------------------------------------
    -- PORTAL
    ---------------------------------------------------------
    local portal_val = args.portal or ""

    if portal_val ~= "" and portal_val:lower() ~= "no" then
        local portal_expandit = frame:preprocess(
            "[[Fitxer:Wikipe-tan face.svg|16px||class=notpageimage|link=Portal:Anime i Manga|Portal Anime i Manga]] " ..
            "[[Portal:Anime i Manga|Portal Anime i Manga]]"
        )

        res:tag("tr"):tag("td")
            :attr("colspan","2")
			:addClass(CSS.SUBHEADER)
            :addClass(CSS.CELL_FULL)
            :wikitext(portal_expandit)
    end

    ---------------------------------------------------------
    -- ESTILS
    ---------------------------------------------------------
    local styles = frame:extensionTag("templatestyles", "", {src="Mòdul:Infotaula animanga/estils.css"})
    return styles .. tostring(res)
end

return p