<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from "vue";
import { useNotesStore } from "../stores/notes";
import {
  LABEL_CHIP_CLASSES,
  NOTE_CARD_CLASSES,
  NOTE_COLOR_KEYS,
  NOTE_COLOR_LABELS,
  NOTE_SWATCH_CLASSES,
  type NoteColor,
} from "../notes/colors";
import type { Note } from "../stores/notes";
import Icon from "./Icon.vue";
import LinkPreview from "./LinkPreview.vue";
import MarkdownText from "./MarkdownText.vue";
import NoteChecklist from "./NoteChecklist.vue";
import { formatReminder, formatTrashCountdown, isOverdue, trashDaysLeft } from "../notes/datetime";
import { useConfigStore } from "../stores/config";

const props = defineProps<{ note: Note; reorderable?: boolean; active?: boolean }>();
const emit = defineEmits<{
  (e: "open", note: Note): void;
  (e: "dragstart", note: Note): void;
  (e: "dragend", note: Note): void;
  (e: "drop", note: Note): void;
}>();
const notes = useNotesStore();
const config = useConfigStore();

// --- Retention countdown. A note in Trash is on a clock, and the card is the only
// place someone browsing Trash would ever find that out in time to restore it.
// Null whenever nothing is going to happen: not trashed, or retention turned off. ---
const trashDays = computed(() =>
  props.note.trashed ? trashDaysLeft(props.note.deleted_at, config.trashRetentionDays) : null,
);
const trashCountdown = computed(() => formatTrashCountdown(trashDays.value));
// Same red the overdue reminder uses — the last few days are worth noticing.
const trashUrgent = computed(() => trashDays.value !== null && trashDays.value <= 3);

// The card previews the first image inline; non-image files show as compact chips.
const firstImage = computed(() => props.note.attachments.find((a) => a.mime.startsWith("image/")));
const otherAttachments = computed(() => props.note.attachments.filter((a) => !a.mime.startsWith("image/")));

const root = ref<HTMLElement | null>(null);

// --- Drag-to-reorder. Native HTML5 DnD, gated behind an explicit grip handle so
// a plain click/select never starts a drag by accident. `dragging` dims the
// source card; `dragOver` shows where the drop will land. ---
const canDrag = () => !!props.reorderable && !props.note.trashed;
const grabbing = ref(false); // handle pressed → the card is momentarily draggable
const dragging = ref(false); // this card is the one being dragged
const dragOver = ref(false); // another card is hovering over this one as a drop target

function onDragStart(e: DragEvent) {
  dragging.value = true;
  if (e.dataTransfer) {
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.setData("text/plain", props.note.id); // some browsers need a payload to drag
  }
  emit("dragstart", props.note);
}
function onDragEnd() {
  dragging.value = false;
  grabbing.value = false;
  dragOver.value = false;
  emit("dragend", props.note);
}
function onDragOver(e: DragEvent) {
  e.preventDefault(); // allow drop
  if (e.dataTransfer) e.dataTransfer.dropEffect = "move";
  if (!dragging.value) dragOver.value = true; // don't flag the source as its own target
}
function onDragLeave(e: DragEvent) {
  // dragleave also fires when moving onto a child; only clear when truly leaving the card.
  const to = e.relatedTarget as Node | null;
  if (to && root.value?.contains(to)) return;
  dragOver.value = false;
}
function onDrop() {
  dragOver.value = false;
  emit("drop", props.note);
}

// When this card becomes the keyboard-focused card, scroll it into view.
watch(
  () => props.active,
  (a) => {
    if (a) root.value?.scrollIntoView({ block: "nearest", behavior: "smooth" });
  },
);

function cardClass(color: NoteColor): string {
  return NOTE_CARD_CLASSES[color] ?? NOTE_CARD_CLASSES.default;
}

function labelChip(color: string): string {
  return LABEL_CHIP_CLASSES[color as NoteColor] ?? LABEL_CHIP_CLASSES.default;
}

// Per-card color popover (recolor without opening the editor).
const colorOpen = ref(false);

function swatch(color: string): string {
  return NOTE_SWATCH_CLASSES[color as NoteColor] ?? NOTE_SWATCH_CLASSES.default;
}

function pickColor(color: NoteColor) {
  colorOpen.value = false;
  void notes.setColor(props.note.id, color);
}

function onDocMousedown(e: MouseEvent) {
  if (colorOpen.value && root.value && !root.value.contains(e.target as Node)) colorOpen.value = false;
}
// Only listen for outside clicks while the popover is actually open.
watch(colorOpen, (open) => {
  if (open) document.addEventListener("mousedown", onDocMousedown);
  else document.removeEventListener("mousedown", onDocMousedown);
});
onBeforeUnmount(() => document.removeEventListener("mousedown", onDocMousedown));
</script>

<template>
  <div
    ref="root"
    class="group relative mb-4 break-inside-avoid rounded-xl border p-3 shadow-sm transition hover:shadow-md"
    :class="[
      cardClass(note.color),
      dragging ? 'opacity-40' : '',
      dragOver
        ? 'scale-[1.02] shadow-lg ring-2 ring-brand ring-offset-2 ring-offset-white dark:ring-offset-neutral-950'
        : '',
      active ? 'ring-2 ring-brand' : '',
    ]"
    :draggable="canDrag() && grabbing"
    @dragstart="onDragStart"
    @dragend="onDragEnd"
    @dragover="onDragOver"
    @dragleave="onDragLeave"
    @drop="onDrop"
  >
    <!-- Drag handle: reorder is gated behind this grip so a normal click/select
         never starts a drag. Appears on hover; board views only (reorderable).
         Mouse-only affordance — native DnD has no keyboard equivalent. -->
    <button
      v-if="canDrag()"
      type="button"
      tabindex="-1"
      class="pointer-events-none absolute left-1.5 top-1.5 z-10 flex cursor-grab items-center rounded-full bg-white/85 p-1 text-neutral-500 opacity-0 shadow-sm ring-1 ring-black/5 backdrop-blur-sm transition hover:text-neutral-800 active:cursor-grabbing group-hover:pointer-events-auto group-hover:opacity-100 dark:bg-neutral-900/85 dark:text-neutral-400 dark:ring-white/10 dark:hover:text-neutral-100"
      title="Drag to reorder"
      aria-label="Drag to reorder"
      @mousedown="grabbing = true"
      @mouseup="grabbing = false"
    >
      <Icon name="grip" />
    </button>

    <img
      v-if="firstImage"
      :src="firstImage.url"
      alt=""
      loading="lazy"
      decoding="async"
      class="mb-2 max-h-48 w-full cursor-pointer rounded-lg object-cover"
      @click="emit('open', note)"
    />
    <div v-if="otherAttachments.length" class="mb-2 flex flex-wrap gap-1">
      <span
        v-for="att in otherAttachments"
        :key="att.id"
        class="inline-flex max-w-full items-center gap-1 rounded-md bg-black/5 px-1.5 py-0.5 text-xs text-neutral-500 dark:bg-white/10 dark:text-neutral-400"
      >
        <Icon name="paperclip" />
        <span class="max-w-[140px] truncate">{{ att.filename || "file" }}</span>
      </span>
    </div>

    <div v-if="note.previews.length" class="mb-2 flex flex-col gap-2">
      <LinkPreview v-for="p in note.previews" :key="p.id" :preview="p" />
    </div>

    <!-- Checklist notes can't nest interactive controls in a <button>, so use a
         focusable div; text notes keep a semantic button. -->
    <template v-if="note.kind === 'list'">
      <div
        role="button"
        tabindex="0"
        class="rounded focus:outline-none focus-visible:ring-2 focus-visible:ring-brand"
        @click="emit('open', note)"
        @keydown.enter="emit('open', note)"
      >
        <h3 v-if="note.title" class="mb-1 break-words text-sm font-semibold text-neutral-900 dark:text-neutral-100">
          {{ note.title }}
        </h3>
      </div>
      <NoteChecklist class="mt-1" :note-id="note.id" :items="note.items" @click="emit('open', note)" />
    </template>

    <button
      v-else
      type="button"
      class="block w-full cursor-text rounded text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2 focus-visible:ring-offset-transparent"
      @click="emit('open', note)"
    >
      <h3 v-if="note.title" class="mb-1 break-words text-sm font-semibold text-neutral-900 dark:text-neutral-100">
        {{ note.title }}
      </h3>
      <div v-if="note.body" class="text-sm text-neutral-700 dark:text-neutral-300">
        <MarkdownText :text="note.body" />
      </div>
      <p v-if="!note.title && !note.body && !note.attachments.length" class="text-sm italic text-neutral-400">
        Empty note
      </p>
    </button>

    <div v-if="note.labels.length" class="mt-2 flex flex-wrap gap-1">
      <span
        v-for="lb in note.labels"
        :key="lb.id"
        class="rounded-full px-2 py-0.5 text-xs"
        :class="labelChip(lb.color)"
        >{{ lb.via_tag ? "#" + lb.name : lb.name }}</span
      >
    </div>

    <div v-if="note.remind_at" class="mt-2">
      <span
        class="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs"
        :class="
          isOverdue(note.remind_at)
            ? 'bg-red-100 text-red-700 dark:bg-red-950/50 dark:text-red-300'
            : 'bg-black/5 text-neutral-600 dark:bg-white/10 dark:text-neutral-300'
        "
      >
        <svg
          class="h-3 w-3"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <circle cx="12" cy="12" r="10" />
          <polyline points="12 6 12 12 16 14" />
        </svg>
        {{ formatReminder(note.remind_at) }}
      </span>
    </div>

    <div v-if="trashCountdown" class="mt-2">
      <span
        class="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs"
        :class="
          trashUrgent
            ? 'bg-red-100 text-red-700 dark:bg-red-950/50 dark:text-red-300'
            : 'bg-black/5 text-neutral-600 dark:bg-white/10 dark:text-neutral-300'
        "
        :title="`Permanently deleted ${config.trashRetentionDays} days after it was trashed`"
      >
        <svg
          class="h-3 w-3"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
        >
          <circle cx="12" cy="12" r="10" />
          <polyline points="12 6 12 12 16 14" />
        </svg>
        {{ trashCountdown }}
      </span>
    </div>

    <!-- Toolbar overlays the card's top-right on hover/focus as a floating pill
         (window-control style) instead of reserving a permanent row — so at rest
         the card is content-sized with even padding, not text pinned to the top
         above an empty strip. -->
    <div
      class="pointer-events-none absolute right-1.5 top-1.5 flex items-center gap-0.5 rounded-full bg-white/85 p-0.5 opacity-0 shadow-sm ring-1 ring-black/5 backdrop-blur-sm transition focus-within:pointer-events-auto focus-within:opacity-100 group-hover:pointer-events-auto group-hover:opacity-100 dark:bg-neutral-900/85 dark:ring-white/10"
    >
      <template v-if="note.trashed">
        <button type="button" class="icon-btn" title="Restore" aria-label="Restore" @click="notes.restore(note.id)">
          <Icon name="restore" />
        </button>
        <button
          type="button"
          class="icon-btn"
          title="Delete forever"
          aria-label="Delete forever"
          @click="notes.deleteForever(note.id)"
        >
          <Icon name="trash" />
        </button>
      </template>
      <template v-else>
        <button
          type="button"
          class="icon-btn"
          title="Change color"
          aria-label="Change color"
          @click.stop="colorOpen = !colorOpen"
        >
          <span
            class="h-4 w-4 rounded-full border border-black/10 dark:border-white/20"
            :class="swatch(note.color)"
          ></span>
        </button>
        <button
          type="button"
          class="icon-btn"
          :class="note.pinned ? 'text-brand-700 dark:text-brand' : ''"
          :title="note.pinned ? 'Unpin' : 'Pin'"
          :aria-label="note.pinned ? 'Unpin' : 'Pin'"
          :aria-pressed="note.pinned"
          @click="notes.setPinned(note.id, !note.pinned)"
        >
          <Icon name="pin" />
        </button>
        <button
          type="button"
          class="icon-btn"
          :title="note.archived ? 'Unarchive' : 'Archive'"
          :aria-label="note.archived ? 'Unarchive' : 'Archive'"
          @click="notes.setArchived(note.id, !note.archived)"
        >
          <Icon name="archive" />
        </button>
        <button
          type="button"
          class="icon-btn"
          title="Move to trash"
          aria-label="Move to trash"
          @click="notes.trash(note.id)"
        >
          <Icon name="trash" />
        </button>
      </template>
    </div>

    <div
      v-if="colorOpen"
      class="absolute right-1.5 top-11 z-20 flex w-40 flex-wrap gap-1.5 rounded-lg border border-neutral-200 bg-white p-2 shadow-lg dark:border-neutral-700 dark:bg-neutral-800"
    >
      <button
        v-for="key in NOTE_COLOR_KEYS"
        :key="key"
        type="button"
        :title="NOTE_COLOR_LABELS[key]"
        :aria-label="NOTE_COLOR_LABELS[key]"
        class="h-6 w-6 rounded-full border border-black/10 transition hover:scale-110 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand"
        :class="[NOTE_SWATCH_CLASSES[key], note.color === key ? 'ring-2 ring-brand' : '']"
        @click.stop="pickColor(key)"
      />
    </div>
  </div>
</template>
