<template>
	<div class="column-picker" ref="rootRef">
		<NcButton @click="open = !open">
			<template #icon>
				<ViewColumn :size="20" />
			</template>
			Spalten
		</NcButton>
		<div v-if="open" class="column-picker__dropdown">
			<label v-for="col in columns" :key="col.key"
				class="column-picker__option">
				<input type="checkbox"
					:checked="modelValue.includes(col.key)"
					:disabled="col.alwaysVisible"
					@change="toggle(col.key)">
				{{ col.label }}
			</label>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { NcButton } from '@nextcloud/vue'
import ViewColumn from 'vue-material-design-icons/ViewColumn.vue'

const props = defineProps({
	columns: { type: Array, required: true },
	modelValue: { type: Array, required: true },
})

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

const open = ref(false)
const rootRef = ref(null)

function toggle(key) {
	const col = props.columns.find(c => c.key === key)
	if (col && col.alwaysVisible) return

	const current = [...props.modelValue]
	const idx = current.indexOf(key)
	if (idx >= 0) {
		current.splice(idx, 1)
	} else {
		// Insert in the same order as columns definition
		const allIdx = props.columns.findIndex(c => c.key === key)
		let insertAt = current.length
		for (let i = 0; i < current.length; i++) {
			const currentAllIdx = props.columns.findIndex(c => c.key === current[i])
			if (currentAllIdx > allIdx) {
				insertAt = i
				break
			}
		}
		current.splice(insertAt, 0, key)
	}
	emit('update:modelValue', current)
}

function onClickOutside(event) {
	if (rootRef.value && !rootRef.value.contains(event.target)) {
		open.value = false
	}
}

onMounted(() => document.addEventListener('click', onClickOutside))
onBeforeUnmount(() => document.removeEventListener('click', onClickOutside))
</script>

<style scoped>
.column-picker {
	position: relative;
}

.column-picker__dropdown {
	position: absolute;
	top: 100%;
	right: 0;
	z-index: 100;
	min-width: 220px;
	max-height: 400px;
	overflow-y: auto;
	background: var(--color-main-background);
	border: 1px solid var(--color-border);
	border-radius: var(--border-radius-large);
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
	padding: 8px 0;
	margin-top: 4px;
}

.column-picker__option {
	display: flex;
	align-items: center;
	gap: 8px;
	padding: 6px 16px;
	cursor: pointer;
	font-size: 0.9em;
	white-space: nowrap;
}

.column-picker__option:hover {
	background: var(--color-background-hover);
}

.column-picker__option input[type="checkbox"] {
	margin: 0;
}

.column-picker__option input[type="checkbox"]:disabled {
	opacity: 0.5;
}
</style>
