<template>
  <header class="flex items-center justify-between gap-4 px-5 py-3.5 bg-[#f4f7fa] border-b border-border">
    <div class="flex items-center gap-3">
      <div class="w-9 h-9 rounded-[10px] bg-gradient-to-br from-accent to-[#86b7e6] text-white grid place-items-center font-bold tracking-[0.04em] shadow-[0_6px_16px_rgba(90,147,218,0.35)]">LV</div>
      <div class="flex flex-col">
        <div class="text-[18px] font-semibold">GUI Designer</div>
        <div class="text-[12px] text-muted">KNX Display</div>
      </div>
    </div>
    <div class="flex items-center gap-2.5 flex-wrap justify-end">
      <button class="border border-border bg-panel-2 text-text px-3.5 py-2 rounded-[10px] text-[13px] font-semibold transition hover:-translate-y-0.5 hover:bg-[#e4ebf2] active:translate-y-0.5" @click="emit('open-files')">Dateien</button>
      <button class="border border-border bg-panel-2 text-text px-3.5 py-2 rounded-[10px] text-[13px] font-semibold transition hover:-translate-y-0.5 hover:bg-[#e4ebf2] active:translate-y-0.5" @click="emit('open-settings')">Einstellungen</button>
      <button
        :class="[
          'border px-3.5 py-2 rounded-[10px] text-[13px] font-semibold transition hover:-translate-y-0.5 active:translate-y-0.5',
          knxProgMode ? 'border-red-200 bg-[#f7dede] text-[#b3261e] hover:bg-[#f2cfcf] shadow-[0_6px_14px_rgba(179,38,30,0.2)]' : 'border-border bg-panel-2 text-text hover:bg-[#e4ebf2]',
          knxProgPending ? 'opacity-60 cursor-not-allowed' : ''
        ]"
        :aria-pressed="knxProgMode"
        :disabled="knxProgPending"
        :title="knxProgMode ? 'KNX Programmiermodus aktiv' : 'KNX Programmiermodus aus'"
        @click="toggleKnxProg"
      >
        {{ knxProgMode ? 'KNX Prog AN' : 'KNX Prog AUS' }}
      </button>
      <button
        :class="[
          'border border-red-200 bg-[#f7dede] text-[#b3261e] px-3.5 py-2 rounded-[10px] text-[13px] font-semibold transition hover:-translate-y-0.5 hover:bg-[#f2cfcf] active:translate-y-0.5',
          knxResetPending ? 'opacity-60 cursor-not-allowed' : ''
        ]"
        :disabled="knxResetPending"
        title="KNX Einstellungen loeschen"
        @click="resetKnxSettings"
      >
        KNX Reset
      </button>
      <button class="border border-red-200 bg-[#f7dede] text-[#b3261e] px-3.5 py-2 rounded-[10px] text-[13px] font-semibold transition hover:-translate-y-0.5 hover:bg-[#f2cfcf] active:translate-y-0.5" @click="handleReset">Zuruecksetzen</button>
      <button class="border border-[#2b62a5] bg-[#2f6db8] text-white px-3.5 py-2 rounded-[10px] text-[13px] font-semibold transition hover:-translate-y-0.5 hover:bg-[#2b62a5] active:translate-y-0.5 shadow-[0_8px_18px_rgba(47,109,184,0.3)]" @click="handleSave">Speichern & Anwenden</button>
    </div>
  </header>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useEditorStore } from '../stores/editor';

const store = useEditorStore();
const emit = defineEmits(['open-settings', 'open-files']);
const knxProgMode = ref(false);
const knxProgPending = ref(false);
const knxResetPending = ref(false);

onMounted(() => {
  loadKnxProgMode();
});

async function handleSave() {
  try {
    await store.saveConfig();
    // alert('Gespeichert!'); 
    // Ideally use a toast/status indicator like in the original, but alert is fine for now
  } catch (e) {
    alert('Fehler beim Speichern');
  }
}

async function handleReset() {
  if (!confirm('Wirklich auf Standardeinstellungen zuruecksetzen?')) return;
  try {
    await store.resetConfig();
  } catch (e) {
    alert('Fehler');
    }
}

async function loadKnxProgMode() {
  try {
    const resp = await fetch('/api/knx/prog');
    if (!resp.ok) return;
    const data = await resp.json();
    if (typeof data.progMode === 'boolean') {
      knxProgMode.value = data.progMode;
    } else if (typeof data.enabled === 'boolean') {
      knxProgMode.value = data.enabled;
    }
  } catch (e) {
    // Ignore when API is not available.
  }
}

async function toggleKnxProg() {
  if (knxProgPending.value) return;
  const next = !knxProgMode.value;
  knxProgPending.value = true;
  try {
    const resp = await fetch('/api/knx/prog', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ enabled: next })
    });
    if (!resp.ok) {
      alert('KNX Prog fehlgeschlagen');
      return;
    }
    const data = await resp.json();
    const updated =
      typeof data.progMode === 'boolean'
        ? data.progMode
        : (typeof data.enabled === 'boolean' ? data.enabled : null);
    if (updated === null) {
      alert('KNX Prog fehlgeschlagen');
      return;
    }
    knxProgMode.value = updated;
  } catch (e) {
    alert('Fehler beim Umschalten');
  } finally {
    knxProgPending.value = false;
  }
}

async function resetKnxSettings() {
  if (knxResetPending.value) return;
  if (!confirm('KNX Einstellungen wirklich loeschen?\n\nDas Geraet startet neu und muss in ETS neu programmiert werden.')) return;
  knxResetPending.value = true;
  try {
    const resp = await fetch('/api/knx/reset', { method: 'POST' });
    if (!resp.ok) {
      alert('KNX Reset fehlgeschlagen');
      return;
    }
    alert('KNX Einstellungen geloescht. Geraet startet neu.');
  } catch (e) {
    alert('KNX Reset fehlgeschlagen');
  } finally {
    knxResetPending.value = false;
  }
}
</script>
