<script setup lang="ts" generic="T extends boolean | undefined | any[]">
import { resolveI18n } from '@bagelink/vue'
import { computed, onMounted } from 'vue'
import type { BagelInputShellProps } from './bagelInputShell'
import { useBagelInputShell } from './bagelInputShell'

const props = defineProps<{
	label?: string
	id?: string
	title?: string
	small?: boolean
	required?: boolean
	disabled?: boolean
	defaultValue?: T
	value?: any
} & BagelInputShellProps>()

const { shellClass, shellStyle } = useBagelInputShell(props)

const uid = Math.random().toString(36).slice(7)
const inputId = computed(() => props.id || uid)

const checked = defineModel<T>('modelValue', { default: undefined })

const hasValue = computed(() => {
	const v = checked.value
	return Array.isArray(v) ? v.length > 0 : Boolean(v)
})

onMounted(() => {
	if (checked.value === undefined && props.defaultValue !== undefined) checked.value = props.defaultValue as T
})
</script>

<template>
	<div
		class="bagel-input bgl-checkbox align-items-center ps-025" :title
		:class="[shellClass, { small, 'has-value': hasValue }]" :style="shellStyle"
	>
		<input
			:id="inputId + value" v-model="checked" :disabled="disabled" :value :required type="checkbox"
			class="me-05"
		>
		<label :for="inputId + value">
			<slot name="label">
				{{ resolveI18n(label) }}
			</slot>
		</label>
	</div>
</template>

<style scoped>

.bgl-checkbox {
flex-direction: row;
cursor: pointer;
align-items: flex-start;
}

.bgl-checkbox input[type='checkbox'] {
accent-color: var(--bgl-input-label-active-color, var(--bgl-accent-color));
height: calc(var(--bgl-input-height) / 2.75);
width: calc(var(--bgl-input-height) / 2.75);
min-width: 0;
display: flex;
justify-content: center;
align-items: center;
flex-shrink: 0;
}

.bgl-checkbox input[type='checkbox']::before {
content: '';
height: calc(var(--bgl-input-height) / 2.75);
width: calc(var(--bgl-input-height) / 2.75);
background: var(--bgl-input-label-active-color, var(--bgl-primary));
border-radius: 100%;
opacity: 0;
transition: all 200ms ease;
position: absolute;
}

.bgl-checkbox input[type='checkbox']:hover::before {
opacity: 0.2;
transform: scale(2);
}

.bgl-checkbox label {
cursor: pointer;
user-select: none;
font-size: var(--bgl-input-font-size);
transition: var(--bgl-transition-400);
}

.bgl-checkbox:hover label {
color: var(--bgl-input-label-active-color, var(--bgl-primary)) !important;
}

.bgl-checkbox input:checked+label {
color: var(--bgl-input-label-active-color, var(--bgl-primary)) !important;
}

.bagel-input:focus-within.bgl-checkbox:not(:checked) label {
color: var(--bgl-label-color) !important;
}

.bgl-checkbox input:disabled+label,
.bgl-checkbox:has(input:disabled):hover label {
color: var(--bgl-input-label-color) !important;
opacity: 0.5;
}

</style>
