local p = {}

local function check_pages(pages, format)
	for _, page in ipairs(pages) do
		if mw.title.new(page).exists then
			return string.format(format, page)
		end
	end
	return ""
end

local function parse_chinese_date(month_str, day_str)
	local month = month_str:match("(%d+)月")
	local day = day_str:match("(%d+)日")
	return tonumber(month), tonumber(day)
end

local function format_chinese_date(year, month, day, full)
	if full then
		return string.format("%d年/%d月%d日", year, month, day)
	else
		return string.format("%d月%d日", month, day)
	end
end

local function get_adjacent_date(year, month, day, offset, full)
	local date = os.time({year = year, month = month, day = day})
	local adj_date = os.date("*t", date + offset * 24 * 60 * 60)
	return format_chinese_date(adj_date.year, adj_date.month, adj_date.day, full)
end

function p.main(frame)
	local parent_args = frame:getParent().args

	local params = {
		[1] = {required = true, type = "string", default = "langcode"},
		[2] = {required = true, type = "string", default = "word"},
		[3] = {required = true, type = "string"},
		[4] = {required = true, type = "string"},
		[5] = {required = true, type = "string"},
		[6] = {required = true, type = "string"},
		[7] = {type = "string"},
		["audio"] = {type = "string"},
		["image"] = {type = "string"},
		["image_size"] = {type = "number", default = 150},
		["tr"] = {type = "string"}
	}

	local args = require("Module:parameters").process(parent_args, params)

	local langcode = args[1]
	local word = args[2]
	local pos = args[3]
	local month_str = args[4]
	local day_str = args[5]
	local definition = args[6]
	local comment = args[7] or ""
	local audio = args["audio"]
	local image = args["image"]
	local image_size = args["image_size"]
	local tr = args["tr"] or ""

	local month, day = parse_chinese_date(month_str, day_str)
	local year = os.date("%Y")

	local audio_link = ""
	if audio and audio ~= "no" then
		audio_link = string.format('<div style="float:right">[[File:%s|noicon]]</div>', audio)
	end

	local current_title = mw.title.getCurrentTitle()
	local purge_url = current_title:fullUrl({action = 'purge'})
	
	local edit_template = frame:expandTemplate{title = "edit", args = {string.format("Wiktionary:外語每日一詞/%d年/%d月%d日", year, month, day)}}

	local header_row = mw.html.create('span')
	header_row:css('float', 'right')
		:css('font-size', 'small')
		:wikitext(edit_template .. ' · [' .. purge_url .. ' 刷新] · [[Wiktionary:外語每日一詞/' .. year .. '年/' .. month .. '月' .. day .. '日|檢視]]')

	local langname = require("Module:languages").getByCode(langcode):getCanonicalName()
	
	local title_container = mw.html.create('div')
	title_container:css('display', 'flex')
	    :css('justify-content', 'space-between')
	    :css('align-items', 'center')
	    :css('border-bottom', '1px solid #AAAAAA') -- underline
	
	-- skip h2 in the archive page
	if not string.find(mw.title.getCurrentTitle().fullText, "存檔") then
	    local title_row = mw.html.create('h2')
	    title_row:addClass('hp-segment-title')
	        :css('margin-bottom', '0')
	        :css('border-bottom', 'none') --  override underline in Mainpage.css
	        :wikitext('[[Wiktionary:外語每日一詞|外語每日一詞]] <span style="font-size:small;">' .. format_chinese_date(year, month, day, false) .. ' · ' .. '[[:Category:' .. langname .. '|' .. langname .. ']]</span>')
	    title_container:node(title_row)
	else
		local langname_div_archive = mw.html.create('div')
		langname_div_archive:wikitext('[[:Category:' .. langname .. '|' .. langname .. ']]</span>')
		title_container:node(langname_div_archive)
	end
	
	-- always add header_row
	title_container:node(header_row)

	local output = mw.html.create('div')
		:addClass('mf-wotd')
		:attr('title', '外語每日一詞')
		:css('background-color', '#F4F9F0')
		:css('padding', '10px')

	local word_wikitext
	if word:match('span') then -- 如果傳入的參數已帶有連結,會有 span 標籤
		word_wikitext = word
	else
		template_args = {langcode, word}
		if tr ~= "" then
			template_args["tr"] = tr
		end
		word_wikitext = frame:expandTemplate{title = 'l', args = template_args}
	end

	local word_row = output:tag('div')
	word_row:css('padding-left', '10px')
		:wikitext(string.format("'''%s''' %s", word_wikitext, pos))

	if image and image ~= "" then
		local image_html = string.format('[[File:%s|%dpx|right]]', image, image_size)
		word_row:wikitext(image_html)
	end

	local def_row = output:tag('div')
	def_row:css('padding-left', '10px')
		:wikitext(string.format('<div id="WOTD-rss-description">\n%s</div>', definition))

	if comment ~= "" then
		def_row:tag('div')
			:css('padding-left', '10px')
			:wikitext(string.format('[[File:PointingHand.svg|20px]]&#32;<span style="font-size:80%;">%s</span>', comment))
	end
   
	if audio_link ~= "" then
		def_row:tag('div')
			:css('padding-left', '10px')
			:wikitext(audio_link)
	end

	local prev_day = get_adjacent_date(year, month, day, -1, true)
	local next_day = get_adjacent_date(year, month, day, 1, true)
	mw.log("Received word parameter: " .. tostring(word))
	local target = word:match('span') and word:match('%[%[(.-)#') or word
	mw.log("Received target parameter: " .. tostring(target))
	local footer_row = output:tag('div')
	footer_row:css('font-size', '80%')
		:css('text-align', 'center')
		:css('vertical-align', 'top')
		:wikitext(string.format('[[Wiktionary:外語每日一詞/%s|← 昨日]] &#124; [[Wiktionary:外語每日一詞|關於外語每日一詞]] · [[Wiktionary:外語每日一詞#提名|提名新詞]] · <span class="plainlinks" title="Wiktionary:回饋">[https://zh.wiktionary.org/w/index.php?title=Wiktionary:回饋&action=edit&section=new&preload=Wiktionary:回饋%%2Fpreload&editintro=Wiktionary:回饋%%2Fintro&preloadtitle=外語每日一詞:&#91;&#91;%s&#93;&#93; 給予回饋]</span> &#124; [[Wiktionary:外語每日一詞/%s|明日&nbsp;→]]', 
			prev_day, mw.uri.encode(target), next_day
		))

	local container = mw.html.create('td')
	container:css('background-color', '#F4F9F0')
	container:node(title_container)
	container:node(output)

	return tostring(container)
end

return p