<script setup>
import { onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue';

const props = defineProps({ tweaks: { type: Object, default: () => ({}) } });
const open = ref(false);
const state = reactive({
    variant: 'forest',
    particles: true,
    moon: true,
    ...props.tweaks,
    ...readStoredTweaks(),
});

function readStoredTweaks() {
    try {
        return JSON.parse(localStorage.getItem('moonwell.tweaks') || '{}');
    } catch {
        return {};
    }
}

function applyTweaks() {
    document.body.dataset.variant = state.variant;
    document.body.dataset.particles = state.particles ? 'true' : 'false';
    document.body.dataset.moon = state.moon ? 'true' : 'false';
}

const onKey = (event) => {
    if (event.key === '`' || (event.altKey && event.key.toLowerCase() === 't')) {
        open.value = !open.value;
    }
};

onMounted(() => {
    applyTweaks();
    window.addEventListener('keydown', onKey);
});
onBeforeUnmount(() => window.removeEventListener('keydown', onKey));

watch(state, () => {
    applyTweaks();
    try {
        localStorage.setItem('moonwell.tweaks', JSON.stringify(state));
    } catch {
        // Appearance preferences are non-critical.
    }
}, { deep: true });
</script>

<template>
    <button class="tweaks-fab" aria-label="Tweaks" title="Настройки внешнего вида (alt+T)" @click="open = !open">✦</button>
    <div :class="['tweaks', { open }]">
        <div class="tweaks-title">
            <span>Tweaks</span>
            <button aria-label="Close" @click="open = false">×</button>
        </div>
        <div class="tweak-row">
            <label>Настроение</label>
            <div class="tweak-seg">
                <button :class="{ active: state.variant === 'forest' }" @click="state.variant = 'forest'">Лес</button>
                <button :class="{ active: state.variant === 'temple' }" @click="state.variant = 'temple'">Храм</button>
            </div>
        </div>
        <div class="tweak-row">
            <label>Частицы и анимации</label>
            <div :class="['tweak-switch', { on: state.particles }]" role="switch" :aria-checked="state.particles" @click="state.particles = !state.particles"></div>
        </div>
        <div class="tweak-row">
            <label>Луна на фоне</label>
            <div :class="['tweak-switch', { on: state.moon }]" role="switch" :aria-checked="state.moon" @click="state.moon = !state.moon"></div>
        </div>
    </div>
</template>
