import { redirect } from "next/navigation";
import Image from "next/image";
import { getCurrentUser } from "@/lib/auth";
import { db, hasLiveAgent } from "@/lib/db";
import { courses, courseProgressPercent } from "@/lib/courses";
import { hasCourseAccess, hasPaidRegistration, isOnTrial, ownsCourse, trialEnd } from "@/lib/access";
import { COURSE_PRICE_GHS } from "@/lib/pricing";

export const metadata = { title: "Classroom" };

export default async function DashboardPage() {
  const user = await getCurrentUser();
  if (!user) redirect("/login?next=/dashboard");
  if (!hasPaidRegistration(user)) redirect("/pay");

  const rows = db
    .prepare("SELECT course_slug, level_id, step_id FROM progress WHERE user_id = ?")
    .all(user.id) as { course_slug: string; level_id: string; step_id: string }[];

  const byCourse = new Map<string, Set<string>>();
  for (const r of rows) {
    const set = byCourse.get(r.course_slug) ?? new Set<string>();
    set.add(`${r.level_id}:${r.step_id}`);
    byCourse.set(r.course_slug, set);
  }

  const trial = isOnTrial(user);
  const ends = trialEnd(user);

  return (
    <div className="mx-auto max-w-6xl px-4 py-12">
      <p className="text-xs uppercase tracking-[0.28em] text-terra">Classroom</p>
      <h1 className="font-display mt-2 text-4xl text-forest">Welcome back, {user.name.split(" ")[0]}.</h1>
      {trial ? (
        <p className="mt-3 max-w-xl rounded-2xl bg-gold/30 px-4 py-3 text-sm text-forest">
          All courses are open until <strong>{ends.toLocaleString()}</strong>. After 72 hours they lock
          unless you pay ₵{COURSE_PRICE_GHS} each.
        </p>
      ) : (
        <p className="mt-3 max-w-xl text-forest/75">
          Your 3-day window has ended. Unlock any blueprint for ₵{COURSE_PRICE_GHS} to keep learning.
        </p>
      )}
      {!hasLiveAgent(user) ? (
        <a href="/pay" className="mt-4 inline-block text-sm font-medium text-terra">
          Add live coach · ₵80 →
        </a>
      ) : (
        <a href="/agent" className="mt-4 inline-block text-sm font-medium text-terra">
          Open live coach thread →
        </a>
      )}

      <div className="mt-10 grid gap-5 md:grid-cols-2 lg:grid-cols-3">
        {courses.map((c) => {
          const pct = courseProgressPercent(c, byCourse.get(c.slug) ?? new Set());
          const open = await hasCourseAccess(user, c.slug);
          const owned = await ownsCourse(user, c.slug);
          return (
            <a
              key={c.slug}
              href={open ? `/courses/${c.slug}` : `/pay?course=${c.slug}`}
              className="card-lift overflow-hidden rounded-3xl border border-forest/10 bg-cream"
            >
              <div className="relative h-36">
                <Image src={c.image} alt="" fill className="object-cover" />
                {!open ? (
                  <div className="absolute inset-0 grid place-items-center bg-forest/70">
                    <span className="rounded-full bg-gold px-3 py-1 text-xs font-bold text-forest">
                      Unlock ₵{COURSE_PRICE_GHS}
                    </span>
                  </div>
                ) : null}
              </div>
              <div className="p-5">
                <h2 className="font-display text-xl text-forest">{c.title}</h2>
                <div className="mt-3 h-1.5 overflow-hidden rounded-full bg-paper-2">
                  <div className="h-full bg-gold" style={{ width: `${pct}%` }} />
                </div>
                <p className="mt-2 text-xs text-forest/60">
                  {owned ? "Purchased" : trial ? "Open for 3 days" : "Locked"} · {pct}% of steps marked
                </p>
              </div>
            </a>
          );
        })}
      </div>
    </div>
  );
}
