<script setup>
import { ref, watch } from 'vue'
import { fetchElements, createElement, deleteElement } from '../../api.js'
import ElementList from './ElementList.vue'
import ElementDetail from './ElementDetail.vue'

const props = defineProps({
  topic: { type: String, required: true },
  provider: { type: String, default: 'claude' },
  openId: { type: String, default: null },   // Element-ID, die geöffnet werden soll
  openTick: { type: Number, default: 0 },    // Erhöhung = openId (erneut) öffnen
})

const emit = defineEmits(['close', 'changed'])

const elements = ref([])
const creating = ref(false)
const selected = ref(null)

watch(() => props.topic, load, { immediate: true })

async function load() {
  selected.value = null
  try {
    elements.value = await fetchElements(props.topic)
  } catch (e) {
    console.error('Fehler beim Laden der Elemente:', e)
  }
  openFromProp()
}

// Aus der Übersicht im Hauptbereich angeklicktes Element öffnen
watch(() => props.openTick, openFromProp)

function openFromProp() {
  if (!props.openId) return
  const el = elements.value.find((e) => e.id === props.openId)
  if (el) selected.value = el
}

async function create(hint) {
  if (creating.value) return
  creating.value = true
  try {
    const el = await createElement(props.topic, hint, props.provider)
    elements.value.unshift(el)
    emit('changed')
  } catch (e) {
    console.error('Fehler beim Erstellen des Elements:', e)
  } finally {
    creating.value = false
  }
}

async function remove(el) {
  await deleteElement(el.id)
  elements.value = elements.value.filter((e) => e.id !== el.id)
  if (selected.value?.id === el.id) selected.value = null
  emit('changed')
}

// Bearbeitetes Element in Liste und Auswahl synchron halten
function onUpdated(el) {
  selected.value = el
  const idx = elements.value.findIndex((e) => e.id === el.id)
  if (idx !== -1) elements.value.splice(idx, 1, el)
  emit('changed')
}
</script>

<template>
  <aside class="elements-sidebar">
    <ElementDetail
      v-if="selected"
      :element="selected"
      :provider="provider"
      @back="selected = null"
      @close="emit('close')"
      @updated="onUpdated"
      @changed="emit('changed')"
    />
    <template v-else>
      <header class="el-header">
        <span class="el-title">Elemente</span>
        <button class="el-close" title="Schließen" @click="emit('close')">×</button>
      </header>
      <ElementList
        :elements="elements"
        :creating="creating"
        @select="(el) => (selected = el)"
        @create="create"
        @remove="remove"
      />
    </template>
  </aside>
</template>

<style scoped>
.elements-sidebar {
  width: 320px;
  min-width: 320px;
  height: 100dvh;
  display: flex;
  flex-direction: column;
  background: var(--panel);
  border-left: 1px solid var(--border);
  /* Über dem Guide-Chat (FAB/Panel: z-index 20) */
  position: relative;
  z-index: 30;
}

/* Mobil/schmal: als Overlay über den Hauptinhalt legen, statt ihn
   im Flex-Fluss einzuquetschen. */
@media (max-width: 768px) {
  .elements-sidebar {
    position: fixed;
    top: 0;
    right: 0;
    width: min(100vw, 380px);
    min-width: 0;
    box-shadow: -4px 0 16px var(--shadow);
  }
}

.el-header {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 0.6rem 0.9rem;
  border-bottom: 1px solid var(--border);
}

.el-title {
  flex: 1;
  font-weight: 600;
  font-size: 0.9rem;
  color: var(--text);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.el-close {
  border: none;
  background: none;
  color: var(--text-faint);
  font-size: 1.2rem;
  line-height: 1;
  cursor: pointer;
  padding: 0 4px;
}

.el-close:hover {
  color: var(--text);
}
</style>
