<template>
  <div class="kole-switchgroup">
    <div class="kole-switchgroup-head" v-if="title || selectAll">
      <span class="kole-switchgroup-title">{{ title }}</span>
      <div v-if="selectAll" class="kole-switch" :class="{ 'is-on': allOn }" @click="toggleAll"></div>
    </div>
    <div class="kole-switch-row" v-for="(o, i) in options" :key="i">
      <div class="kole-switch-text">
        <span class="kole-switch-label">{{ o.label }}</span>
        <span class="kole-switch-desc" v-if="o.desc">{{ o.desc }}</span>
      </div>
      <div class="kole-switch" :class="{ 'is-on': modelValue.indexOf(o.value) >= 0 }" @click="toggle(o.value)"></div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue';
const props = defineProps({
  options: { type: Array, default: () => [] },
  modelValue: { type: Array, default: () => [] },
  title: { type: String, default: '' },
  selectAll: { type: Boolean, default: false }
});
const emit = defineEmits(['update:modelValue']);

const allOn = computed(() =>
  props.options.length > 0 && props.options.every(o => props.modelValue.indexOf(o.value) >= 0)
);

function toggle(v) {
  const arr = props.modelValue.slice();
  const idx = arr.indexOf(v);
  if (idx >= 0) arr.splice(idx, 1); else arr.push(v);
  emit('update:modelValue', arr);
}
function toggleAll() {
  const next = allOn.value ? [] : props.options.map(o => o.value);
  emit('update:modelValue', next);
}
</script>

<style src="./SwitchGroup.css"></style>
