<script setup>
import { ref, watch } from 'vue';

import ActorSearch from '#/components/actors/search.vue';

const props = defineProps({
	item: {
		type: Object,
		default: null,
	},
	scene: {
		type: Object,
		default: null,
	},
	edits: {
		type: Object,
		default: () => {},
	},
	editing: {
		type: Set,
		default: null,
	},
});

const emit = defineEmits(['actors']);

const newActors = ref([]);

function addActor(actor) {
	newActors.value = newActors.value.concat(actor);

	emit('actors', props.edits.actors.concat(actor.id));
}

watch(() => props.scene, () => {
	newActors.value = [];
});
</script>

<template>
	<ul
		class="actors nolist"
		:class="{ disabled: !editing.has(item.key) }"
	>
		<li
			v-for="actor in [...item.value, ...newActors]"
			:key="`actor-${actor.id}`"
			class="actor"
			:class="{ deleted: edits.actors && !edits.actors.some((actorId) => actorId === actor.id) }"
		>
			<span class="actor-name">{{ actor.name }}</span>

			<Icon
				v-if="edits.actors && !edits.actors.some((actorId) => actorId === actor.id)"
				icon="checkmark"
				class="add"
				@click="emit('actors', edits.actors.concat(actor.id))"
			/>

			<Icon
				v-else
				icon="cross2"
				class="remove"
				@click="emit('actors', edits.actors.filter((actorId) => actorId !== actor.id))"
			/>
		</li>

		<li class="new">
			<ActorSearch
				:disabled="!editing.has(item.key)"
				@actor="addActor"
			>
				<Icon
					icon="plus3"
					class="add"
				/>
			</ActorSearch>
		</li>
	</ul>
</template>

<style scoped>
.actors {
	display: flex;
	flex-wrap: wrap;
	gap: .35rem .25rem;

	&.disabled {
		.actor {
			background: var(--glass-weak-50);
			color: var(--glass-strong-10);

			.remove,
			.add {
				fill: var(--shadow-weak-30);
				background: var(--shadow-weak-50);
			}
		}

		.new .icon {
			background: var(--shadow-weak-40);
		}
	}

	.new {
		display: flex;
		align-items: center;
		margin-left: .25rem;

		&:hover {
			box-shadow: 0 0 3px var(--shadow-weak-20);
		}

		.icon {
			height: 100%;
			padding: 0 .5rem;
			background: var(--success);
			fill: var(--text-light);
		}
	}
}

.actor {
	display: flex;
	align-items: stretch;
	border-radius: .25rem;
	background: var(--background);
	box-shadow: 0 0 3px var(--shadow-weak-30);

	&.deleted  {
		color: var(--glass);
		text-decoration: line-through;
	}
}

.actor,
.new {
	.remove,
	.add {
		height: auto;
		padding: .25rem .3rem;
		border-radius: .25rem;
		fill: var(--highlight-strong-10);

		&:hover {
			fill: var(--text-light);
			cursor: pointer;
		}
	}

	.remove {
		fill: var(--error);

		&:hover {
			background: var(--error);
		}
	}

	.add {
		fill: var(--success);

		&:hover {
			background: var(--success);
		}
	}
}

.actor-name {
	padding: .25rem .5rem;
}
</style>
