<script setup>
import {inject, onBeforeUnmount, onMounted, onUpdated, ref} from "vue";

const props = defineProps(["name", "value"])
const rootRef = ref()

let oldContent
let oldName
let oldValue

const getName = () => {
	let name = props.name
	if (typeof name !== "string" || name.length === 0) {
		name = rootRef.value.textContent
		if (typeof name !== "string" || name.length === 0) {
			name = rootRef.value.innerText
		}
	}
	return name
}

onMounted(() => {
	oldContent = rootRef.value.innerHTML

	let name = getName()
	oldName = name
	oldValue = props.value
	const addFn = inject("$addSelectOption")
	addFn(name, props.value)
})

onBeforeUnmount(() => {
	let name = getName()
	const removeFn = inject("$removeSelectOption")
	removeFn(name, props.value)
})

onUpdated(() => {
	if (oldContent != rootRef.value.innerHTML) {
		oldContent = rootRef.value.innerHTML

		const newName = getName()
		const newValue = props.value
		const updateFn = inject("$updateSelectOption")
		updateFn(oldName, oldValue, newName, newValue)
		oldName = newName
		oldValue = newValue
	}
})

</script>

<template>
	<div ref="rootRef">
		<slot></slot>
	</div>
</template>

<style scoped>

</style>