<template>
	<div class="color-selector">
		<w-input
			v-model="colorValue"
			placeholder="#000000"
			class="color-selector__input"
			inner-icon-left="mdi mdi-eyedropper-variant"
			color="gray"
		/>

		<div class="color-selector__palette">
			<div
				v-for="color in $store.state.config.colorPalette"
				:key="color"
				class="color-selector__palette-color"
				:style="{ backgroundColor: color }"
				@click="selectColor(color)"
			>	
				<w-transition-scale-fade>
					<w-icon
						v-if="color == value"
					>
						mdi mdi-check
					</w-icon>
				</w-transition-scale-fade>
			</div>
		</div>

		<w-button
			v-if="clearable"
			icon="mdi mdi-cancel"
			bg-color="error"
			:max="7"
			@click="$emit('input', '')"
		/>
	</div>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
	
	props: {
		value: String,
		clearable: Boolean
	},

	data: () => ({
		colorValue: ''
	}),

	watch: {
		value(value) {
			this.colorValue = value || '';
		},
		colorValue(value) {
			if(!value) {
				this.$emit('input', null);
				return;
			}

			const isValid = /^#[0-9A-F]{6}$/i.test(value);

			if (isValid) {
				this.$emit('input', value);
			}
		}
	},

	created() {
		this.colorValue = this.value;
	},

	methods: {
		selectColor(color: string) {
			this.colorValue = color;
		}
	}
});
</script>

<style lang="scss">
.color-selector {
	display: flex;
	align-items: center;
	gap: 0.5rem;
	flex-wrap: wrap;

	&__input {
		max-width: 110px;
		padding: 0;
		margin: 0;
	}

	&__palette {
		display: flex;
		gap: 0.5rem;
		flex-wrap: wrap;
	}

	&__palette-color {
		@include rounded(full);
		@include transition(transform);
	
		height: 1.5rem;
		aspect-ratio: 1/1;
		display: flex;
		justify-content: center;
		align-items: center;
		cursor: pointer;
		color: white;
	}
}
</style>