<script setup>
import { computed } from 'vue';

const props = defineProps({
    modelValue: {
        type: Array,
        default: () => []
    },
    label: {
        type: String,
        required: true
    },
    options: {
        type: Array,
        required: true
    },
    max: {
        type: Number,
        default: 2
    },
    error: {
        type: String,
        default: null
    }
});

const emit = defineEmits(['update:modelValue']);

const isSelected = (value) => {
    return props.modelValue.includes(value);
};

const isDisabled = (value) => {
    return !isSelected(value) && props.modelValue.length >= props.max;
};

const toggle = (value) => {
    if (isDisabled(value)) return;

    const newValue = [...props.modelValue];
    if (isSelected(value)) {
        const index = newValue.indexOf(value);
        newValue.splice(index, 1);
    } else {
        newValue.push(value);
    }
    emit('update:modelValue', newValue);
};
</script>

<template>
    <div class="field md:col-span-2 space-y-2">
        <p class="text-xs font-medium text-surface-600 dark:text-surface-300">
            {{ label }}
            <span class="font-normal text-surface-400">(можно выбрать до {{ max }})</span>
        </p>
        <div class="grid grid-cols-1 gap-2 sm:grid-cols-2">
            <div
                v-for="option in options"
                :key="option.value"
                class="flex items-start gap-2 rounded-xl border px-4 py-3 text-left text-sm transition cursor-pointer"
                :class="{
                    'border-primary-500 bg-primary-50 text-primary-900 shadow-sm dark:border-primary-400 dark:bg-primary-900/30 dark:text-primary-50': isSelected(option.value),
                    'border-surface-200 bg-surface-0 text-surface-900 hover:border-primary-200 hover:bg-primary-50/40 dark:border-surface-700 dark:bg-surface-900 dark:text-surface-100 dark:hover:border-primary-500/60':
                        !isSelected(option.value) && !isDisabled(option.value),
                    'opacity-50 cursor-not-allowed': isDisabled(option.value)
                }"
                @click="toggle(option.value)"
            >
                <span class="font-medium">{{ option.label }}</span>
            </div>
        </div>
        <small v-if="error" class="p-error">{{ error }}</small>
    </div>
</template>
