<template>
  <div>
    <!-- Power Node -->
    <h4 :class="headingClass">Power Node</h4>
    <div :class="rowClass"><label :class="labelClass">Label</label><input :class="inputClass" type="text" v-model="powerNodeLabel"></div>

    <!-- Primary Value (Bottom) -->
    <h4 :class="subHeadingClass">Unten (Primaer)</h4>
    <div :class="rowClass"><label :class="labelClass">Quelle</label>
      <select :class="inputClass" v-model.number="widget.textSrc" @change="handleTextSrcChange">
        <optgroup v-for="group in groupedSources(sourceOptions.powernode)" :key="group.label" :label="group.label">
          <option v-for="opt in group.values" :key="opt" :value="opt">{{ textSources[opt] }}</option>
        </optgroup>
      </select>
    </div>
    <div v-if="widget.textSrc === 0" :class="rowClass">
      <label :class="labelClass">Wert</label><input :class="inputClass" type="text" v-model="powerNodeValue">
    </div>
    <template v-else>
      <div :class="rowClass"><label :class="labelClass">Format</label><input :class="inputClass" type="text" v-model="powerNodeValue"></div>
      <div :class="rowClass"><label :class="labelClass">KNX Objekt</label>
        <select :class="inputClass" v-model.number="widget.knxAddr">
          <option :value="0">-- Waehlen --</option>
          <option v-for="addr in store.knxAddresses" :key="`${addr.addr}-${addr.index}`" :value="addr.addr">
            GA {{ addr.addrStr }} (GO{{ addr.index }})
          </option>
        </select>
      </div>
    </template>

    <!-- Secondary Value (Left) -->
    <h4 :class="subHeadingClass">Links (Sekundaer)</h4>
    <div :class="rowClass"><label :class="labelClass">Quelle</label>
      <select :class="inputClass" v-model.number="widget.textSrc2">
        <option :value="0">-- Keine --</option>
        <optgroup v-for="group in groupedSources(sourceOptions.powernode)" :key="group.label" :label="group.label">
          <option v-for="opt in group.values" :key="opt" :value="opt">{{ textSources[opt] }}</option>
        </optgroup>
      </select>
    </div>
    <template v-if="widget.textSrc2 > 0">
      <div :class="rowClass"><label :class="labelClass">Format</label><input :class="inputClass" type="text" v-model="widget.text2" maxlength="15"></div>
      <div :class="rowClass"><label :class="labelClass">KNX Objekt</label>
        <select :class="inputClass" v-model.number="widget.knxAddr2">
          <option :value="0">-- Waehlen --</option>
          <option v-for="addr in store.knxAddresses" :key="`${addr.addr}-${addr.index}`" :value="addr.addr">
            GA {{ addr.addrStr }} (GO{{ addr.index }})
          </option>
        </select>
      </div>
    </template>

    <!-- Tertiary Value (Right) -->
    <h4 :class="subHeadingClass">Rechts (Tertiaer)</h4>
    <div :class="rowClass"><label :class="labelClass">Quelle</label>
      <select :class="inputClass" v-model.number="widget.textSrc3">
        <option :value="0">-- Keine --</option>
        <optgroup v-for="group in groupedSources(sourceOptions.powernode)" :key="group.label" :label="group.label">
          <option v-for="opt in group.values" :key="opt" :value="opt">{{ textSources[opt] }}</option>
        </optgroup>
      </select>
    </div>
    <template v-if="widget.textSrc3 > 0">
      <div :class="rowClass"><label :class="labelClass">Format</label><input :class="inputClass" type="text" v-model="widget.text3" maxlength="15"></div>
      <div :class="rowClass"><label :class="labelClass">KNX Objekt</label>
        <select :class="inputClass" v-model.number="widget.knxAddr3">
          <option :value="0">-- Waehlen --</option>
          <option v-for="addr in store.knxAddresses" :key="`${addr.addr}-${addr.index}`" :value="addr.addr">
            GA {{ addr.addrStr }} (GO{{ addr.index }})
          </option>
        </select>
      </div>
    </template>

    <!-- Conditions -->
    <h4 :class="headingClass">Bedingungen</h4>
    <div :class="rowClass">
      <label :class="labelClass">Anzahl</label>
      <select :class="inputClass" v-model.number="conditionCount">
        <option :value="0">Keine</option>
        <option :value="1">1</option>
        <option :value="2">2</option>
        <option :value="3">3</option>
      </select>
    </div>
    <div v-for="(cond, idx) in conditions" :key="idx" class="border border-border rounded-lg px-2.5 py-2 mb-2 bg-panel-2">
      <div class="flex items-center gap-2 mb-2 text-[11px] text-muted">
        <label class="w-[50px]">Bed. {{ idx + 1 }}</label>
        <select class="flex-1 bg-white border border-border rounded-md px-2 py-1 text-[11px]" v-model="cond.source">
          <option value="primary">Unten</option>
          <option value="secondary">Links</option>
          <option value="tertiary">Rechts</option>
        </select>
      </div>
      <div class="flex items-center gap-2 mb-2 text-[11px] text-muted">
        <label class="w-[50px]">Wenn</label>
        <select class="w-[60px] bg-white border border-border rounded-md px-2 py-1 text-[11px]" v-model="cond.op">
          <option value="lt">&lt;</option>
          <option value="lte">&lt;=</option>
          <option value="eq">=</option>
          <option value="gte">&gt;=</option>
          <option value="gt">&gt;</option>
          <option value="neq">!=</option>
        </select>
        <input class="flex-1 bg-white border border-border rounded-md px-2 py-1 text-[11px]" type="number" step="0.1" v-model.number="cond.threshold" placeholder="Schwelle">
      </div>
      <div class="flex items-center gap-2 mb-2 text-[11px] text-muted">
        <label class="w-[50px]">Icon</label>
        <button class="flex-1 bg-white border border-border rounded-md px-2.5 py-1 text-[11px] flex items-center justify-center gap-1 cursor-pointer hover:bg-[#e4ebf2]" @click="$emit('open-condition-icon-picker', idx)">
          <span v-if="cond.icon" class="material-symbols-outlined text-[16px]">{{ String.fromCodePoint(cond.icon) }}</span>
          <span v-else>Kein Icon</span>
        </button>
        <button v-if="cond.icon" class="w-6 h-6 rounded-md border border-red-200 bg-[#f7dede] text-[#b3261e] grid place-items-center text-[11px] cursor-pointer hover:bg-[#f2cfcf]" @click="cond.icon = 0">x</button>
      </div>
      <div class="flex items-center gap-2 text-[11px] text-muted">
        <label class="w-[50px]">Farbe</label>
        <input class="h-[22px] w-[32px] cursor-pointer border-0 bg-transparent p-0" type="color" v-model="cond.textColor">
      </div>
    </div>

    <!-- Typography -->
    <h4 :class="headingClass">Typo</h4>
    <div :class="rowClass"><label :class="labelClass">Wert Schriftgr.</label>
      <select :class="inputClass" v-model.number="widget.fontSize">
        <option v-for="(size, idx) in fontSizes" :key="idx" :value="idx">{{ size }}</option>
      </select>
    </div>

    <!-- Icon -->
    <h4 :class="headingClass">Icon</h4>
    <div :class="rowClass">
      <label :class="labelClass">Icon</label>
      <button :class="iconSelectClass" @click="$emit('open-icon-picker')">
        <span v-if="widget.iconCodepoint" class="material-symbols-outlined text-[20px]">{{ String.fromCodePoint(widget.iconCodepoint) }}</span>
        <span v-else>Kein Icon</span>
      </button>
      <button v-if="widget.iconCodepoint" :class="iconRemoveClass" @click="widget.iconCodepoint = 0">x</button>
    </div>
    <template v-if="widget.iconCodepoint">
      <div :class="rowClass">
        <label :class="labelClass">Icon-Gr.</label>
        <select :class="inputClass" v-model.number="widget.iconSize">
          <option v-for="(size, idx) in fontSizes" :key="idx" :value="idx">{{ size }}</option>
        </select>
      </div>
    </template>

    <!-- Style -->
    <h4 :class="headingClass">Stil</h4>
    <div :class="rowClass"><label :class="labelClass">Textfarbe</label><input :class="colorInputClass" type="color" v-model="widget.textColor"></div>
    <div :class="rowClass"><label :class="labelClass">Ringfarbe</label><input :class="colorInputClass" type="color" v-model="widget.bgColor"></div>
    <div :class="rowClass"><label :class="labelClass">Ring Deckkraft</label><input :class="inputClass" type="number" min="0" max="255" v-model.number="widget.bgOpacity"></div>
    <h4 :class="headingClass">Rand</h4>
    <div :class="rowClass"><label :class="labelClass">Breite</label><input :class="inputClass" type="number" min="0" max="32" v-model.number="widget.borderWidth"></div>
    <div :class="rowClass"><label :class="labelClass">Farbe</label><input :class="colorInputClass" type="color" v-model="widget.borderColor"></div>
    <div :class="rowClass"><label :class="labelClass">Deckkraft</label><input :class="inputClass" type="number" min="0" max="255" v-model.number="widget.borderOpacity"></div>

    <!-- Glow -->
    <h4 :class="headingClass">Glow</h4>
    <div :class="rowClass"><label :class="labelClass">Aktiv</label><input class="accent-[var(--accent)]" type="checkbox" v-model="widget.shadow.enabled"></div>
    <div :class="rowClass"><label :class="labelClass">X</label><input :class="inputClass" type="number" v-model.number="widget.shadow.x"></div>
    <div :class="rowClass"><label :class="labelClass">Y</label><input :class="inputClass" type="number" v-model.number="widget.shadow.y"></div>
    <div :class="rowClass"><label :class="labelClass">Blur</label><input :class="inputClass" type="number" v-model.number="widget.shadow.blur"></div>
    <div :class="rowClass"><label :class="labelClass">Farbe</label><input :class="colorInputClass" type="color" v-model="widget.shadow.color"></div>
  </div>
</template>

<script setup>
import { computed } from 'vue';
import { useEditorStore } from '../../../stores/editor';
import { sourceOptions, textSources, textSourceGroups, fontSizes, defaultFormats } from '../../../constants';
import { rowClass, labelClass, inputClass, headingClass, subHeadingClass, iconSelectClass, iconRemoveClass, colorInputClass } from '../shared/styles';

const props = defineProps({
  widget: { type: Object, required: true }
});

defineEmits(['open-icon-picker', 'open-condition-icon-picker']);

const store = useEditorStore();

const conditions = computed(() => props.widget?.conditions ?? []);

const conditionCount = computed({
  get() {
    return conditions.value.length || 0;
  },
  set(value) {
    if (!props.widget) return;
    const target = Math.max(0, Math.min(value, 3));
    if (!Array.isArray(props.widget.conditions)) {
      props.widget.conditions = [];
    }
    while (props.widget.conditions.length < target) {
      props.widget.conditions.push({
        source: 'secondary',
        threshold: 0,
        op: 'lt',
        priority: props.widget.conditions.length,
        icon: 0,
        textColor: '#FF0000'
      });
    }
    if (props.widget.conditions.length > target) {
      props.widget.conditions = props.widget.conditions.slice(0, target);
    }
  }
});

const powerNodeLabel = computed({
  get() {
    return splitPowerNodeText(props.widget?.text).label;
  },
  set(value) {
    const parts = splitPowerNodeText(props.widget?.text);
    setPowerNodeText(value, parts.value);
  }
});

const powerNodeValue = computed({
  get() {
    return splitPowerNodeText(props.widget?.text).value;
  },
  set(value) {
    const parts = splitPowerNodeText(props.widget?.text);
    setPowerNodeText(parts.label, value);
  }
});

function groupedSources(options) {
  const allowed = new Set(options || []);
  return textSourceGroups
    .map((group) => ({
      label: group.label,
      values: group.values.filter((value) => allowed.has(value))
    }))
    .filter((group) => group.values.length > 0);
}

function handleTextSrcChange() {
  const newSrc = props.widget.textSrc;
  if (newSrc > 0 && defaultFormats[newSrc]) {
    const parts = splitPowerNodeText(props.widget.text);
    setPowerNodeText(parts.label, defaultFormats[newSrc]);
  }
}

function splitPowerNodeText(text) {
  if (typeof text !== 'string') return { label: '', value: '' };
  const parts = text.split('\n');
  const label = parts[0] ?? '';
  const value = parts.slice(1).join('\n');
  return { label, value };
}

function setPowerNodeText(label, value) {
  if (!props.widget) return;
  const labelLine = label ?? '';
  const valueLine = value ?? '';
  props.widget.text = valueLine !== '' || labelLine !== '' ? `${labelLine}${valueLine !== '' ? `\n${valueLine}` : ''}` : '';
}
</script>
