<script setup lang="ts">
type CourseStatus = "processing" | "ready" | "error";

interface CourseSummary {
  id: string
  title: string
  subject: string
  status: CourseStatus
  stage: string | null
  createdAt: string
  topicCount: number
  completedCount: number
  costAI: number | null
  costAudio: number | null
  organisation: string | null
}

const { data: courses, refresh } = await useAsyncData(
  "courses-list",
  () => $fetch<CourseSummary[]>("/api/courses")
);

let pollTimer: ReturnType<typeof setInterval> | null = null;

function maybeStartPolling() {
  const hasProcessing = courses.value?.some((c) => c.status === "processing");
  if (hasProcessing && !pollTimer) {
    pollTimer = setInterval(async () => {
      await refresh();
      if (!courses.value?.some((c) => c.status === "processing")) {
        clearInterval(pollTimer!);
        pollTimer = null;
      }
    }, 4000);
  }
}

onMounted(maybeStartPolling);
watch(courses, maybeStartPolling);
onUnmounted(() => { if (pollTimer) clearInterval(pollTimer); });

function relativeTime(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime();
  const mins  = Math.floor(diff / 60000);
  const hours = Math.floor(diff / 3600000);
  const days  = Math.floor(diff / 86400000);
  if (mins < 2)   return "just now";
  if (mins < 60)  return `${mins}m ago`;
  if (hours < 24) return `${hours}h ago`;
  if (days < 30)  return `${days}d ago`;
  return new Date(dateStr).toLocaleDateString("en-GB", { day: "numeric", month: "short" });
}

const STAGE_LABELS: Record<string, string> = {
  parsing_pdfs:        "Reading your documents…",
  analysing_sources:   "Identifying key topics…",
  building_curriculum: "Building your curriculum…",
  finalising:          "Generating lessons & quizzes…",
};

function stageLabel(stage: string | null): string {
  return (stage && STAGE_LABELS[stage]) ?? "Processing…";
}

const retrying = ref<Record<string, boolean>>({});

async function retry(courseId: string) {
  retrying.value[courseId] = true;
  try {
    await $fetch(`/api/courses/${courseId}/generate`, { method: "POST" });
    await refresh();
    maybeStartPolling();
  } catch {
    // leave error state
  } finally {
    retrying.value[courseId] = false;
  }
}

function progressPct(course: CourseSummary): number {
  if (!course.topicCount) return 0;
  return Math.round((course.completedCount / course.topicCount) * 100);
}

// deterministic warm color from subject string
function subjectColor(subject: string): string {
  const palette = [
    "#c9a87c", "#7a9e8e", "#8b7faa", "#b07c7c",
    "#7c9db0", "#a89e7c", "#8aaa7c", "#aa7c9e",
  ];
  let hash = 0;
  for (let i = 0; i < subject.length; i++) {
    hash = (hash * 31 + subject.charCodeAt(i)) & 0xffff;
  }
  return palette[hash % palette.length] ?? palette[0]!;
}
</script>

<template>
  <div class="dashboard">

    <!-- header -->
    <div class="dash-head">
      <div class="dash-head-date">{{ new Date().toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long", year: "numeric" }) }}</div>
      <h1 class="dash-head-title">Your courses</h1>
    </div>

    <!-- empty state -->
    <div v-if="!courses?.length" class="empty-state">
      <div class="empty-icon">
        <svg width="32" height="32" viewBox="0 0 20 20" fill="none" stroke="var(--accent)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
          <path d="M4 3h10a1 1 0 011 1v12a1 1 0 01-1 1H4a1 1 0 01-1-1V4a1 1 0 011-1z"/>
          <path d="M7 7h6M7 10h6M7 13h4"/>
        </svg>
      </div>
      <h2 class="empty-heading">No courses yet</h2>
      <p class="empty-sub">Upload your lecture slides and past papers to generate a personalised learning path.</p>
      <NuxtLink to="/new" class="empty-cta">Create your first course →</NuxtLink>
    </div>

    <!-- grid -->
    <div v-else class="course-grid">

      <a
        v-for="course in courses"
        :key="course.id"
        :href="course.status !== 'error' ? `/course/${course.id}` : undefined"
        class="course-card"
        :class="{
          'course-card--ready':      course.status === 'ready',
          'course-card--processing': course.status === 'processing',
          'course-card--error':      course.status === 'error',
        }"
        :style="course.status === 'error' ? 'cursor: default;' : ''"
        @click.prevent="course.status !== 'error' && $router.push(`/course/${course.id}`)"
      >
        <!-- color strip — derived from subject initials hash for consistency -->
        <div class="card-strip" :style="{ background: subjectColor(course.subject) }" />

        <div class="card-body">
          <!-- top row -->
          <div class="card-top">
            <div>
              <div class="card-subject">{{ course.subject }}</div>
              <h3 class="card-title">{{ course.title }}</h3>

              <!-- org chip -->
              <div v-if="course.organisation" class="card-org-chips">
                <span class="org-chip">{{ course.organisation }}</span>
              </div>
            </div>

            <span class="status-badge" :class="`status-badge--${course.status}`">
              <span v-if="course.status === 'processing'" class="badge-pulse" />
              {{ course.status === 'ready' ? 'Ready' : course.status === 'error' ? 'Error' : 'Processing' }}
            </span>
          </div>

          <!-- bottom -->
          <div class="card-bottom">
            <template v-if="course.status === 'ready'">
              <!-- progress bar -->
              <div class="progress-row">
                <div class="progress-track">
                  <div class="progress-fill" :style="{ width: `${progressPct(course)}%`, background: subjectColor(course.subject) }" />
                </div>
                <span class="progress-label">{{ course.completedCount }}&thinsp;/&thinsp;{{ course.topicCount }}</span>
              </div>

              <div class="card-footer">
                <span class="card-date">Last opened {{ relativeTime(course.createdAt) }}</span>

                <div v-if="(course.costAI ?? 0) + (course.costAudio ?? 0) > 0" class="cost-row">
                  <span>${{ ((course.costAI ?? 0) + (course.costAudio ?? 0)).toFixed(2) }}</span>
                </div>
              </div>
            </template>

            <template v-else-if="course.status === 'processing'">
              <p class="stage-label">
                <span class="stage-dot" />
                Generating lessons...
              </p>
              <span class="card-date">{{ relativeTime(course.createdAt) }}</span>
            </template>

            <template v-else-if="course.status === 'error'">
              <div class="error-row">
                <span class="error-msg">Generation failed</span>
                <button
                  class="retry-btn"
                  :disabled="retrying[course.id]"
                  @click.prevent="retry(course.id)"
                >{{ retrying[course.id] ? 'Retrying…' : 'Retry' }}</button>
              </div>
              <span class="card-date">{{ relativeTime(course.createdAt) }}</span>
            </template>
          </div>
        </div>
      </a>

      <!-- add new card -->
      <NuxtLink to="/new" class="add-card">
        <div class="add-card-circle">
          <svg width="18" height="18" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round">
            <path d="M10 4v12M4 10h12"/>
          </svg>
        </div>
        <span class="add-card-label">Upload new course materials</span>
      </NuxtLink>

    </div>

  </div>
</template>

<style scoped>
.dashboard {
  padding: 40px 48px;
  max-width: 960px;
}

.dash-head {
  margin-bottom: 36px;
}

.dash-head-date {
  font-size: 12px;
  font-weight: 500;
  color: var(--text-3);
  letter-spacing: 0.08em;
  text-transform: uppercase;
  margin-bottom: 6px;
}

.dash-head-title {
  font-family: "Lora", serif;
  font-size: 28px;
  font-weight: 600;
  color: var(--text);
  letter-spacing: -0.4px;
}

/* empty state */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  padding: 6rem 0;
  gap: 1rem;
}

.empty-icon {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: var(--accent-light);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 0.5rem;
}

.empty-heading {
  font-family: "Lora", serif;
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--text);
}

.empty-sub {
  font-size: 0.9rem;
  line-height: 1.7;
  color: var(--text-2);
  max-width: 380px;
}

.empty-cta {
  margin-top: 0.5rem;
  display: inline-block;
  background: var(--accent);
  color: white;
  font-size: 0.875rem;
  font-weight: 500;
  padding: 0.75rem 1.75rem;
  border-radius: var(--r-btn);
  text-decoration: none;
  transition: opacity 0.15s;
}
.empty-cta:hover { opacity: 0.88; }

/* grid */
.course-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

@media (max-width: 700px) {
  .dashboard { padding: 24px 20px; }
  .course-grid { grid-template-columns: 1fr; }
}

/* card */
.course-card {
  display: flex;
  flex-direction: column;
  background: var(--surface);
  border: 1px solid var(--border);
  border-radius: var(--r-card);
  overflow: hidden;
  text-decoration: none;
  cursor: default;
  transition: border-color 0.18s, transform 0.18s, box-shadow 0.18s;
}

.course-card--ready {
  cursor: pointer;
}

.course-card--ready:hover {
  border-color: var(--border-2);
  transform: translateY(-2px);
  box-shadow: 0 8px 28px oklch(0% 0 0 / 0.06);
}

.course-card--error {
  border-color: oklch(80% 0.06 15);
}

.card-strip {
  height: 6px;
  opacity: 0.85;
}

.card-body {
  padding: 20px 22px;
  display: flex;
  flex-direction: column;
  gap: 0;
  flex: 1;
}

.card-top {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
}

.card-subject {
  font-size: 11px;
  font-weight: 600;
  letter-spacing: 0.07em;
  color: var(--text-3);
  text-transform: uppercase;
  margin-bottom: 4px;
}

.card-title {
  font-family: "Lora", serif;
  font-weight: 600;
  font-size: 16px;
  color: var(--text);
  line-height: 1.3;
  margin-bottom: 8px;
}

.card-org-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.org-chip {
  font-size: 11px;
  font-weight: 500;
  color: var(--text-2);
  border: 1px solid var(--border-2);
  border-radius: 20px;
  padding: 2px 9px;
  background: var(--surface-2);
  white-space: nowrap;
  letter-spacing: 0.01em;
}

.status-badge {
  font-size: 10px;
  letter-spacing: 0.08em;
  text-transform: uppercase;
  padding: 3px 8px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  gap: 5px;
  flex-shrink: 0;
  font-weight: 500;
}

.status-badge--ready {
  background: var(--green-light);
  color: var(--green);
}

.status-badge--processing {
  background: var(--accent-light);
  color: var(--accent);
}

.status-badge--error {
  background: oklch(93% 0.04 15);
  color: oklch(42% 0.12 15);
}

.badge-pulse {
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: currentColor;
  animation: badge-blink 1.4s ease-in-out infinite;
}

@keyframes badge-blink {
  0%, 100% { opacity: 0.35; }
  50%       { opacity: 1; }
}

.card-bottom {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: auto;
}

.progress-row {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-track {
  flex: 1;
  height: 6px;
  background: var(--border);
  border-radius: 99px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 99px;
  transition: width 0.5s ease;
}

.progress-label {
  font-size: 12px;
  color: var(--text-3);
  flex-shrink: 0;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-date {
  font-size: 12px;
  color: var(--text-3);
}

.cost-row {
  font-size: 11px;
  color: var(--text-3);
}

.stage-label {
  font-size: 13px;
  color: var(--accent);
  display: flex;
  align-items: center;
  gap: 6px;
}

.stage-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--accent);
  flex-shrink: 0;
  animation: badge-blink 1.4s ease-in-out infinite;
}

.course-card--processing {
  cursor: pointer;
}

.course-card--processing:hover {
  border-color: var(--border-2);
  transform: translateY(-2px);
  box-shadow: 0 8px 28px oklch(0% 0 0 / 0.06);
}

.error-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}

.error-msg {
  font-size: 13px;
  color: oklch(42% 0.12 15);
}

.retry-btn {
  font-size: 11px;
  letter-spacing: 0.06em;
  text-transform: uppercase;
  background: none;
  border: 1px solid oklch(78% 0.06 15);
  color: oklch(42% 0.12 15);
  padding: 3px 10px;
  border-radius: 20px;
  cursor: pointer;
  transition: background 0.15s;
  flex-shrink: 0;
}
.retry-btn:hover:not(:disabled) { background: oklch(93% 0.04 15); }
.retry-btn:disabled { opacity: 0.4; cursor: not-allowed; }

/* add card */
.add-card {
  background: transparent;
  border: 1.5px dashed var(--border-2);
  border-radius: var(--r-card);
  padding: 40px 22px;
  text-align: center;
  cursor: pointer;
  color: var(--text-3);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10px;
  text-decoration: none;
  transition: all 0.18s;
  min-height: 160px;
}

.add-card:hover {
  border-color: var(--accent);
  color: var(--accent);
  background: var(--accent-light);
}

.add-card-circle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 1.5px dashed currentColor;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-card-label {
  font-size: 14px;
  font-weight: 500;
}
</style>
