@props([
	'name' => null,
	'json' => null,
])
@php
	$array = json_decode($json, true);


	if(! is_array($array)) {
		$array = [];
	}
@endphp

<input type="hidden" name="{{ $name }}" value="{{ $json }}">

@foreach($array AS $label => $value)

<x-bs-form.json-key
	:label=$label
	:value=$value
	:group=$name
	:jsonName=$label
/>

@endforeach

<script>

var jsonElements = document.querySelectorAll(`[data-json_input][data-json_group={{ $name }}]`);

jsonElements.forEach((jsonElement) => {
	jsonElement.addEventListener('change', function(event) {

		let jsonGroup = event.target.dataset.json_group;
		let jsonInput = document.querySelector(`input[name="${jsonGroup}"]`);
		let jsonString = jsonInput.value;
		let json = JSON.parse(jsonString);

		setByPath(json, event.target.dataset.json_name, event.target.value);
		jsonInput.value = JSON.stringify(json);
	});
});

function setByPath(obj, path, value) {
    const keys = path.split('.');
    let current = obj;
    for (let i = 0; i < keys.length - 1; i++) {
        const key = keys[i];
        if (!current[key]) current[key] = {};
        current = current[key];
    }
    current[keys[keys.length - 1]] = value;
}


</script>