local p = {}

function colorCell(val)
	if val > 48 then
		return cell(val, '000', 'FF0')
	elseif val >= 37 then
		return cell(val, '602000', 'FF0')
	elseif val >= 28 then
		return cell(val, '804020', 'FF0')
	elseif val >= 23 then
		return cell(val, 'b06030', 'FF0')
	elseif val >= 19 then
		return cell(val, 'CC5500', 'FF0')
	elseif val >= 16 then
		return cell(val, 'E9692C')
	elseif val >= 13 then
		return cell(val, 'FF8C00')
	elseif val >= 10 then
		return cell(val, 'FFA500')
	elseif val >= 7 then
		return cell(val, 'FCC200')
	elseif val >= 4 then
		return cell(val, 'FFDF00')
	elseif val >= 1 then
		return cell(val, 'FBEC5D')
	end
	return cell(val, 'FFF')
end

function cell(val, bgcolor, color)
	bgcolor = bgcolor or 'f8f9fa'
	color = color or '202122'
	return '\n|style="text-align:center;background-color:#' .. bgcolor .. ';color:#' .. color .. ';"|' .. val
end

function redgreen(val)
	if val < 0 then
		return cell(val, 'FFC7C7')
	elseif val > 0 then
		return cell('+' .. val, 'BFD')
	end
	return cell('0')
end

function p.main(frame)
	local args = frame:getParent().args
	local months = {args.jan, args.feb, args.mar, args.apr, args.may, args.jun, args.jul, args.aug, args.sep, args.oct, args.nov, args.dec}
	local refs = {args.janref, args.febref, args.marref, args.aprref, args.mayref, args.junref, args.julref, args.augref, args.sepref, args.octref, args.novref, args.decref}
	local restored = tonumber(args.restored) or 0
	local rfas = tonumber(args.rfas) or 0
	local output = '|-\n!|' .. args.year
	local counter = 0
	local total = 0
	
	for i = 1, 12 do
		local month = tonumber(months[i])
		if month ~= nil and month >= 0 then
			output = output .. colorCell(month)
			if (refs[i] ~= nil) then
				local efn = frame:expandTemplate{title='efn', args={name=refs[i]}}
				output = output .. efn
			end
			total = total + month
			counter = counter + 1
		else
			output = output .. cell('—')
		end
	end
	local mean = math.floor((total / counter) * 10) / 10
	if counter == 0 then
		mean = 0
	end
	output = output .. colorCell(mean) .. cell(total) .. cell(restored) .. cell(rfas)
	local change = restored + rfas - total
	output = output .. redgreen(change)
	return output
end

return p