<script setup>
import { api, ensureCsrf } from "../../services/api.js";
import { useNavigation } from "../../composables/useNavigation.js";

import Button from "primevue/button";
import Message from "primevue/message";

import { cloneDeepForSave, normalizeTreeFromApi } from "./superadminNavigationTree.js";

import NavNodeEditor from "./NavNodeEditor.vue";
import { onMounted, ref } from "vue";

const loading = ref(false);
const saving = ref(false);
const error = ref("");
const tree = ref([]);
const modules = ref([]);
const permissions = ref([]);
const rootNode = ref(null);

const { fetchNavigation } = useNavigation();

async function loadModulesAndPermissions() {
  await ensureCsrf();
  const [modsRes, permRes] = await Promise.all([
    api.get("/api/superadmin/modules"),
    api.get("/api/permissions"),
  ]);
  modules.value = Array.isArray(modsRes.data?.modules) ? modsRes.data.modules : [];
  permissions.value = Array.isArray(permRes.data?.data)
    ? permRes.data.data
    : [];
}

async function loadTree() {
  loading.value = true;
  error.value = "";
  try {
    await ensureCsrf();
    await loadModulesAndPermissions();
    const { data } = await api.get("/api/superadmin/navigation-tree");
    const normalized = normalizeTreeFromApi(data?.tree ?? []);
    tree.value = normalized;
    rootNode.value = normalized[0] ?? null;
  } catch (e) {
    error.value =
      e?.response?.data?.message || "Could not load navigation tree.";
    tree.value = [];
    rootNode.value = null;
  } finally {
    loading.value = false;
  }
}

async function save() {
  if (!rootNode.value) return;
  saving.value = true;
  error.value = "";
  try {
    await ensureCsrf();
    const payload = {
      tree: cloneDeepForSave([rootNode.value]),
    };
    await api.put("/api/superadmin/navigation-tree", payload);
    await fetchNavigation();
    await loadTree();
  } catch (e) {
    const msg =
      e?.response?.data?.message ||
      (Array.isArray(e?.response?.data?.errors?.tree)
        ? e.response.data.errors.tree.join(" ")
        : null);
    error.value = msg || "Save failed. Check validation.";
  } finally {
    saving.value = false;
  }
}

onMounted(() => {
  loadTree();
});
</script>

<template>
  <div>
    <h1 class="title-h5 mb-4">Navigation structure</h1>
    <p class="body-small text-surface-600 dark:text-surface-400 mb-6">
      Edit sidebar entries (labels, routes, permissions). Each node uses
      <strong class="font-medium text-surface-700 dark:text-surface-300">Overview / Properties</strong>
      and
      <strong class="font-medium text-surface-700 dark:text-surface-300">Sub-items</strong>
      tabs so nested links stay organized. Save to apply.
    </p>
    <Message v-if="error" severity="error" class="mb-4" :closable="false">
      {{ error }}
    </Message>
    <Message
      v-if="!loading && !error && !rootNode"
      severity="warn"
      class="mb-4"
      :closable="false"
    >
      No navigation tree was returned (empty <code class="text-sm px-1">tree</code
      >). Usually that means rows were never seeded in
      <code class="text-sm px-1">maestro_navigation_nodes</code>. Run migrations,
      then:
      <code class="text-sm px-1 rounded bg-surface-100 dark:bg-surface-800"
        >php artisan db:seed --class=&quot;Maestro\\Core\\Database\\Seeders\\ModuleAndNavigationSeeder&quot;</code
      >
      — that creates the default root item and sidebar structure.
    </Message>
    <div class="flex flex-wrap gap-2 mb-6">
      <Button
        label="Reload"
        icon="pi pi-refresh"
        severity="secondary"
        outlined
        :loading="loading"
        type="button"
        @click="loadTree"
      />
      <Button
        label="Save navigation"
        icon="pi pi-save"
        :loading="saving"
        :disabled="loading || !rootNode"
        type="button"
        @click="save"
      />
    </div>
    <div v-if="rootNode">
      <NavNodeEditor
        :node="rootNode"
        :modules="modules"
        :permissions="permissions"
        :depth="0"
      />
    </div>
  </div>
</template>
