<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { apiGet, apiPost, apiErrorMessage } from "@/api/client";
import { emptyChoices, type InceptionChoices } from "@/api/inception";
import InceptionCard from "@/components/InceptionCard.vue";
import { useToastStore } from "@/stores/toast";
import { milestoneColor } from "@/utils/palette";

interface MilestoneSummary {
  id: number;
  title: string;
  status: string;
  pct: number;
  total: number;
  completed: number;
}

interface Project {
  id: number;
  user_id: number;
  title: string;
  description: string | null;
  goal: string | null;
  status: "active" | "paused" | "completed" | "archived";
  color: string | null;
  permission?: string;
  is_shared?: boolean;
  created_at: string;
  updated_at: string;
  summary?: {
    task_counts: { todo?: number; in_progress?: number; done?: number };
    note_count: number;
    milestone_summary: MilestoneSummary[];
  };
}

const router = useRouter();
const toast = useToastStore();

const projects = ref<Project[]>([]);
const loading = ref(false);
const error = ref<string | null>(null);
const activeTab = ref<"all" | "active" | "paused" | "completed" | "archived">("all");

// New project modal
const showNewProjectModal = ref(false);
const newTitle = ref("");
const newDescription = ref("");
const newGoal = ref("");
const creating = ref(false);
// Step 2 of the modal (milestone 297): what the new project inherits.
const modalStep = ref<1 | 2>(1);
const newInception = ref<InceptionChoices>(emptyChoices());

const filteredProjects = computed(() => {
  if (activeTab.value === "all") return projects.value;
  return projects.value.filter((p) => p.status === activeTab.value);
});

async function loadProjects() {
  loading.value = true;
  error.value = null;
  try {
    const data = await apiGet<{ projects: Project[] }>("/api/projects?include_summary=true");
    projects.value = data.projects;
  } catch {
    error.value = "Failed to load projects.";
  } finally {
    loading.value = false;
  }
}


onMounted(loadProjects);

function openNewProjectModal() {
  newTitle.value = "";
  newDescription.value = "";
  newGoal.value = "";
  modalStep.value = 1;
  newInception.value = emptyChoices();
  showNewProjectModal.value = true;
}

function closeModal() {
  showNewProjectModal.value = false;
}

async function createProject() {
  if (!newTitle.value.trim()) return;
  creating.value = true;
  try {
    const project = await apiPost<Project>("/api/projects", {
      title: newTitle.value.trim(),
      description: newDescription.value.trim() || undefined,
      goal: newGoal.value.trim() || undefined,
      // The decision rides the create: a project made here is never undecided.
      inception: newInception.value,
    });
    projects.value.unshift(project);
    showNewProjectModal.value = false;
    toast.show("Project created");
    router.push(`/projects/${project.id}`);
  } catch (e: unknown) {
    toast.show(apiErrorMessage(e, "Failed to create project"), "error");
  } finally {
    creating.value = false;
  }
}

function statusLabel(status: Project["status"]): string {
  if (status === "active") return "Active";
  if (status === "paused") return "Paused";
  if (status === "completed") return "Completed";
  if (status === "archived") return "Archived";
  return status;
}

function truncate(text: string | null, max = 120): string {
  if (!text) return "";
  return text.length > max ? text.slice(0, max) + "..." : text;
}

// A card is a glance, not a report. Roundtable had ~35 milestones and its tile
// ran several viewport-heights tall, which made the grid unreadable (#2391).
const MAX_MILESTONE_BARS = 10;

interface MilestoneBar extends MilestoneSummary {
  /** Position in the FULL list, so a bar keeps its colour when another
   *  milestone is added or finishes. Tying the palette to the visible index
   *  would recolour the card every time work closed. */
  paletteIndex: number;
}

/** Bars to draw per project, plus how many were withheld.
 *
 * Ordered OPEN WORK FIRST, newest first. Recency alone would be wrong here: a
 * long-running project's oldest milestones are usually its finished ones, so
 * showing 10 completed bars while hiding the 3 in flight is worse than showing
 * nothing. What the card is for is "what is happening", not "what happened".
 *
 * Computed once per load rather than called from the template — a helper in a
 * v-for is re-run on every render, and this one sorts.
 */
const milestoneBars = computed(() => {
  const byProject = new Map<number, { bars: MilestoneBar[]; hidden: number }>();
  for (const project of projects.value) {
    const all = project.summary?.milestone_summary ?? [];
    const indexed: MilestoneBar[] = all.map((ms, i) => ({ ...ms, paletteIndex: i }));
    const newestFirst = (a: MilestoneBar, b: MilestoneBar) => b.id - a.id;
    const ordered = [
      ...indexed.filter((m) => m.pct < 100).sort(newestFirst),
      ...indexed.filter((m) => m.pct >= 100).sort(newestFirst),
    ];
    byProject.set(project.id, {
      bars: ordered.slice(0, MAX_MILESTONE_BARS),
      hidden: Math.max(0, ordered.length - MAX_MILESTONE_BARS),
    });
  }
  return byProject;
});

function overallPct(project: Project): { total: number; pct: number } {
  const counts = project.summary?.task_counts;
  if (!counts) return { total: 0, pct: 0 };
  const total = (counts.todo ?? 0) + (counts.in_progress ?? 0) + (counts.done ?? 0);
  const pct = total > 0 ? Math.round((counts.done ?? 0) / total * 100) : 0;
  return { total, pct };
}
</script>

<template>
  <main class="page-container">
    <div class="page-header">
      <h1>Projects</h1>
      <button class="btn-primary" @click="openNewProjectModal">+ New Project</button>
    </div>

    <!-- Filter tabs -->
    <div class="filter-tabs">
      <button
        v-for="tab in ['all', 'active', 'paused', 'completed', 'archived'] as const"
        :key="tab"
        :class="['tab-btn', { active: activeTab === tab }]"
        @click="activeTab = tab"
      >
        {{ tab.charAt(0).toUpperCase() + tab.slice(1) }}
      </button>
    </div>

    <div v-if="loading" class="skeleton-grid">
      <div class="skeleton-card" v-for="i in 4" :key="i"></div>
    </div>
    <p v-else-if="error" class="error-msg">{{ error }}</p>

    <div v-else-if="filteredProjects.length === 0" class="empty-state-rich">
      <div class="empty-icon">◈</div>
      <p class="empty-title">No projects yet</p>
      <p class="empty-sub">Organise your notes and tasks into a project</p>
      <button class="empty-action" @click="openNewProjectModal">New project →</button>
    </div>

    <div v-else class="projects-grid">
      <div
        v-for="project in filteredProjects"
        :key="project.id"
        class="project-card"
        @click="router.push(`/projects/${project.id}`)"
      >
        <div class="card-header">
          <span class="project-title">{{ project.title }}</span>
          <span
            :class="['status-badge', `status-${project.status}`]"
          >{{ statusLabel(project.status) }}</span>
        </div>
        <p v-if="project.goal" class="project-goal">
          <span class="field-label">Goal:</span> {{ truncate(project.goal) }}
        </p>
        <p v-if="project.description" class="project-desc">{{ truncate(project.description) }}</p>

        <!-- Overall completion bar -->
        <div
          v-if="overallPct(project).total > 0"
          class="overall-bar-row"
          :title="`${project.summary?.task_counts.done ?? 0} of ${overallPct(project).total} tasks complete`"
        >
          <div class="overall-bar-track">
            <div class="overall-bar-fill" :style="{ width: overallPct(project).pct + '%' }"></div>
          </div>
          <span class="overall-bar-pct">{{ overallPct(project).pct }}%</span>
        </div>

        <!-- Milestone progress bars -->
        <div
          v-if="milestoneBars.get(project.id)?.bars.length"
          class="milestone-bars"
        >
          <div
            v-for="ms in milestoneBars.get(project.id)!.bars"
            :key="ms.id"
            class="milestone-bar-row"
            :title="`${ms.title} — ${ms.pct}% (${ms.completed}/${ms.total} tasks)`"
          >
            <span class="milestone-bar-label">{{ ms.title }}</span>
            <div class="milestone-bar-track">
              <div
                class="milestone-bar-fill"
                :style="{ width: ms.pct + '%', background: milestoneColor(ms.paletteIndex) }"
              ></div>
            </div>
            <span class="milestone-bar-pct">{{ ms.pct }}%</span>
          </div>
          <!-- Say what is withheld. A list that simply stops reads as a
               rendering bug; a count reads as a summary. Plain text, not a
               link: the whole card already navigates to this project, and a
               link nested inside a clickable region is a trap for keyboard
               and screen-reader users. -->
          <span
            v-if="milestoneBars.get(project.id)!.hidden"
            class="milestone-more"
          >
            +{{ milestoneBars.get(project.id)!.hidden }}
            {{ milestoneBars.get(project.id)!.hidden === 1 ? 'more milestone' : 'more milestones' }}
          </span>
        </div>

        <div class="card-footer">
          <span class="meta-date">Updated {{ new Date(project.updated_at).toLocaleDateString() }}</span>
        </div>
      </div>
    </div>

    <!-- New Project Modal -->
    <teleport to="body">
      <div v-if="showNewProjectModal" class="modal-overlay" @click.self="closeModal">
        <div class="modal-card">
          <h3 class="modal-title">{{ modalStep === 1 ? "New Project" : "New Project — what it inherits" }}</h3>
          <InceptionCard v-if="modalStep === 2" mode="create" v-model:choices="newInception" />
          <div v-if="modalStep === 1" class="modal-field">
            <label>Title <span class="required">*</span></label>
            <input
              v-model="newTitle"
              type="text"
              class="modal-input"
              placeholder="Project title"
              autofocus
              @keydown.enter="modalStep = 2"
              @keydown.escape="closeModal"
            />
          </div>
          <div v-if="modalStep === 1" class="modal-field">
            <label>Goal</label>
            <input
              v-model="newGoal"
              type="text"
              class="modal-input"
              placeholder="What are you trying to achieve?"
              @keydown.escape="closeModal"
            />
          </div>
          <div v-if="modalStep === 1" class="modal-field">
            <label>Description</label>
            <textarea
              v-model="newDescription"
              class="modal-textarea"
              placeholder="Optional description..."
              rows="3"
              @keydown.escape="closeModal"
            ></textarea>
          </div>
          <div class="modal-actions">
            <button class="modal-btn" @click="closeModal">Cancel</button>
            <button v-if="modalStep === 2" class="modal-btn" @click="modalStep = 1">Back</button>
            <button
              v-if="modalStep === 1"
              class="modal-btn modal-btn-primary"
              @click="modalStep = 2"
              :disabled="!newTitle.trim()"
            >
              Next
            </button>
            <button
              v-else
              class="modal-btn modal-btn-primary"
              @click="createProject"
              :disabled="!newTitle.trim() || creating"
            >
              {{ creating ? "Creating..." : "Create" }}
            </button>
          </div>
        </div>
      </div>
    </teleport>
  </main>
</template>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}
.page-header h1 {
  margin: 0;
}

/* Moss action-primary per Hybrid — list-view utility action,
   not a brand moment. Empty-state .empty-action below keeps accent. */

.filter-tabs {
  display: flex;
  gap: 0.25rem;
  margin-bottom: 1.25rem;
  border-bottom: 1px solid var(--fs-border-color);
  padding-bottom: 0;
}
.tab-btn {
  padding: 0.4rem 0.85rem;
  background: none;
  border: none;
  border-bottom: 2px solid transparent;
  cursor: pointer;
  font-size: 0.875rem;
  color: var(--fs-text-secondary);
  font-family: inherit;
  margin-bottom: -1px;
}
.tab-btn:hover {
  color: var(--fs-accent);
}
.tab-btn.active {
  color: var(--fs-accent);
  border-bottom-color: var(--fs-accent);
  font-weight: 500;
}

.loading-msg,
.error-msg {
  color: var(--fs-text-tertiary);
  font-size: 0.9rem;
  margin-top: 1rem;
}
.error-msg {
  color: var(--fs-error);
}

.empty-state-rich { text-align: center; padding: 3rem 1rem; color: var(--fs-text-tertiary); }
.empty-icon { font-size: 2.5rem; margin-bottom: 0.75rem; opacity: 0.3; }
.empty-title { font-size: 1rem; font-weight: 500; color: var(--fs-text-secondary); margin: 0 0 0.35rem; }
.empty-sub { font-size: 0.85rem; margin: 0 0 1rem; }
.empty-action { display: inline-block; padding: 0.4rem 1rem; border: 1px solid var(--fs-action-primary); border-radius: var(--fs-radius-sm); color: var(--fs-action-primary); background: none; cursor: pointer; font-size: 0.85rem; transition: background 0.15s, color 0.15s; }
.empty-action:hover { background: var(--fs-action-primary); color: var(--fs-text-on-action); }

.skeleton-card {
  height: 140px;
  border-radius: var(--fs-radius-lg);
  background: linear-gradient(90deg, var(--fs-surface-raised) 25%, var(--fs-border-color) 50%, var(--fs-surface-raised) 75%);
  background-size: 200% 100%;
  animation: skeleton-shimmer 1.4s ease infinite;
}
@keyframes skeleton-shimmer {
  0% { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}
.skeleton-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1rem;
}

.projects-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1rem;
}

.project-card {
  background: var(--fs-surface-raised);
  border: 1px solid var(--fs-border-color);
  border-radius: var(--fs-radius-lg);
  padding: 1rem 1.1rem;
  cursor: pointer;
  transition: border-color 0.15s, box-shadow 0.15s, transform 0.18s ease;
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}
.project-card:hover {
  border-color: var(--fs-accent);
  box-shadow: 0 2px 8px var(--color-shadow);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 0.5rem;
}
.project-title {
  font-size: 1rem;
  font-weight: 500;
  color: var(--fs-text-primary);
  min-width: 0;
  flex: 1;
  word-break: break-word;
}

.status-badge {
  font-size: 0.7rem;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  padding: 0.15rem 0.45rem;
  border-radius: 999px;
  flex-shrink: 0;
  white-space: nowrap;
}
.status-active {
  background: color-mix(in srgb, var(--fs-success) 15%, transparent);
  color: var(--fs-success);
}
.status-completed {
  background: color-mix(in srgb, var(--fs-accent) 15%, transparent);
  color: var(--fs-accent);
}
.status-archived {
  background: color-mix(in srgb, var(--fs-text-tertiary) 15%, transparent);
  color: var(--fs-text-tertiary);
}

.project-goal {
  font-size: 0.875rem;
  color: var(--fs-text-primary);
  margin: 0;
  line-height: 1.4;
}
.field-label {
  font-weight: 500;
  color: var(--fs-text-secondary);
}

.project-desc {
  font-size: 0.82rem;
  color: var(--fs-text-secondary);
  margin: 0;
  line-height: 1.45;
}

.overall-bar-row {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  font-size: 0.72rem;
  margin-top: 0.1rem;
}
.overall-bar-track {
  flex: 1;
  height: 6px;
  background: var(--fs-border-color);
  border-radius: 999px;
  overflow: hidden;
}
.overall-bar-fill {
  height: 100%;
  border-radius: 999px;
  background: var(--fs-accent);
  transition: width 0.3s ease;
}
.overall-bar-pct {
  color: var(--fs-text-secondary);
  flex-shrink: 0;
  min-width: 2.5rem;
  text-align: right;
  font-weight: 500;
}

.milestone-bars {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  margin-top: 0.1rem;
}
.milestone-bar-row {
  display: flex;
  align-items: center;
  gap: 0.4rem;
  font-size: 0.72rem;
}
.milestone-bar-label {
  color: var(--fs-text-secondary);
  min-width: 0;
  flex: 0 0 30%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.milestone-bar-track {
  flex: 1;
  height: 5px;
  background: var(--fs-border-color);
  border-radius: 999px;
  overflow: hidden;
}
.milestone-bar-fill {
  height: 100%;
  border-radius: 999px;
  transition: width 0.3s ease;
}
.milestone-bar-pct {
  color: var(--fs-text-tertiary);
  flex-shrink: 0;
  min-width: 2.5rem;
  text-align: right;
}

/* Deliberately quiet — it is a footnote about what is not shown, not another
   row competing with the bars above it. */
.milestone-more {
  color: var(--fs-text-tertiary);
  font-size: var(--fs-size-tiny);
  padding-top: 0.15rem;
}

.card-footer {
  margin-top: auto;
}
.meta-date {
  font-size: 0.75rem;
  color: var(--fs-text-tertiary);
}

.modal-card {
  max-width: 480px;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}
.modal-title {
  margin: 0;
  font-size: 1.1rem;
}
.modal-field {
  display: flex;
  flex-direction: column;
  gap: 0.3rem;
}
.modal-field label {
  font-size: 0.875rem;
  font-weight: 500;
  color: var(--fs-text-primary);
}
.required {
  color: var(--fs-error);
}
.modal-input,
.modal-textarea {
  padding: 0.45rem 0.7rem;
  border: 1px solid var(--fs-border-color);
  border-radius: var(--fs-radius-sm);
  background: var(--fs-surface-page);
  color: var(--fs-text-primary);
  font-size: 0.9rem;
  font-family: inherit;
  box-sizing: border-box;
  width: 100%;
}
.modal-input:focus,
.modal-textarea:focus {
  outline: none;
  border-color: var(--fs-accent);
}
.modal-textarea {
  resize: vertical;
}

@media (max-width: 600px) {
  .projects-grid {
    grid-template-columns: 1fr;
  }
  .modal-card {
    margin: 1rem;
    max-width: calc(100vw - 2rem);
  }
}
</style>
