const format = {
	html: (html: string) => {
		const formatted = []
		const reg = /(>)(<)(\/*)/g
		const tab = '  '
		let level = 0

		html = html.replace(reg, '$1\n$2$3')

		const lines = html.split('\n')

		for (const line of lines) {
			if (line.match(/<\/\w+/) && !line.match(/\/>/)) {
				level--
			}
			formatted.push(tab.repeat(Math.max(level, 0)) + line)
			if (line.match(/<\w[^>]*[^/]>/)) {
				level++
			}
		}
		return formatted.join('\n')
	},
	json: (jsonString: string, indent = 4) => {
		try {
			const jsonObject = JSON.parse(jsonString)
			return JSON.stringify(jsonObject, null, indent)
		} catch (error) {
			return `Invalid JSON: ${(error as Error).message}`
		}
	},
	javascript: (jsCode: string, indent = 4) => {
		try {
			const tab = ' '.repeat(indent)
			let formatted = ''
			let level = 0
			let inString = ''

			for (let i = 0; i < jsCode.length; i++) {
				const char = jsCode[i]
				const nextChar = jsCode[i + 1]
				if (char === '"' || char === '\'' || char === '`') {
					formatted += char
					if (inString.length && inString === char) {
						inString = ''
					} else if (!inString.length) {
						inString = char
					}
					continue
				}
				if (inString) {
					formatted += char
					continue
				}
				if (char === '{' || char === '[') {
					formatted += `${char}\n${tab.repeat(++level)}`
					continue
				}
				if (char === '}' || char === ']') {
					formatted += `\n${tab.repeat(--level)}${char}`
					continue
				}
				if (char === ';' || char === ',') {
					formatted += `${char}\n${tab.repeat(level)}`
					continue
				}
				if (char === '\n') {
					formatted += `\n${tab.repeat(level)}`
					continue
				}
				if (
					(char === ')' && nextChar === '{')
					|| (char === ')' && nextChar === ' ')
				) {
					formatted += `${char}\n${tab.repeat(level)}`
					continue
				}
				formatted += char
			}

			return formatted
		} catch (error) {
			return `Error formatting JavaScript: ${(error as Error).message}`
		}
	}
}

export function formatCode(code: string, language: string) {
	switch (language) {
		case 'html':
			return format.html(code)
		case 'json':
			return format.json(code)
		case 'javascript':
			return format.javascript(code)
		default:
			return code
	}
}
