<script setup lang="ts">
import { onMounted, onUnmounted, computed, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useTasksStore } from "@/stores/tasks";
import { useNotesStore } from "@/stores/notes";
import { renderMarkdown } from "@/utils/markdown";
import { relativeTime } from "@/composables/useRelativeTime";
import { apiPost, apiGet } from "@/api/client";
import type { Note } from "@/types/note";
import type { TaskStatus } from "@/types/task";
import StatusBadge from "@/components/StatusBadge.vue";
import PriorityBadge from "@/components/PriorityBadge.vue";
import TagPill from "@/components/TagPill.vue";
import TableOfContents from "@/components/TableOfContents.vue";
import ShareDialog from "@/components/ShareDialog.vue";
import { Clock, Pencil, Link as LinkIcon } from "lucide-vue-next";

const route = useRoute();
const router = useRouter();
const store = useTasksStore();
const notesStore = useNotesStore();
const backlinks = ref<{ type: string; id: number; title: string }[]>([]);
const converting = ref(false);
const showShare = ref(false);

// Context enrichment
const projectTitle = ref<string | null>(null);
const milestoneName = ref<string | null>(null);
const subTasks = ref<Note[]>([]);

const taskId = computed(() => Number(route.params.id));

const statusCycle: Record<TaskStatus, TaskStatus> = {
  todo: "in_progress",
  in_progress: "done",
  done: "todo",
  cancelled: "todo",
};

const statusDotClass: Record<TaskStatus, string> = {
  todo: "dot-todo",
  in_progress: "dot-in-progress",
  done: "dot-done",
  cancelled: "dot-cancelled",
};

function cycleSubTaskStatus(subTask: Note) {
  if (!subTask.status) return;
  const next = statusCycle[subTask.status as TaskStatus];
  store.patchStatus(subTask.id, next).then(() => {
    const idx = subTasks.value.findIndex((t) => t.id === subTask.id);
    if (idx !== -1) subTasks.value[idx] = { ...subTasks.value[idx], status: next };
  });
}

async function loadContext(task: Note) {
  projectTitle.value = null;
  milestoneName.value = null;
  subTasks.value = [];

  const promises: Promise<void>[] = [];

  if (task.project_id) {
    promises.push(
      apiGet<any>(`/api/projects/${task.project_id}`).then((data) => {
        projectTitle.value = data.title ?? null;
        if (task.milestone_id && data.summary?.milestone_summary) {
          const ms = (data.summary.milestone_summary as Array<{ id: number; title: string }>)
            .find((m) => m.id === task.milestone_id);
          if (ms) milestoneName.value = ms.title;
        }
      }).catch(() => {})
    );
  }

  // Load sub-tasks via the notes endpoint with parent_id filter
  promises.push(
    apiGet<{ notes: Note[]; total: number }>(
      `/api/notes?parent_id=${task.id}&type=task&sort=created_at&order=asc&limit=50`
    ).then((data) => {
      subTasks.value = data.notes;
    }).catch(() => {})
  );

  await Promise.all(promises);
}

async function loadTask(id: number) {
  backlinks.value = [];
  await store.fetchTask(id);
  if (!store.currentTask) return;

  const [bl] = await Promise.allSettled([
    notesStore.fetchBacklinks(id),
    loadContext(store.currentTask),
  ]);
  if (bl.status === "fulfilled") backlinks.value = bl.value;
}

function handleKeydown(e: KeyboardEvent) {
  if (e.key !== "Escape") return;
  e.stopPropagation(); // prevent App.vue's global handler from also firing
  const active = document.activeElement as HTMLElement | null;
  if (active && active !== document.body) {
    (active as HTMLElement).blur();
    return;
  }
  if (store.currentTask?.project_id) {
    router.push(`/projects/${store.currentTask.project_id}`);
  } else {
    router.push("/tasks");
  }
}

onMounted(() => {
  loadTask(taskId.value);
  // Capture phase so this fires before App.vue's document-level handler
  window.addEventListener("keydown", handleKeydown, true);
});
onUnmounted(() => window.removeEventListener("keydown", handleKeydown, true));

watch(() => route.params.id, (newId) => {
  if (newId) loadTask(Number(newId));
});

const renderedBody = computed(() => {
  if (!store.currentTask) return "";
  return renderMarkdown(store.currentTask.body);
});

function cycleStatus() {
  if (!store.currentTask) return;
  store.patchStatus(
    store.currentTask.id,
    statusCycle[store.currentTask.status as TaskStatus]
  );
}

const forwardStatus: Record<TaskStatus, TaskStatus | null> = {
  todo: "in_progress",
  in_progress: "done",
  done: null,
  cancelled: null,
};

function recurrenceSummary(rule: Record<string, unknown> | null): string | null {
  if (!rule) return null;
  if (rule.type === "interval") {
    return `Every ${rule.every} ${rule.unit}(s)`;
  }
  if (rule.type === "calendar") {
    if (rule.unit === "month") return `Monthly on day ${rule.day_of_month}`;
    if (rule.unit === "year") {
      const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
      const m = months[((rule.month as number) ?? 1) - 1];
      return `Yearly on ${m} ${rule.day_of_month}`;
    }
  }
  return null;
}

const advanceLabel = computed(() => {
  const s = store.currentTask?.status as TaskStatus | undefined;
  if (!s) return null;
  const next = forwardStatus[s];
  if (!next) return null;
  return next === "in_progress" ? "→ In Progress" : "→ Done";
});

function advanceStatus() {
  if (!store.currentTask) return;
  const next = forwardStatus[store.currentTask.status as TaskStatus];
  if (next) store.patchStatus(store.currentTask.id, next);
}

function isOverdue(): boolean {
  if (!store.currentTask?.due_date || store.currentTask.status === "done")
    return false;
  const today = new Date().toISOString().slice(0, 10);
  return store.currentTask.due_date < today;
}

async function convertToNote() {
  if (converting.value) return;
  converting.value = true;
  try {
    await notesStore.convertToNote(taskId.value);
    const { useToastStore } = await import("@/stores/toast");
    useToastStore().show("Converted to note");
    router.push(`/notes/${taskId.value}`);
  } catch {
    const { useToastStore } = await import("@/stores/toast");
    useToastStore().show("Failed to convert task", "error");
  } finally {
    converting.value = false;
  }
}

async function onBodyClick(e: MouseEvent) {
  const target = e.target as HTMLElement;

  const tagLink = target.closest(".inline-tag") as HTMLAnchorElement | null;
  if (tagLink) {
    e.preventDefault();
    const tag = tagLink.dataset.tag;
    if (tag) {
      router.push({ path: "/notes", query: { tag } });
    }
    return;
  }

  const wikilink = target.closest(".wikilink") as HTMLAnchorElement | null;
  if (wikilink) {
    e.preventDefault();
    const title = wikilink.dataset.title;
    if (title) {
      try {
        const note = await apiPost<Note>(
          "/api/notes/resolve-title",
          { title }
        );
        router.push(`/notes/${note.id}`);
      } catch {
        const { useToastStore } = await import("@/stores/toast");
        useToastStore().show(`Failed to resolve note "${title}"`, "error");
      }
    }
  }
}

function onTagClick(tag: string) {
  router.push({ path: "/tasks", query: { tag } });
}

// Sub-task progress
const subTaskProgress = computed(() => {
  if (!subTasks.value.length) return null;
  const done = subTasks.value.filter((t) => t.status === "done").length;
  const total = subTasks.value.length;
  return { done, total, pct: Math.round((done / total) * 100) };
});
</script>

<template>
  <div class="viewer-layout">
    <main class="viewer">
      <div v-if="store.loading" class="viewer-skeleton" aria-label="Loading task">
        <div class="skel-toolbar">
          <div class="skel-btn"></div>
          <div class="skel-btn skel-btn--wide"></div>
          <div class="skel-btn"></div>
        </div>
        <div class="skel-title"></div>
        <div class="skel-meta"></div>
        <div class="skel-badges"></div>
        <div class="skel-line"></div>
        <div class="skel-line skel-line--short"></div>
        <div class="skel-line"></div>
        <div class="skel-line skel-line--medium"></div>
        <div class="skel-line skel-line--short"></div>
      </div>
      <template v-else-if="store.currentTask">
        <div class="toolbar">
          <router-link
            :to="store.currentTask.project_id ? `/projects/${store.currentTask.project_id}` : '/tasks'"
            class="btn-ghost"
          >{{ store.currentTask.project_id ? "← Project" : "← Tasks" }}</router-link>
          <router-link
            :to="`/tasks/${store.currentTask.id}/edit`"
            class="btn-primary"
          >
            Edit
          </router-link>
          <button
            v-if="advanceLabel"
            class="btn-primary"
            @click="advanceStatus"
          >
            {{ advanceLabel }}
          </button>
          <button
            class="btn-secondary btn-compact"
            @click="convertToNote"
            :disabled="converting"
          >
            {{ converting ? "Converting..." : "Convert to Note" }}
          </button>
          <button class="btn-secondary btn-compact" @click="showShare = true">Share</button>
        </div>

        <!-- Breadcrumb: parent task → project → milestone -->
        <div
          v-if="store.currentTask.parent_id || store.currentTask.project_id"
          class="context-bar"
        >
          <router-link
            v-if="store.currentTask.parent_id"
            :to="`/tasks/${store.currentTask.parent_id}`"
            class="ctx-crumb ctx-crumb-parent"
          >
            ↑ {{ store.currentTask.parent_title || "Parent task" }}
          </router-link>
          <router-link
            v-if="store.currentTask.project_id && projectTitle"
            :to="`/projects/${store.currentTask.project_id}`"
            class="ctx-crumb ctx-crumb-project"
          >
            {{ projectTitle }}
          </router-link>
          <span v-if="milestoneName" class="ctx-crumb ctx-crumb-milestone">
            {{ milestoneName }}
          </span>
        </div>

        <h1 class="task-title">{{ store.currentTask.title || "Untitled" }}</h1>
        <p class="meta">
          <span class="meta-item">
            <Clock :size="16" />
            Updated {{ relativeTime(store.currentTask.updated_at) }}
          </span>
          <span class="meta-sep" aria-hidden="true">·</span>
          <span class="meta-item">
            <Pencil :size="16" />
            Created {{ relativeTime(store.currentTask.created_at) }}
          </span>
        </p>
        <div class="badges">
          <StatusBadge
            :status="store.currentTask.status!"
            clickable
            @click="cycleStatus"
          />
          <PriorityBadge :priority="store.currentTask.priority!" />
          <span
            v-if="store.currentTask.due_date"
            :class="['due-date', { overdue: isOverdue() }]"
          >
            Due: {{ store.currentTask.due_date }}
          </span>
        </div>
        <div class="task-meta-row" v-if="store.currentTask.started_at || store.currentTask.completed_at || store.currentTask.recurrence_rule">
          <span v-if="store.currentTask.started_at" class="task-meta-item">
            Started: {{ new Date(store.currentTask.started_at).toLocaleString() }}
          </span>
          <span v-if="store.currentTask.completed_at" class="task-meta-item">
            Completed: {{ new Date(store.currentTask.completed_at).toLocaleString() }}
          </span>
          <span v-if="recurrenceSummary(store.currentTask.recurrence_rule as Record<string, unknown> | null)" class="task-meta-item task-meta-recurrence">
            ↻ {{ recurrenceSummary(store.currentTask.recurrence_rule as Record<string, unknown> | null) }}
          </span>
        </div>
        <div class="tags" v-if="store.currentTask.tags.length">
          <TagPill
            v-for="tag in store.currentTask.tags"
            :key="tag"
            :tag="tag"
            @click="onTagClick"
          />
        </div>
        <div
          v-if="store.currentTask.description"
          class="task-goal-display"
        >
          <h3 class="goal-label">Goal</h3>
          <p class="goal-text">{{ store.currentTask.description }}</p>
        </div>


        <div
          class="body prose"
          v-html="renderedBody"
          @click="onBodyClick"
        ></div>

        <!-- Sub-tasks -->
        <div v-if="subTasks.length" class="subtasks">
          <div class="subtasks-header">
            <h2 class="subtasks-title">Sub-tasks</h2>
            <span v-if="subTaskProgress" class="subtasks-progress">
              {{ subTaskProgress.done }}/{{ subTaskProgress.total }}
              <span class="subtasks-pct">({{ subTaskProgress.pct }}%)</span>
            </span>
          </div>
          <div v-if="subTaskProgress" class="subtasks-track">
            <div class="subtasks-fill" :style="{ width: subTaskProgress.pct + '%' }"></div>
          </div>
          <ul class="subtasks-list">
            <li
              v-for="sub in subTasks"
              :key="sub.id"
              class="subtask-row"
            >
              <button
                :class="['sub-dot', statusDotClass[sub.status as TaskStatus] ?? 'dot-todo']"
                :title="`${sub.status} — click to advance`"
                @click="cycleSubTaskStatus(sub)"
              ></button>
              <router-link :to="`/tasks/${sub.id}/edit`" class="sub-title" :class="{ 'sub-done': sub.status === 'done' }">
                {{ sub.title || "Untitled" }}
              </router-link>
              <span v-if="sub.due_date" class="sub-due">{{ sub.due_date }}</span>
            </li>
          </ul>
        </div>

        <div v-if="backlinks.length" class="backlinks">
          <h3 class="backlinks-heading">
            <LinkIcon :size="16" />
            Backlinks
            <span class="backlinks-count">{{ backlinks.length }}</span>
          </h3>
          <div class="backlinks-grid">
            <router-link
              v-for="link in backlinks"
              :key="`${link.type}-${link.id}`"
              :to="`/${link.type === 'note' ? 'notes' : 'tasks'}/${link.id}`"
              class="backlink-card"
            >
              <span :class="['backlink-type-badge', `badge-${link.type}`]">{{ link.type }}</span>
              <span class="backlink-title">{{ link.title || "Untitled" }}</span>
            </router-link>
          </div>
        </div>
      </template>
      <p v-else>Task not found.</p>
    </main>
    <TableOfContents
      v-if="store.currentTask?.body"
      :body="store.currentTask.body"
      class="toc-sidebar"
    />
  </div>

  <ShareDialog
    v-if="showShare && store.currentTask"
    resource-type="note"
    :resource-id="store.currentTask.id"
    :resource-title="store.currentTask.title || '(untitled)'"
    @close="showShare = false"
  />
</template>

<style src="@/assets/viewer-shared.css" />
<style scoped>
.viewer-layout {
  display: flex;
  max-width: 1400px;
  margin: 0 auto;
  gap: 2rem;
}
.viewer {
  flex: 1;
  min-width: 0;
  max-width: 1100px;
  margin: 2rem 0;
  padding: 0 1rem;
}
.toc-sidebar {
  margin-top: 2rem;
}
@media (max-width: 1200px) {
  .toc-sidebar {
    display: none;
  }
}
.toolbar {
  display: flex;
  gap: 0.75rem;
  margin-bottom: 0.75rem;
}

.meta {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  flex-wrap: wrap;
  font-size: 0.83rem;
  color: var(--fs-text-tertiary);
  margin: 0 0 0.75rem;
}
.meta-item {
  display: inline-flex;
  align-items: center;
  gap: 0.3rem;
}
.meta-sep {
  opacity: 0.5;
}
.badges {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
}
.due-date {
  font-size: 0.85rem;
  color: var(--fs-text-secondary);
}
.due-date.overdue {
  color: var(--fs-overdue);
  font-weight: 500;
}
.task-meta-row {
  display: flex;
  flex-wrap: wrap;
  gap: 0.75rem;
  margin-bottom: 0.5rem;
}
.task-meta-item {
  font-size: 0.78rem;
  color: var(--fs-text-tertiary);
}
.task-meta-recurrence {
  color: var(--fs-accent);
  font-weight: 500;
}
.tags {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1rem;
  flex-wrap: wrap;
}

/* Sub-tasks */
.subtasks {
  margin-top: 2rem;
  border-top: 1px solid var(--fs-border-color);
  padding-top: 1rem;
}
.subtasks-header {
  display: flex;
  align-items: baseline;
  gap: 0.6rem;
  margin-bottom: 0.4rem;
}
.subtasks-title {
  font-size: 1rem;
  margin: 0;
  font-weight: 500;
}
.subtasks-progress {
  font-size: 0.8rem;
  color: var(--fs-text-tertiary);
}
.subtasks-pct {
  color: var(--fs-text-tertiary);
}
.subtasks-track {
  height: 4px;
  background: var(--fs-surface-raised);
  border-radius: 2px;
  margin-bottom: 0.75rem;
  overflow: hidden;
}
.subtasks-fill {
  height: 100%;
  background: var(--fs-status-done);
  border-radius: 2px;
  transition: width 0.3s ease;
}
.subtasks-list {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
  gap: 0.2rem;
}
.subtask-row {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.3rem 0.5rem;
  border-radius: var(--fs-radius-sm);
}
.subtask-row:hover {
  background: var(--fs-surface-raised);
}
.sub-dot {
  flex-shrink: 0;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: none;
  cursor: pointer;
  padding: 0;
  transition: transform 0.1s, opacity 0.1s;
}
.sub-dot:hover {
  transform: scale(1.25);
  opacity: 0.8;
}
.dot-todo {
  background: transparent;
  border: 2px solid var(--fs-text-tertiary);
}
.dot-in-progress {
  background: var(--fs-status-in-progress);
}
.dot-done {
  background: var(--fs-status-done);
}
.dot-cancelled {
  background: var(--fs-text-tertiary);
}
.sub-title {
  flex: 1;
  font-size: 0.9rem;
  color: var(--fs-text-primary);
  text-decoration: none;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.sub-title:hover {
  color: var(--fs-accent);
}
.sub-title.sub-done {
  color: var(--fs-text-tertiary);
  text-decoration: line-through;
}
.sub-due {
  font-size: 0.75rem;
  color: var(--fs-text-tertiary);
  flex-shrink: 0;
}

.backlinks {
  margin-top: 2.5rem;
  border-top: 1px solid var(--fs-border-color);
  padding-top: 1.25rem;
}
.backlinks-heading {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  font-size: 0.78rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.06em;
  color: var(--fs-text-tertiary);
  margin: 0 0 0.75rem;
}
.backlinks-count {
  margin-left: 0.2rem;
  font-size: 0.72rem;
  background: var(--fs-surface-raised);
  border: 1px solid var(--fs-border-color);
  border-radius: 999px;
  padding: 0 0.4rem;
  line-height: 1.4;
}
.backlinks-grid {
  display: flex;
  flex-direction: column;
  gap: 0.4rem;
}
.backlink-card {
  display: flex;
  align-items: center;
  gap: 0.6rem;
  padding: 0.5rem 0.75rem;
  border-radius: var(--fs-radius-lg);
  background: var(--fs-surface-raised);
  border: 1px solid var(--fs-border-color);
  text-decoration: none;
  color: var(--fs-text-primary);
  transition: border-color 0.15s, box-shadow 0.15s;
  font-size: 0.9rem;
}
.backlink-card:hover {
  border-color: color-mix(in srgb, var(--fs-accent) 50%, transparent);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  color: var(--fs-accent);
}
.backlink-type-badge {
  font-size: 0.68rem;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  font-weight: 500;
  padding: 0.1rem 0.45rem;
  border-radius: 999px;
  flex-shrink: 0;
}
.badge-note {
  background: color-mix(in srgb, var(--fs-accent) 12%, transparent);
  color: var(--fs-accent);
  border: 1px solid color-mix(in srgb, var(--fs-accent) 25%, transparent);
}
.badge-task {
  background: color-mix(in srgb, #f59e0b 12%, transparent);
  color: #d97706;
  border: 1px solid color-mix(in srgb, #f59e0b 30%, transparent);
}
.backlink-title {
  flex: 1;
  min-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* ── Skeleton loader ── */
@keyframes skel-shine {
  to { background-position: 200% center; }
}
.viewer-skeleton {
  display: flex;
  flex-direction: column;
  gap: 0.65rem;
  padding-top: 0.5rem;
}
.skel-btn,
.skel-title,
.skel-meta,
.skel-badges,
.skel-line {
  border-radius: var(--fs-radius-sm);
  background: linear-gradient(
    90deg,
    var(--fs-surface-raised) 25%,
    color-mix(in srgb, var(--fs-text-tertiary) 18%, var(--fs-surface-raised)) 50%,
    var(--fs-surface-raised) 75%
  );
  background-size: 200% 100%;
  animation: skel-shine 1.5s ease infinite;
}
.skel-toolbar {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 0.25rem;
}
.skel-btn { width: 70px; height: 32px; }
.skel-btn--wide { width: 90px; }
.skel-title { height: 2.2rem; width: 65%; border-radius: var(--fs-radius-lg); }
.skel-meta { height: 0.85rem; width: 45%; }
.skel-badges { height: 1.6rem; width: 30%; border-radius: 999px; }
.skel-line { height: 0.9rem; }
.skel-line--short { width: 50%; }
.skel-line--medium { width: 78%; }

/* ── Goal block + auto-summary banner ─────────────────────────────────────── */
.task-goal-display {
  border-left: 2px solid var(--fs-border-color);
  padding: 0.4rem 0 0.4rem 0.9rem;
  margin: 0.75rem 0 1.25rem;
  background: rgba(255, 255, 255, 0.02);
}
.goal-label {
  font-family: var(--fs-font-display);
  font-style: italic;
  font-size: 0.78rem;
  font-weight: 500;
  letter-spacing: 0.04em;
  text-transform: uppercase;
  color: var(--fs-text-tertiary);
  margin: 0 0 0.25rem;
}
.goal-text {
  margin: 0;
  font-size: 0.95rem;
  line-height: 1.45;
  color: var(--fs-text-primary);
  white-space: pre-wrap;
}
</style>
