메뉴 여닫기
환경 설정 메뉴 여닫기
개인 메뉴 여닫기
로그인하지 않음
만약 지금 편집한다면 당신의 IP 주소가 공개될 수 있습니다.

💬 같이 떠들 사람? 노바위키 디스코드

모듈:요약정보

노바위키

이 모듈에 대한 설명문서는 모듈:요약정보/설명문서에서 만들 수 있습니다

local p = {}

local VISIBLE_FIELDS = 5
local DEFAULT_IMAGE_SIZE = 350

-- 그림이 있을 때 먼저 보여 줄 항목 수를 그림 높이에 맞춘다 (값은 화면 어림치)
local ROW_HEIGHT = 39               -- 정보 항목 한 줄 높이(px)
local IMAGE_BOX_WIDTH = 300         -- 데스크탑 그림 칸에서 그림이 실제로 차지하는 너비(px)
local MAX_IMAGE_HEIGHT = 250        -- 그림 최대 높이(px), getImageMarkup의 x250px와 같음
local IMAGE_PADDING = 25            -- 그림 칸 위아래 여백(px)
local CAPTION_HEIGHT = 22           -- 그림 설명 한 줄(px)
local MAX_VISIBLE_WITH_IMAGE = 10
local FOLD_MIN_EXTRA = 3            -- 접기에 남는 항목이 이보다 적으면 접지 않고 다 보여 줌

local function clean(value)
    if value == nil then
        return nil
    end

    value = mw.text.trim(tostring(value))

    if value == '' then
        return nil
    end

    return value
end


local TITLE_KEYS = {
    '제목', '이름', '작품명'
}

local ENGLISH_KEYS = {
    '영문 제목', '영문제목',
    '영문 이름', '영문이름',
    '영문명', '영제'
}

local ORIGINAL_KEYS = {
    '원제', '원어 제목', '원어제목', '원어'
}

local SUBTITLE_KEYS = {
    '부제', '부제목'
}

local IMAGE_CONFIG = {
    {
        keys = {
            '그림1', '이미지1', '사진1', '그림 1',
            '이미지 1', '사진 1', '로고', '사진',
            '이미지', '포스터', '표지'
        },
        sizes = {
            '그림1 크기', '그림1크기', '그림크기1', '그림 1 크기',
            '그림 1크기', '이미지1 크기', '이미지1크기', '이미지크기1',
            '이미지 1 크기', '이미지 1크기', '사진1 크기', '사진1크기',
            '사진크기1', '사진 1 크기', '사진 1크기', '로고 크기',
            '로고크기', '사진 크기', '사진크기', '이미지 크기',
            '이미지크기', '포스터 크기', '포스터크기', '표지 크기',
            '표지크기'
        },
        captions = {
            '그림1 설명', '그림1설명', '그림설명1', '그림 1 설명',
            '그림 1설명', '이미지1 설명', '이미지1설명', '이미지설명1',
            '이미지 1 설명', '이미지 1설명', '사진1 설명', '사진1설명',
            '사진설명1', '사진 1 설명', '사진 1설명', '로고 설명',
            '로고설명', '사진 설명', '사진설명', '이미지 설명',
            '이미지설명', '포스터 설명', '포스터설명', '표지 설명',
            '표지설명'
        }
    },
    {
        keys = {
            '그림2', '이미지2', '사진2', '그림 2',
            '이미지 2', '사진 2', '워드마크'
        },
        sizes = {
            '그림2 크기', '그림2크기', '그림크기2', '그림 2 크기',
            '그림 2크기', '이미지2 크기', '이미지2크기', '이미지크기2',
            '이미지 2 크기', '이미지 2크기', '사진2 크기', '사진2크기',
            '사진크기2', '사진 2 크기', '사진 2크기', '워드마크 크기',
            '워드마크크기'
        },
        captions = {
            '그림2 설명', '그림2설명', '그림설명2', '그림 2 설명',
            '그림 2설명', '이미지2 설명', '이미지2설명', '이미지설명2',
            '이미지 2 설명', '이미지 2설명', '사진2 설명', '사진2설명',
            '사진설명2', '사진 2 설명', '사진 2설명', '워드마크 설명',
            '워드마크설명'
        }
    },
    {
        keys = {
            '그림3', '이미지3', '사진3', '그림 3',
            '이미지 3', '사진 3', '그림'
        },
        sizes = {
            '그림3 크기', '그림3크기', '그림크기3', '그림 3 크기',
            '그림 3크기', '이미지3 크기', '이미지3크기', '이미지크기3',
            '이미지 3 크기', '이미지 3크기', '사진3 크기', '사진3크기',
            '사진크기3', '사진 3 크기', '사진 3크기', '그림 크기',
            '그림크기'
        },
        captions = {
            '그림3 설명', '그림3설명', '그림설명3', '그림 3 설명',
            '그림 3설명', '이미지3 설명', '이미지3설명', '이미지설명3',
            '이미지 3 설명', '이미지 3설명', '사진3 설명', '사진3설명',
            '사진설명3', '사진 3 설명', '사진 3설명', '그림 설명',
            '그림설명'
        }
    }
}

local IMAGE_ALIAS_OPTIONS = {
    ['로고'] = {
        sizes = {'로고크기', '로고 크기'},
        captions = {'로고설명', '로고 설명'},
        defaultSize = 150
    },
    ['워드마크'] = {
        sizes = {'워드마크 크기', '워드마크크기'},
        captions = {'워드마크설명', '워드마크 설명'},
        defaultSize = 300
    },
    ['그림'] = {
        defaultSize = 300
    },
    ['사진'] = {
        sizes = {'사진 크기', '사진크기'},
        captions = {'사진 설명', '사진설명'},
        defaultSize = 400
    },
    ['이미지'] = {
        sizes = {'이미지 크기', '이미지크기'},
        captions = {'이미지 설명', '이미지설명'}
    },
    ['포스터'] = {
        sizes = {'포스터 크기', '포스터크기'},
        captions = {'포스터 설명', '포스터설명'}
    },
    ['표지'] = {
        sizes = {'표지 크기', '표지크기'},
        captions = {'표지 설명', '표지설명'}
    }
}

local CONTROL_KEYS = {
    '항목순서',
    '틀',
    '글씨색상코드',
    '배경색상코드',
    '표배경색',
    '표글씨색',
    '테두리색',
    '제목배경색',
    '제목배경그라데이션',
    '제목글씨색',
    '항목배경색',
    '항목글씨색',
    '값배경색',
    '값글씨색',
    '이미지배경색',
    '이미지글씨색',
    '추가정보배경색',
    '추가정보글씨색',
    '하단배경색',
    '하단글씨색',
    '전체폭항목수',
    '전체폭항목'
}

local reserved = {}

local function reserve(keys)
    if not keys then
        return
    end

    for _, key in ipairs(keys) do
        reserved[key] = true
    end
end

reserve(TITLE_KEYS)
reserve(ENGLISH_KEYS)
reserve(ORIGINAL_KEYS)
reserve(SUBTITLE_KEYS)
reserve(CONTROL_KEYS)

-- 역 문서에서 별도로 한 행에 묶어 출력하는 항목
reserve({'이전역', '다음역'})

for _, config in ipairs(IMAGE_CONFIG) do
    reserve(config.keys)
    reserve(config.sizes)
    reserve(config.captions)
end

for _, options in pairs(IMAGE_ALIAS_OPTIONS) do
    reserve(options.sizes)
    reserve(options.captions)
end

local preferredOrder = {
    '국가', '국적', '제작 국가', '언어',
    '형태', '종류', '분류', '장르',

    '설립일', '창립', '창립일',
    '창립자', '설립 근거',

    '본명', '출생명', '일본어 이름',
    '생년월일', '출생일', '사망일',
    '나이', '출생지', '사망지', '거주지',

    '대표자', '핵심 인물', '인물',
    '본사', '본사 소재지', '소재지',
    '장소', '본사 우편번호',
    '사업 지역', '지사 수',

    '약칭', '별명', '이전 상호',
    '전신', '후신', '이전 회사', '이후 회사',

    '산업', '산업 분야', '사업 내용',
    '서비스', '제품', '대표 제품',

    '신장', '체중', '혈액형',
    '가문', '본관', '학력',
    '직업', '종교', '취미', '경력', '소속',

    '원작', '원작자', '감독', '연출',
    '각본', '극본', '저자', '작가',
    '글', '작화', '삽화', '번역', '역자',

    '주연', '출연', '배우', '담당 배우',
    '성우', '담당 성우',

    '음악', '촬영', '편집',
    '제작', '제작자', '제작사',
    '배급사', '출판사', '발행처',
    '방송사', '플랫폼', '개발사', '유통사',

    '개봉일', '공개일', '출간일',
    '발행일', '발매일', '출시일',
    '첫 방영', '방영일', '방영 기간',
    '연재 기간', '연재처',

    '상영 시간', '러닝타임', '방영 시간',
    '화수', '총 화수', '권수', '총 권수',
    '분량', '페이지', '관람 등급', '이용 등급',

    '데뷔', '활동기간', '음악장르',

    '제작비', '제작 예산', '흥행 수익',
    '누적관객수', '월드와이드',
    '판매량', 'ISBN',

    '티커 심볼', '시장 정보', '상장일',
    '자본금', '매출액', '영업이익',
    '영업 이익', '순이익', '순자산',
    '자산총액', '자산 총액', '주요 주주',
    '주주', '발행주식총수', '결산기',
    '모기업', '자회사', '주요 자회사',
    '계열사', '종업원', '종업원 수',
    '직원 수', '해체', '분할',

    '시리즈', '전작', '후속작',

    '팬클럽', '팬페이지', 'SNS',

    '국왕', '대통령', '총리', '원내대표',
    '정당', '정당 연합', '표방이념',

    '슬로건', '공식 사이트',
    '웹사이트', '사이트', '링크',
    '비고', '각주'
}

local function getArgs(frame)
    local parent = frame:getParent()
    local source = parent and parent.args or frame.args
    local args = {}

    for key, value in pairs(source) do
        local normalizedValue = clean(value)

        if normalizedValue then
            if type(key) == 'number' then
                args[key] = normalizedValue
            elseif type(key) == 'string' then
                local normalizedKey = clean(key)

                if normalizedKey then
                    local numericKey = tonumber(normalizedKey)

                    if numericKey
                        and numericKey >= 1
                        and numericKey <= 13
                        and numericKey == math.floor(numericKey)
                    then
                        args[numericKey] = normalizedValue
                    else
                        args[normalizedKey] = normalizedValue
                    end
                end
            end
        end
    end

    return args
end

local function pick(args, keys)
    if not keys then
        return nil
    end

    for _, key in ipairs(keys) do
        if args[key] then
            return args[key]
        end
    end

    return nil
end

local function pickWithKey(args, keys)
    for _, key in ipairs(keys) do
        if args[key] then
            return args[key], key
        end
    end

    return nil, nil
end

local function addSuffixIfNumber(value, suffix)
    if not value then
        return nil
    end

    if value:match('^[%d,%s%.]+$') then
        return value .. suffix
    end

    return value
end

local function addDollarIfNumber(value)
    if not value then
        return nil
    end

    if value:match('^[%d,%s%.]+$') then
        return '$' .. value
    end

    return value
end

local function normalizeColor(value)
    if not value then
        return nil
    end

    if value:match('^%x%x%x$')
        or value:match('^%x%x%x%x%x%x$')
    then
        return '#' .. value
    end

    return value
end

local function applyColor(element, property, value)
    value = normalizeColor(value)

    if value then
        element:css(property, value)
    end

    return element
end

local function contrastTextColor(value)
    if not value then
        return nil
    end

    local hex = value:match('^#(%x%x%x%x%x%x)$')

    if not hex then
        local short = value:match('^#(%x%x%x)$')

        if short then
            hex = short:sub(1, 1):rep(2)
                .. short:sub(2, 2):rep(2)
                .. short:sub(3, 3):rep(2)
        end
    end

    if not hex then
        return nil
    end

    local red = tonumber(hex:sub(1, 2), 16)
    local green = tonumber(hex:sub(3, 4), 16)
    local blue = tonumber(hex:sub(5, 6), 16)

    local brightness =
        (red * 299 + green * 587 + blue * 114) / 1000

    if brightness < 150 then
        return '#FFFFFF'
    end

    return '#202122'
end

local function adaptLegacyFilm(args)
    -- 위치 매개변수가 3개 이상일 때만 구형 영화 틀로 본다.
    -- '=' 를 빠뜨린 줄 하나 때문에 영화 분류가 붙는 것을 막는다.
    local positional = 0

    for index = 1, 13 do
        if args[index] then
            positional = positional + 1
        end
    end

    if positional < 3 then
        return false
    end

    local function setIfMissing(key, value)
        if value and not args[key] then
            args[key] = value
        end
    end

    setIfMissing('그림1', args[1])
    setIfMissing('그림1 크기', args[2])
    setIfMissing('제목', args[3])
    setIfMissing('원제', args[4])
    setIfMissing('장르', args[5])
    setIfMissing('감독', args[6])
    setIfMissing('주연', args[7])

    if not args['상영 시간'] and not args['러닝타임'] then
        setIfMissing(
            '상영 시간',
            addSuffixIfNumber(args[8], '분')
        )
    end

    setIfMissing('개봉일', args[9])
    setIfMissing('제작사', args[10])

    setIfMissing(
        '누적관객수',
        addSuffixIfNumber(args[11], '명')
    )

    setIfMissing(
        '월드와이드',
        addDollarIfNumber(args[12])
    )

    if args[13]
        and not args['제목배경색']
        and not args['배경색상코드']
    then
        local color = normalizeColor(args[13])
        args['제목배경색'] = color

        if not args['제목글씨색']
            and not args['글씨색상코드']
        then
            args['제목글씨색'] =
                contrastTextColor(color)
        end
    end

    return true
end

local function normalizeImageSize(value, defaultSize)
    defaultSize = defaultSize or DEFAULT_IMAGE_SIZE

    if not value then
        return tostring(defaultSize) .. 'px'
    end

    local number = value:match('^(%d+)%s*px$')
        or value:match('^(%d+)$')

    number = tonumber(number)

    if not number then
        return tostring(defaultSize) .. 'px'
    end

    number = math.max(80, math.min(number, 600))

    return tostring(number) .. 'px'
end

local function plainText(value)
    if not value then
        return ''
    end

    value = mw.text.killMarkers(value)
        :gsub('%[%[[^%]|]*|', '')
        :gsub('[%[%]|=<>{}\'"]', '')

    return mw.text.trim(value)
end

local function getImageMarkup(filename, size, altText)
    if not filename then
        return nil
    end

    if filename:match('^%[%[') then
        return filename
    end

    filename = filename
        :gsub('^파일:', '')
        :gsub('^그림:', '')
        :gsub('^[Ff]ile:', '')
        :gsub('^[Ii]mage:', '')

    -- MediaWiki의 폭 x 높이 옵션으로 CSS 미적용 시에도 250px 높이를 보장한다.
    local width = size:match('^(%d+)px$') or tostring(DEFAULT_IMAGE_SIZE)
    local alt = plainText(altText)
    local markup = '[[파일:' .. filename .. '|' .. width .. 'x250px'

    if alt ~= '' then
        markup = markup .. '|alt=' .. alt
    end

    return markup .. ']]'
end

local function getImages(args)
    local images = {}

    for index, config in ipairs(IMAGE_CONFIG) do
        local filename, selectedKey = pickWithKey(
            args,
            config.keys
        )

        if filename then
            local options =
                IMAGE_ALIAS_OPTIONS[selectedKey] or {}

            local size =
                pick(args, config.sizes)
                or pick(args, options.sizes)

            local caption =
                pick(args, config.captions)
                or pick(args, options.captions)

            if
                index == 1
                and selectedKey ~= '로고'
                and not args['그림']
                and not pick(args, IMAGE_CONFIG[3].keys)
            then
                if not size then
                    size = pick(args, {
                        '그림 크기',
                        '그림크기'
                    })
                end

                if not caption then
                    caption = pick(args, {
                        '그림 설명',
                        '그림설명'
                    })
                end
            end

            images[#images + 1] = {
                index = index,
                filename = filename,
                size = normalizeImageSize(
                    size,
                    options.defaultSize
                ),
                caption = caption
            }
        end
    end

    return images
end

local function getFields(args)
    local fields = {}
    local used = {}

    local function addField(key)
        if
            not reserved[key]
            and args[key]
            and not used[key]
        then
            fields[#fields + 1] = {
                name = key,
                value = args[key]
            }

            used[key] = true
        end
    end

    local customOrder = args['항목순서']

    if customOrder then
        for key in mw.text.gsplit(
            customOrder,
            ',',
            true
        ) do
            key = clean(key)

            if key then
                addField(key)
            end
        end
    end

    for _, key in ipairs(preferredOrder) do
        addField(key)
    end

    local remaining = {}

    for key, _ in pairs(args) do
        if type(key) == 'string'
            and not reserved[key]
            and not used[key]
        then
            remaining[#remaining + 1] = key
        end
    end

    table.sort(remaining)

    for _, key in ipairs(remaining) do
        addField(key)
    end

    return fields
end

-- 가로형 정보상자용 단일 정보 항목: 항목명과 값의 기존 색상 규칙 유지
local function addFieldCard(target, item, args, wide)
    local card = target:tag('div')
        :addClass('nw-summary-field')
        :css('display', 'flex')
        :css('width', '100%')
        :css('min-width', '0')
        :css('box-sizing', 'border-box')
        :css('border-bottom', '1px solid var(--border-color-base,#A2A9B1)')

    if wide then
        card:addClass('nw-summary-field-wide')
        -- CSS를 읽지 못할 경우에도 가로폭 전체를 차지한다.
        card:css('flex', '1 1 100%')
    else
        -- 별칭없는 일반 항목은 한 줄에 최대 두 쌍을 배치한다.
        card:css('flex', '1 1 45%')
            :css('min-width', 'min(450px,100%)')
    end

    local label = card:tag('div')
        :addClass('nw-summary-label')
        :css('flex', wide and '0 0 18%' or '0 0 30%')
        :css('min-width', '0')
        :css('box-sizing', 'border-box')
        :css('padding', '0.55em 0.65em')
        :css('font-size', '90%')
        :css('font-weight', 'bold')
        :css('line-height', '1.5')
        :css('text-align', 'center')
        :css('overflow-wrap', 'anywhere')
        :css('border-right', '1px solid var(--border-color-base,#A2A9B1)')
        :css('background-color', 'var(--color-surface-2,var(--background-color-interactive-subtle,#EAECF0))')
        :wikitext(item.name)

    applyColor(label, 'background-color', args['항목배경색'])
    applyColor(label, 'color', args['항목글씨색'])
    applyColor(label, 'border-color', args['테두리색'])

    local value = card:tag('div')
        :addClass('nw-summary-value')
        :css('flex', '1 1 0')
        :css('min-width', '0')
        :css('box-sizing', 'border-box')
        :css('padding', '0.55em 0.65em')
        :css('font-size', '90%')
        :css('line-height', '1.5')
        :css('text-align', 'left')
        :css('overflow-wrap', 'anywhere')
        :wikitext(item.value)

    applyColor(value, 'background-color', args['값배경색'])
    applyColor(value, 'color', args['값글씨색'])
    applyColor(value, 'border-color', args['테두리색'])
end

-- 사진이 없는 데스크탑에서 첫 몇 개 항목만 전체폭으로 배치한다.
local function getFullWidthOptions(args)
    local count = tonumber(args['전체폭항목수']) or 3
    count = math.max(0, math.min(VISIBLE_FIELDS, math.floor(count)))

    local named = {}
    if args['전체폭항목'] then
        for name in mw.text.gsplit(args['전체폭항목'], ',', true) do
            name = clean(name)
            if name then
                named[name] = true
            end
        end
    end

    return count, named
end

-- 전체폭 항목 사이에 낀 일반 항목 묶음마다 홀짝을 따져,
-- 홀수 묶음의 마지막 항목을 전체폭으로 넓혀 반쪽짜리 칸이 남지 않게 한다.
local function computeWide(fields, fromIndex, toIndex, paired,
    firstWideCount, namedWide)
    local wide = {}

    if not paired then
        return wide
    end

    local runLength = 0
    local lastOrdinary = nil

    for index = fromIndex, toIndex do
        if index <= firstWideCount or namedWide[fields[index].name] then
            if runLength % 2 == 1 then
                wide[lastOrdinary] = true
            end

            runLength = 0
            wide[index] = true
        else
            runLength = runLength + 1
            lastOrdinary = index
        end
    end

    if runLength % 2 == 1 then
        wide[lastOrdinary] = true
    end

    return wide
end

local function addFieldCards(target, fields, fromIndex, toIndex, args,
    paired, firstWideCount, namedWide)
    local grid = target:tag('div')
        :addClass('nw-summary-fields')
        -- #css 없이도 데스크탑 4열/모바일 2열로 동작하는 보조 배치.
        :css('display', paired and 'flex' or 'block')
        :css('flex-wrap', 'wrap')
        :css('width', '100%')
        :css('min-width', '0')

    if paired then
        grid:addClass('nw-summary-fields-paired')
    end

    local wideMap = computeWide(
        fields, fromIndex, toIndex, paired,
        firstWideCount or 0, namedWide or {}
    )

    for index = fromIndex, toIndex do
        addFieldCard(grid, fields[index], args, wideMap[index] == true)
    end
end

-- 역 문서의 이전역과 다음역을 정보상자 하단 한 행에 함께 표시한다.
-- 모바일에서도 두 역을 숨기지 않으며 기존의 일반 정보 5개 접힘 기준은 유지한다.
local function addAdjacentStations(root, args)
    local previousStation = args['이전역']
    local nextStation = args['다음역']

    if not previousStation and not nextStation then
        return
    end

    local borderColor = args['테두리색']
        or 'var(--border-color-base,#A2A9B1)'
    local labelBackground = args['항목배경색']
        or 'var(--color-surface-2,var(--background-color-interactive-subtle,#EAECF0))'

    local cell = root:tag('tr')
        :addClass('nw-summary-station-row')
        :tag('td')
        :attr('colspan', '2')
        :addClass('nw-summary-station-cell')
        :css('padding', '0')
        :css('border-color', borderColor)

    applyColor(cell, 'background-color', args['값배경색'])

    local grid = cell:tag('div')
        :addClass('nw-summary-station-grid')
        :css('display', 'grid')
        :css('grid-template-columns', 'minmax(0,1fr) minmax(0,1fr)')
        :css('width', '100%')
        :css('box-sizing', 'border-box')

    local function addStation(labelText, stationText, isLeft)
        local panel = grid:tag('div')
            :addClass('nw-summary-station-panel')
            :css('min-width', '0')
            :css('box-sizing', 'border-box')
            :css('text-align', 'center')
            :css('white-space', 'normal')

        if isLeft then
            panel:css('border-right', '1px solid ' .. borderColor)
        end

        local label = panel:tag('div')
            :addClass('nw-summary-station-label')
            :css('padding', '0.4em 0.45em')
            :css('background-color', labelBackground)
            :css('font-size', '90%')
            :css('font-weight', 'bold')
            :css('line-height', '1.45')
            :css('text-align', 'center')
            :css('word-break', 'keep-all')
            :css('white-space', 'normal')

        applyColor(label, 'color', args['항목글씨색'])
        label:wikitext(labelText)

        local value = panel:tag('div')
            :addClass('nw-summary-station-value')
            :css('padding', '0.45em 0.45em')
            :css('border-top', '1px solid ' .. borderColor)
            :css('font-size', '90%')
            :css('line-height', '1.5')
            :css('text-align', 'center')
            :css('overflow-wrap', 'anywhere')
            :css('word-break', 'keep-all')
            :css('white-space', 'normal')

        applyColor(value, 'background-color', args['값배경색'])
        applyColor(value, 'color', args['값글씨색'])
        value:wikitext(stationText or '—')
    end

    addStation('이전역', previousStation, true)
    addStation('다음역', nextStation, false)
end

-- 이미지는 하나씩 렌더링한다. 화면상의 최대 높이 250px은 틀 CSS에서 제한한다.
local function addImageCard(target, image, args, altText)
    local card = target:tag('div')
        :addClass('nw-summary-image')
        :addClass('nw-summary-image-' .. image.index)
        :css('box-sizing', 'border-box')
        :css('width', '100%')
        :css('min-width', '0')
        :css('padding', '0.7em 0.6em')
        :css('text-align', 'center')

    applyColor(card, 'background-color', args['이미지배경색'])
    applyColor(card, 'color', args['이미지글씨색'])
    applyColor(card, 'border-color', args['테두리색'])

    card:tag('div')
        :addClass('nw-summary-image-file')
        :css('width', '100%')
        :css('max-width', '100%')
        :css('text-align', 'center')
        :css('line-height', '1.3')
        :wikitext(getImageMarkup(
            image.filename,
            image.size,
            image.caption or altText
        ))

    if image.caption then
        local caption = card:tag('div')
            :addClass('nw-summary-image-caption')
            :css('margin-top', '0.4em')
            :css('font-size', '85%')
            :css('line-height', '1.45')
            :css('text-align', 'center')
            :wikitext(image.caption)
        applyColor(caption, 'color', args['이미지글씨색'])
    end
end

-- 첫 그림이 화면에 그려질 높이(px) 어림. 파일 정보를 못 읽으면 최대 높이로 본다.
local function imageBoxHeight(image)
    local width = tonumber((image.size or ''):match('^(%d+)px$')) or DEFAULT_IMAGE_SIZE
    width = math.min(width, IMAGE_BOX_WIDTH)
    local height = MAX_IMAGE_HEIGHT

    if not image.filename:match('^%[%[') then
        local name = image.filename
            :gsub('^파일:', '')
            :gsub('^그림:', '')
            :gsub('^[Ff]ile:', '')
            :gsub('^[Ii]mage:', '')
        local ok, file = pcall(function()
            local t = mw.title.new(name, 'File')
            return t and t.file
        end)
        if ok and file and file.exists and file.width and file.width > 0 and file.height then
            height = math.min(MAX_IMAGE_HEIGHT, width * file.height / file.width)
        end
    end

    return height + IMAGE_PADDING + (image.caption and CAPTION_HEIGHT or 0)
end

-- 먼저 보여 줄 정보 항목 수
local function visibleFieldCount(images, fields)
    local count = VISIBLE_FIELDS

    if #images > 0 then
        count = math.ceil(imageBoxHeight(images[1]) / ROW_HEIGHT)
        count = math.max(VISIBLE_FIELDS, math.min(MAX_VISIBLE_WITH_IMAGE, count))
    end

    if #fields - count < FOLD_MIN_EXTRA then
        count = #fields
    end

    return math.min(count, #fields)
end

-- 100% 가로형: 그림이 있으면 왼쪽 35%, 오른쪽 정보 65%.
-- 그림이 없으면 기본 세 항목은 전체폭, 나머지는 항목명/값 2쌍의 4열.
-- 두 번째 이후 그림과 6번째 이후 정보 항목은 하나의 접기 영역에 배치.
local function addResponsiveBody(root, images, fields, args, title)
    local hasImages = #images > 0
    local hasFields = #fields > 0
    local visibleCount = visibleFieldCount(images, fields)
    local extraImages = math.max(0, #images - 1)
    local extraFields = math.max(0, #fields - visibleCount)
    local firstWideCount, namedWide = getFullWidthOptions(args)

    local cell = root:tag('tr')
        :addClass('nw-summary-body-row')
        :tag('td')
        :attr('colspan', '2')
        :addClass('nw-summary-body-cell')
        :css('padding', '0')
        :css('width', '100%')
        :css('min-width', '0')
        :css('box-sizing', 'border-box')
        :css('border', '1px solid var(--border-color-base,#A2A9B1)')

    applyColor(cell, 'border-color', args['테두리색'])
    applyColor(cell, 'background-color', args['표배경색'])

    local main = cell:tag('div')
        :addClass('nw-summary-main')
        -- CSS 누락 시에도 901px 이상에서 좌측 35%, 우측 65% 배치.
        -- 합계 900px 기준을 넘지 못하면 자연스럽게 세로로 접는다.
        :css('display', 'flex')
        :css('flex-wrap', 'wrap')
        :css('align-items', 'start')
        :css('width', '100%')
        :css('min-width', '0')
        :css('box-sizing', 'border-box')
    if not hasImages then
        main:addClass('nw-summary-no-image')
    end

    if hasImages then
        local imageColumn = main:tag('div')
            :addClass('nw-summary-image-column')
            :css('flex', '35 1 315px')
            :css('min-width', '0')
            :css('box-sizing', 'border-box')
        addImageCard(imageColumn, images[1], args, title)
    end

    -- 정보 항목이 없으면 이미지가 전체 폭을 쓰고, 빈 오른쪽 칸을 만들지 않는다.
    if hasImages and not hasFields then
        main:addClass('nw-summary-image-only')
    else
        local infoColumn = main:tag('div')
            :addClass('nw-summary-fields-column')
            :css('flex', hasImages and '65 1 585px' or '1 1 100%')
            :css('min-width', '0')
            :css('box-sizing', 'border-box')

        if visibleCount > 0 then
            addFieldCards(
                infoColumn, fields, 1, visibleCount, args,
                not hasImages, firstWideCount, namedWide
            )
        end
    end

    -- 더 보여줄 내용이 없으면 접기 버튼을 만들지 않는다.
    if extraImages == 0 and extraFields == 0 then
        return
    end

    local detail = cell:tag('div')
        :addClass('nw-summary-detail')
        :addClass('mw-collapsible')
        :addClass('mw-collapsed')
        :css('width', '100%')
        :css('position', 'relative')
        :css('box-sizing', 'border-box')
        :css('border-top', '1px solid var(--border-color-base,#A2A9B1)')
        :attr('data-expandtext', '펼치기')
        :attr('data-collapsetext', '접기')

    local summaryParts = {}

    if extraFields > 0 then
        summaryParts[#summaryParts + 1] = '추가 항목 ' .. extraFields .. '개'
    end

    if extraImages > 0 then
        summaryParts[#summaryParts + 1] = '이미지 ' .. extraImages .. '장'
    end

    local detailSummary = table.concat(summaryParts, ', ')

    local detailHeading = detail:tag('div')
        :addClass('nw-summary-detail-head')
        :css('padding', '0.65em 6.8em 0.65em 0.7em')
        :css('text-align', 'center')
        :css('font-weight', 'bold')
        :css('font-size', '90%')
        :css('line-height', '1.5')
        :css('background-color', 'var(--color-surface-2,var(--background-color-interactive-subtle,#EAECF0))')
        :wikitext('상세정보 (' .. detailSummary .. ')')

    applyColor(
        detailHeading, 'background-color', args['추가정보배경색']
    )
    applyColor(
        detailHeading, 'color', args['추가정보글씨색']
    )
    applyColor(
        detailHeading, 'border-color', args['테두리색']
    )

    local content = detail:tag('div')
        :addClass('mw-collapsible-content')
        :addClass('nw-summary-detail-content')

    local detailGrid = content:tag('div')
        :addClass('nw-summary-detail-grid')
        :css('display', 'flex')
        :css('flex-wrap', 'wrap')
        :css('align-items', 'start')
        :css('width', '100%')
        :css('box-sizing', 'border-box')

    -- 좌/우 모두 있을 때만 35:65 분할. 한쪽만 있으면 가로폭 전체 사용.
    if extraImages == 0 or extraFields == 0 then
        detailGrid:addClass('nw-summary-detail-single')
    end

    if extraImages > 0 then
        local extraImageColumn = detailGrid:tag('div')
            :addClass('nw-summary-extra-images')
            :css('flex', extraFields > 0 and '35 1 315px' or '1 1 100%')
            :css('min-width', '0')
        for index = 2, #images do
            addImageCard(extraImageColumn, images[index], args, title)
        end
    end

    if extraFields > 0 then
        local extraInfoColumn = detailGrid:tag('div')
            :addClass('nw-summary-extra-fields')
            :css('flex', extraImages > 0 and '65 1 585px' or '1 1 100%')
            :css('min-width', '0')
        local paired = not hasImages or extraImages == 0
        addFieldCards(
            extraInfoColumn, fields, visibleCount + 1,
            #fields, args, paired, firstWideCount, namedWide
        )
    end
end

local function addFooter(root, frame, templateName, args)
    if not templateName then
        return
    end

    local success, expanded = pcall(function()
        return frame:expandTemplate({
            title = templateName
        })
    end)

    if success and expanded and clean(expanded) then
        local cell = root:tag('tr')
            :tag('td')
            :attr('colspan', '2')
            :addClass('nw-summary-footer')
            :wikitext(expanded)

        applyColor(
            cell,
            'background-color',
            args['하단배경색']
        )

        applyColor(
            cell,
            'color',
            args['하단글씨색']
        )

        applyColor(
            cell,
            'border-color',
            args['테두리색']
        )
    end
end

local function emptyNotice()
    local notice = mw.html.create('div')
        :addClass('nw-summary-notice')
        :css('max-width', '400px')
        :css('padding', '0.85em 1em')
        :css('border', '1px solid #B94A48')
        :css('border-left', '5px solid #B94A48')
        :css('background-color', '#FFF4F4')
        :css('color', '#652323')

    notice:tag('strong')
        :wikitext('요약정보를 입력해주세요.')

    notice:tag('div')
        :wikitext(
            '제목, 그림1, 국가 등 필요한 항목을 입력하세요. ' ..
            '[[틀:요약정보#사용법|사용법 보기]]'
        )

    return tostring(notice)
end

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

    if next(args) == nil then
        return emptyNotice()
    end

    local legacyFilm = adaptLegacyFilm(args)

    local title = pick(args, TITLE_KEYS)

    if not title then
        title = mw.title.getCurrentTitle().text
    end

    local english = pick(args, ENGLISH_KEYS)
    local original = pick(args, ORIGINAL_KEYS)
    local subtitle = pick(args, SUBTITLE_KEYS)

    local root = mw.html.create('table')
        :addClass('nw-summary-profile')
        -- 기본 스타일을 Lua에도 지정해 #css 누락 시 완전한 레이아웃 붕괴를 막는다.
        :css('display', 'table')
        :css('width', '100%')
        :css('max-width', '100%')
        :css('margin', '0.65em 0 1em')
        :css('float', 'none')
        :css('clear', 'both')
        :css('table-layout', 'fixed')
        :css('border-collapse', 'collapse')
        :css('box-sizing', 'border-box')
        :css('border', '1px solid var(--border-color-base,#A2A9B1)')
        :css('background-color', 'var(--color-surface-1,var(--background-color-base,#FFFFFF))')
        :css('color', 'var(--color-base,#202122)')

    applyColor(
        root,
        'background-color',
        args['표배경색']
    )

    applyColor(
        root,
        'color',
        args['표글씨색']
    )

    applyColor(
        root,
        'border-color',
        args['테두리색']
    )

    local heading = root:tag('tr')
        :tag('th')
        :attr('colspan', '2')
        :addClass('nw-summary-heading')
        :css('padding', '0.75em 0.65em')
        :css('text-align', 'center')
        :css('vertical-align', 'middle')
        :css('line-height', '1.45')
        :css('border', '1px solid var(--border-color-base,#A2A9B1)')
        :css('background-color', 'var(--color-surface-2,var(--background-color-interactive-subtle,#EAECF0))')
        :css('color', 'inherit')

    applyColor(
        heading,
        'background-color',
        args['제목배경색'] or args['배경색상코드']
    )

    -- 제목배경색은 대체 배경으로 유지하고, 지정된 경우에만 그라데이션을 중첩한다.
    applyColor(
        heading,
        'background-image',
        args['제목배경그라데이션']
    )

    applyColor(
        heading,
        'color',
        args['제목글씨색'] or args['글씨색상코드']
    )

    applyColor(
        heading,
        'border-color',
        args['테두리색']
    )

    heading:tag('div')
        :addClass('nw-summary-title-main')
        :css('font-size', '135%')
        :css('font-weight', 'bold')
        :css('line-height', '1.4')
        :wikitext(title)

    if english then
        heading:tag('div')
            :addClass('nw-summary-title-sub')
            :css('font-size', '90%')
            :css('line-height', '1.45')
            :wikitext(english)
    end

    if original and original ~= english then
        heading:tag('div')
            :addClass('nw-summary-title-original')
            :css('font-size', '90%')
            :css('line-height', '1.45')
            :wikitext(original)
    end

    if subtitle then
        heading:tag('div')
            :addClass('nw-summary-title-caption')
            :css('font-size', '90%')
            :css('line-height', '1.45')
            :wikitext(subtitle)
    end

    local images = getImages(args)
    local fields = getFields(args)

    addResponsiveBody(root, images, fields, args, plainText(title))

    addAdjacentStations(root, args)

    addFooter(root, frame, args['틀'], args)

    local output = tostring(root)

    if legacyFilm
        and mw.title.getCurrentTitle().namespace == 0
    then
        output = output .. '[[분류:영화]]'
    end

    return output
end

return p