<script lang="ts">
	import type { Entity } from 'koota'

	import { T, useThrelte } from '@threlte/core'

	import type { InstancedArrows } from '../../../three/InstancedArrows/InstancedArrows'

	import AxesHelper from '../../AxesHelper.svelte'
	import { useEntityEvents } from '../hooks/useEntityEvents.svelte'
	import { traits, useTrait } from '../../../ecs'
	import { useFocusedEntity, useSelectedEntity } from '../../../hooks/useSelection.svelte'
	import { meshBoundsRaycast, raycast } from '../../../three/InstancedArrows/raycast'

	interface Props {
		entity: Entity
		arrows: InstancedArrows
	}

	let { entity, arrows }: Props = $props()

	const { invalidate } = useThrelte()
	const worldMatrix = useTrait(() => entity, traits.WorldMatrix)
	const invisible = useTrait(() => entity, traits.InheritedInvisible)
	const showAxesHelper = useTrait(() => entity, traits.ShowAxesHelper)

	const events = useEntityEvents(() => entity)
	const selectedEntity = useSelectedEntity()
	const focusedEntity = useFocusedEntity()

	const displayEntity = $derived(selectedEntity.current ?? focusedEntity.current)

	const raycastFunction = $derived.by(() => {
		if (displayEntity) {
			return raycast
		}
		return meshBoundsRaycast
	})

	$effect.pre(() => {
		arrows.matrixAutoUpdate = false
		if (!worldMatrix.current) return
		arrows.matrix.copy(worldMatrix.current)
		arrows.updateMatrixWorld()
		invalidate()
	})
</script>

<T
	is={arrows}
	name={entity}
	{...events}
	raycast={raycastFunction}
	visible={invisible.current !== true}
>
	<T
		is={arrows.headMesh}
		bvh={{ enabled: false }}
		raycast={() => null}
	/>
	<T
		is={arrows.shaftMesh}
		bvh={{ enabled: false }}
		raycast={() => null}
	/>
	{#if showAxesHelper.current}
		<AxesHelper
			name={entity}
			width={3}
			length={0.1}
		/>
	{/if}
</T>
