<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useNotesStore, type Note, type NoteView } from "../stores/notes";
import { useUiStore } from "../stores/ui";
import QuickAdd from "../components/QuickAdd.vue";
import NoteCard from "../components/NoteCard.vue";
import NoteEditor from "../components/NoteEditor.vue";

const notes = useNotesStore();
const route = useRoute();
const ui = useUiStore();
const router = useRouter();

const editing = ref<Note | null>(null);
const quickAdd = ref<InstanceType<typeof QuickAdd> | null>(null);

// The global `c` shortcut bumps composeTick; reopen the composer when we're
// already on the board (a fresh navigation autofocuses it via the prop).
watch(
  () => ui.composeTick,
  () => quickAdd.value?.open(),
);

// The command palette opens a note by navigating here with ?open=<id>.
watch(
  () => route.query.open,
  (v) => {
    if (typeof v === "string" && v) void openFromQuery(v);
  },
  { immediate: true },
);
async function openFromQuery(id: string) {
  const found = notes.items.find((n) => n.id === id) ?? (await notes.fetchOne(id));
  if (found) editing.value = found;
  const q = { ...route.query };
  delete q.open;
  void router.replace({ query: q });
}

function viewForRoute(name: unknown): NoteView {
  if (name === "archive") return "archived";
  if (name === "trash") return "trash";
  return "active"; // board + label views
}

const currentView = computed<NoteView>(() => viewForRoute(route.name));
const currentLabel = computed<string | null>(() => (route.name === "label" ? String(route.params.id) : null));

// Quick-add + pinned/others split only on the main board (not archive/trash/label).
const isMainBoard = computed(() => route.name === "board");
const pinnedNotes = computed(() => notes.items.filter((n) => n.pinned));
const otherNotes = computed(() => notes.items.filter((n) => !n.pinned));

const emptyState = computed(() => {
  if (currentView.value === "trash") return { title: "Trash is empty", subtitle: "Notes you delete land here first." };
  if (currentView.value === "archived")
    return { title: "Nothing archived", subtitle: "Archived notes are tucked away here." };
  if (currentLabel.value) return { title: "No notes with this label", subtitle: "Tag a note to see it here." };
  return { title: "No notes yet", subtitle: "Capture your first thought in the box above." };
});

async function reload() {
  await notes.load(currentView.value, currentLabel.value);
}

onMounted(reload);
watch([currentView, currentLabel], reload);

function openEditor(note: Note) {
  editing.value = note;
}
function closeEditor() {
  editing.value = null;
}

async function onNavigate(id: string) {
  const found = notes.items.find((n) => n.id === id);
  if (found) {
    editing.value = found;
    return;
  }
  const fetched = await notes.fetchOne(id);
  if (fetched) editing.value = fetched;
}

const draggingId = ref<string | null>(null);
function onDragStart(note: Note) {
  draggingId.value = note.id;
}
async function onDrop(target: Note) {
  const from = draggingId.value;
  draggingId.value = null;
  if (!from || from === target.id) return;
  const order = notes.items.map((n) => n.id);
  const fromIdx = order.indexOf(from);
  const toIdx = order.indexOf(target.id);
  if (fromIdx < 0 || toIdx < 0) return;
  order.splice(fromIdx, 1);
  order.splice(toIdx, 0, from);
  await notes.reorder(order);
}
</script>

<template>
  <div class="mx-auto w-full max-w-6xl px-4 py-6">
    <QuickAdd v-if="isMainBoard" ref="quickAdd" autofocus class="mb-8" />

    <div v-if="notes.loading" class="py-24 text-center text-sm text-neutral-400">Loading…</div>

    <div v-else-if="notes.items.length === 0" class="py-24 text-center">
      <h2 class="text-lg font-semibold text-neutral-700 dark:text-neutral-200">{{ emptyState.title }}</h2>
      <p class="mt-1 text-sm text-neutral-400">{{ emptyState.subtitle }}</p>
    </div>

    <template v-else>
      <template v-if="isMainBoard">
        <section v-if="pinnedNotes.length">
          <h2 class="mb-2 text-xs font-semibold uppercase tracking-wide text-neutral-400">Pinned</h2>
          <div class="columns-1 gap-4 sm:columns-2 lg:columns-3 xl:columns-4">
            <NoteCard
              v-for="n in pinnedNotes"
              :key="n.id"
              :note="n"
              reorderable
              @open="openEditor"
              @dragstart="onDragStart"
              @drop="onDrop"
            />
          </div>
        </section>
        <section v-if="otherNotes.length" :class="pinnedNotes.length ? 'mt-8' : ''">
          <h2 v-if="pinnedNotes.length" class="mb-2 text-xs font-semibold uppercase tracking-wide text-neutral-400">
            Others
          </h2>
          <div class="columns-1 gap-4 sm:columns-2 lg:columns-3 xl:columns-4">
            <NoteCard
              v-for="n in otherNotes"
              :key="n.id"
              :note="n"
              reorderable
              @open="openEditor"
              @dragstart="onDragStart"
              @drop="onDrop"
            />
          </div>
        </section>
      </template>

      <div v-else class="columns-1 gap-4 sm:columns-2 lg:columns-3 xl:columns-4">
        <NoteCard
          v-for="n in notes.items"
          :key="n.id"
          :note="n"
          reorderable
          @open="openEditor"
          @dragstart="onDragStart"
          @drop="onDrop"
        />
      </div>
    </template>
  </div>

  <template v-if="editing">
    <NoteEditor :note="editing" @close="closeEditor" @navigate="onNavigate" />
  </template>
</template>
