import { Link, router } from "@inertiajs/react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@/hooks/useAuth";
import { useRolePreview } from "@/contexts/RolePreviewContext";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Progress } from "@/components/ui/progress";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import {
  BookOpen, Calendar, MapPin, Clock, AlertCircle,
  CheckCircle2, ClipboardList, User, ArrowRight, LogOut, Award,
  GraduationCap, Monitor, Search, ChevronRight, Bell, BellDot,
  Target, ShieldCheck, RefreshCw, History, SendHorizonal, Gift,
  TrendingUp, Zap, ExternalLink, Home, Compass,
} from "lucide-react";
import CertificateWallet from "@/components/delegate/CertificateWallet";
import ReferralModule from "@/components/delegate/ReferralModule";
import CourseLookup from "@/components/delegate/CourseLookup";
import SopManual from "@/components/SopManual";
import { BookingActions } from "@/components/BookingActions";
import { SHOW_COMPLIANCE } from "@/lib/feature-flags";
import { format, differenceInDays } from "date-fns";
import { toast } from "sonner";
import { useState } from "react";

const csrfToken = () =>
  (document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';

const DelegateDashboard = () => {
  const { user, signOut } = useAuth();
  const { preview } = useRolePreview();
  const searchParams = new URLSearchParams(window.location.search);
  const queryClient = useQueryClient();
  const orderId = searchParams.get("order_id");
  const [mainTab, setMainTab] = useState("overview");

  // Use preview email when in delegate preview mode, otherwise real user email
  const effectiveEmail = (preview.active && preview.role === "delegate" && preview.previewEmail)
    ? preview.previewEmail
    : user?.email;

  const { data: orders, isLoading: ordersLoading } = useQuery({
    queryKey: ["delegate-orders", effectiveEmail],
    enabled: !!effectiveEmail,
    queryFn: async () => {
      const res = await fetch(`/api/delegate/orders?email=${encodeURIComponent(effectiveEmail!)}`);
      if (!res.ok) throw new Error("Failed to load orders");
      const data = await res.json();
      return data || [];
    },
  });

  const { data: enrolments } = useQuery({
    queryKey: ["delegate-enrolments", user?.id],
    enabled: !!user?.id,
    queryFn: async () => {
      const res = await fetch(`/api/delegate/enrolments`);
      if (!res.ok) return [];
      const data = await res.json();
      return data || [];
    },
  });

  const { data: certificates } = useQuery({
    queryKey: ["delegate-certs-count", effectiveEmail],
    enabled: !!effectiveEmail,
    queryFn: async () => {
      const res = await fetch(`/api/delegate/certificates?email=${encodeURIComponent(effectiveEmail!)}`);
      if (!res.ok) return [];
      const data = await res.json();
      return data || [];
    },
  });

  const { data: notifications } = useQuery({
    queryKey: ["delegate-notifications", user?.id],
    enabled: !!user?.id,
    queryFn: async () => {
      const res = await fetch(`/api/delegate/notifications?limit=10`);
      if (!res.ok) return [];
      const data = await res.json();
      return data || [];
    },
  });

  const markReadMutation = useMutation({
    mutationFn: async (notifId: string) => {
      await fetch(`/api/delegate/notifications/${notifId}/read`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': csrfToken() },
        body: JSON.stringify({ is_read: true }),
      });
    },
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ["delegate-notifications"] }),
  });

  const { data: bookingRequests } = useQuery({
    queryKey: ["delegate-booking-requests", user?.id],
    enabled: !!user?.id,
    queryFn: async () => {
      const res = await fetch(`/api/delegate/booking-requests`);
      if (!res.ok) return [];
      const data = await res.json();
      return data || [];
    },
  });

  const { data: requirements } = useQuery({
    queryKey: ["delegate-requirements", effectiveEmail],
    enabled: !!effectiveEmail,
    queryFn: async () => {
      const res = await fetch(`/api/delegate/requirements?email=${encodeURIComponent(effectiveEmail!)}`);
      if (!res.ok) return null;
      return await res.json();
    },
  });

  const { data: formSubmissions } = useQuery({
    queryKey: ["delegate-form-submissions", orderId, effectiveEmail],
    enabled: !!orderId && !!effectiveEmail,
    queryFn: async () => {
      const res = await fetch(`/api/delegate/form-submissions?order_id=${orderId}&email=${encodeURIComponent(effectiveEmail!)}`);
      if (!res.ok) throw new Error("Failed to load form submissions");
      const data = await res.json();
      return data || [];
    },
  });

  // E-learning bookings (no scheduled date) have no pre-course / onboarding
  // questionnaire, so the delegate is never prompted to complete one.
  const currentOrder = orders?.find((o: any) => o.id === orderId);
  const currentOrderIsElearning = !!currentOrder && !currentOrder.start_date;
  const submittedForms = formSubmissions?.map((s: any) => s.form_type) || [];
  const td02Complete = submittedForms.includes("TD-02");
  const onDayFormsComplete = ["TD-07", "TD-29"].every(f => submittedForms.includes(f));
  const allFormsComplete = td02Complete && onDayFormsComplete;
  const hasOnDayTodo = !!orderId && !onDayFormsComplete && !currentOrderIsElearning;

  const handleSignOut = () => {
    signOut();
    toast.success("Signed out successfully");
  };

  const firstName = user?.full_name?.split(" ")[0] || effectiveEmail?.split("@")[0] || "Delegate";

  const activeCerts = certificates?.filter((c: any) => c.status === "active").length || 0;
  const today = new Date();
  // Orders with no start_date are VT e-learning purchases — they're
  // always "upcoming" until completed, and never auto-move to history.
  const upcomingOrders = orders?.filter((o: any) => {
    if (!o.start_date) return o.status === "confirmed" || o.status === "paid";
    const d = differenceInDays(new Date(o.start_date + "T00:00:00"), today);
    return d >= 0 && (o.status === "confirmed" || o.status === "paid");
  }) || [];
  const completedOrders = orders?.filter((o: any) => {
    if (!o.start_date) return o.status === "completed" || o.status === "cancelled";
    const d = differenceInDays(new Date(o.start_date + "T00:00:00"), today);
    return d < 0 || o.status === "completed" || o.status === "cancelled";
  }) || [];
  const elearningInProgress = enrolments?.filter((e: any) => e.status === "in_progress").length || 0;
  const unreadNotifs = notifications?.filter((n: any) => !n.is_read).length || 0;

  const getRequirementStatus = (courseId: string) => {
    const cert = certificates?.find((c: any) => c.course_id === courseId && c.status === "active");
    if (!cert) return "missing";
    if (cert.expires_at) {
      const days = differenceInDays(new Date(cert.expires_at), new Date());
      if (days < 0) return "expired";
      if (days <= 60) return "expiring";
    }
    return "valid";
  };

  const totalReqs = requirements?.requirements?.length || 0;
  const validReqs = requirements?.requirements?.filter((r: any) => getRequirementStatus(r.course_id) === "valid").length || 0;
  const compliancePercent = totalReqs > 0 ? Math.round((validReqs / totalReqs) * 100) : 100;

  const nextCourse = upcomingOrders[0];
  const nextCourseDays = nextCourse && nextCourse.start_date
    ? differenceInDays(new Date(nextCourse.start_date + "T00:00:00"), today)
    : null;

  return (
    <div className="min-h-screen bg-background">
      <header className="sticky top-0 z-40 bg-card/80 backdrop-blur-xl border-b border-border">
        <div className="max-w-5xl mx-auto px-4 h-14 flex items-center justify-between">
          <Link href="/" className="flex items-center gap-2.5 hover:opacity-80 transition-opacity">
            <div className="w-8 h-8 rounded-lg bg-primary flex items-center justify-center">
              <BookOpen className="w-4 h-4 text-primary-foreground" />
            </div>
            <span className="text-sm font-semibold text-foreground hidden sm:block">Locktel Academy</span>
          </Link>
          <div className="flex items-center gap-1">
            {unreadNotifs > 0 && (
              <Button variant="ghost" size="icon" className="relative" onClick={() => setMainTab("notifications")}>
                <BellDot className="w-4 h-4" />
                <span className="absolute -top-0.5 -right-0.5 w-4 h-4 rounded-full bg-destructive text-[9px] text-destructive-foreground flex items-center justify-center font-bold">
                  {unreadNotifs}
                </span>
              </Button>
            )}
            <Button variant="ghost" size="sm" onClick={() => router.visit("/")} className="text-muted-foreground text-xs">
              <Home className="w-3.5 h-3.5 mr-1" /> Main Site
            </Button>
            <Button variant="ghost" size="sm" onClick={handleSignOut} className="text-muted-foreground text-xs">
              <LogOut className="w-3.5 h-3.5 mr-1" /> Sign out
            </Button>
          </div>
        </div>
      </header>

      <div className="relative overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-br from-primary/20 via-transparent to-accent/10" />
        <div className="relative max-w-5xl mx-auto px-4 py-8 md:py-10">
          <div className="flex items-center gap-4 mb-6">
            <div className="w-14 h-14 rounded-2xl bg-gradient-to-br from-primary to-primary/70 flex items-center justify-center shadow-lg shadow-primary/20">
              <User className="w-7 h-7 text-primary-foreground" />
            </div>
            <div>
              <h1 className="text-2xl md:text-3xl font-bold text-foreground">
                Welcome back, {firstName}
              </h1>
              <p className="text-sm text-muted-foreground mt-0.5">{effectiveEmail}</p>
            </div>
          </div>

          <div className={`grid grid-cols-2 ${SHOW_COMPLIANCE ? "md:grid-cols-4" : "md:grid-cols-3"} gap-3`}>
            {[
              { icon: Calendar, label: "Upcoming", value: upcomingOrders.length, color: "text-primary" },
              { icon: Monitor, label: "E-Learning", value: elearningInProgress, color: "text-primary" },
              { icon: Award, label: "Certificates", value: activeCerts, color: "text-primary" },
              ...(SHOW_COMPLIANCE ? [{
                icon: ShieldCheck,
                label: "Compliant",
                value: `${compliancePercent}%`,
                color: compliancePercent === 100
                  ? "text-green-500"
                  : compliancePercent >= 75
                    ? "text-amber-500"
                    : "text-destructive",
              }] : []),
            ].map((stat) => (
              <Card key={stat.label} className="bg-card/50 border-border/50 hover:border-primary/30 transition-colors">
                <CardContent className="py-4 px-4 flex items-center gap-3">
                  <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center shrink-0">
                    <stat.icon className={`w-5 h-5 ${stat.color}`} />
                  </div>
                  <div>
                    <p className={`text-xl font-bold ${stat.color}`}>{stat.value}</p>
                    <p className="text-[11px] text-muted-foreground">{stat.label}</p>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      </div>

      <div className="max-w-5xl mx-auto px-4 pb-12">
        <div className="space-y-3 mb-6">
          {nextCourse && (
            <Card className="border-primary/30 bg-gradient-to-r from-primary/5 to-transparent">
              <CardContent className="py-4 flex items-center gap-4">
                <div className="w-12 h-12 rounded-xl bg-primary/15 flex items-center justify-center shrink-0">
                  <Zap className="w-6 h-6 text-primary" />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-xs font-medium text-primary uppercase tracking-wider">Next Course</p>
                  <p className="text-sm font-semibold text-foreground truncate mt-0.5">{nextCourse.courses?.title}</p>
                  <p className="text-xs text-muted-foreground mt-0.5">
                    {nextCourse.start_date
                      ? format(new Date(nextCourse.start_date + "T00:00:00"), "EEE d MMM yyyy")
                      : "Online — start anytime"}
                    {nextCourse.venues && ` · ${nextCourse.venues.name}`}
                  </p>
                </div>
                <Badge className="bg-primary/15 text-primary border-0 text-xs shrink-0">
                  {nextCourseDays === null
                    ? "Online"
                    : nextCourseDays === 0 ? "Today!" : `${nextCourseDays} day${nextCourseDays !== 1 ? "s" : ""}`}
                </Badge>
              </CardContent>
            </Card>
          )}

          {orderId && !td02Complete && !currentOrderIsElearning && (
            <Card className="border-blue-500/30 bg-blue-500/5">
              <CardContent className="py-3 flex items-center gap-3">
                <ClipboardList className="w-5 h-5 text-blue-400 shrink-0" />
                <div className="flex-1">
                  <p className="text-sm font-medium text-foreground">Pre-course form required</p>
                  <p className="text-xs text-muted-foreground">Check your inbox for TD-02.</p>
                </div>
              </CardContent>
            </Card>
          )}

          {hasOnDayTodo && (
            <Card className="border-amber-500/30 bg-amber-500/5">
              <CardContent className="py-3 flex items-center gap-3">
                <AlertCircle className="w-5 h-5 text-amber-400 shrink-0" />
                <div className="flex-1">
                  <p className="text-sm font-medium text-foreground">Induction forms needed</p>
                  <div className="flex gap-1.5 mt-1.5">
                    {["TD-07", "TD-29"].map(form => (
                      <Badge key={form} variant={submittedForms.includes(form) ? "default" : "outline"} className="text-[10px]">
                        {submittedForms.includes(form) && <CheckCircle2 className="w-3 h-3 mr-0.5" />}
                        {form}
                      </Badge>
                    ))}
                  </div>
                </div>
                <Button size="sm" className="shrink-0" onClick={() => router.visit(`/onboarding/forms?order_id=${orderId}`)}>
                  Complete <ArrowRight className="w-3 h-3 ml-1" />
                </Button>
              </CardContent>
            </Card>
          )}

          {orderId && allFormsComplete && (
            <Card className="border-green-500/30 bg-green-500/5">
              <CardContent className="py-3 flex items-center gap-3">
                <CheckCircle2 className="w-5 h-5 text-green-400 shrink-0" />
                <p className="text-sm font-medium text-foreground">All forms complete — you're ready for training ✓</p>
              </CardContent>
            </Card>
          )}
        </div>

        <Tabs value={mainTab} onValueChange={setMainTab} className="w-full">
          <TabsList className="w-full justify-start bg-card border border-border rounded-xl h-11 p-1 gap-0.5 mb-6 overflow-x-auto">
            <TabsTrigger value="overview" className="rounded-lg text-xs data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
              <TrendingUp className="w-3.5 h-3.5 mr-1.5" /> Overview
            </TabsTrigger>
            <TabsTrigger value="courses" className="rounded-lg text-xs data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
              <BookOpen className="w-3.5 h-3.5 mr-1.5" /> Courses
            </TabsTrigger>
            <TabsTrigger value="certificates" className="rounded-lg text-xs data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
              <Award className="w-3.5 h-3.5 mr-1.5" /> Certificates
            </TabsTrigger>
            <TabsTrigger value="notifications" className="rounded-lg text-xs data-[state=active]:bg-primary data-[state=active]:text-primary-foreground relative">
              <Bell className="w-3.5 h-3.5 mr-1.5" /> Alerts
              {unreadNotifs > 0 && (
                <span className="ml-1 w-4 h-4 rounded-full bg-destructive text-[9px] text-destructive-foreground flex items-center justify-center font-bold">
                  {unreadNotifs}
                </span>
              )}
            </TabsTrigger>
            <TabsTrigger value="referrals" className="rounded-lg text-xs data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
              <Gift className="w-3.5 h-3.5 mr-1.5" /> Refer
            </TabsTrigger>
            <TabsTrigger value="guide" className="rounded-lg text-xs data-[state=active]:bg-primary data-[state=active]:text-primary-foreground">
              <Compass className="w-3.5 h-3.5 mr-1.5" /> Guide
            </TabsTrigger>
            {/* Not a tab — navigates to the standalone profile page. */}
            <button
              type="button"
              onClick={() => router.visit("/delegate-profile")}
              className="inline-flex items-center justify-center whitespace-nowrap rounded-lg px-3 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors"
            >
              <User className="w-3.5 h-3.5 mr-1.5" /> Profile
            </button>
          </TabsList>

          <TabsContent value="overview" className="space-y-6 mt-0">
            <div className="grid grid-cols-2 gap-3">
              {[
                { icon: GraduationCap, label: "Skills Profile", sub: "Qualifications", to: "/delegate-profile", external: false },
                { icon: Monitor, label: "E-Learning", sub: "Continue", to: "/courses", external: true },
              ].map((a) => (
                <Card
                  key={a.label}
                  className="cursor-pointer hover:border-primary/40 transition-all group"
                  onClick={() => {
                    if (a.external && preview.active) {
                      window.open(a.to, "_blank");
                    } else {
                      router.visit(a.to);
                    }
                  }}
                >
                  <CardContent className="py-5 flex flex-col items-center text-center gap-2">
                    <div className="w-10 h-10 rounded-xl bg-primary/10 flex items-center justify-center group-hover:bg-primary/20 transition-colors">
                      <a.icon className="w-5 h-5 text-primary" />
                    </div>
                    <div>
                      <p className="text-xs font-semibold text-foreground">{a.label}</p>
                      <p className="text-[10px] text-muted-foreground">{a.sub}</p>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>

            <div>
              <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                <Search className="w-4 h-4 text-primary" /> Find a Course
              </h3>
              <CourseLookup />
            </div>

            {bookingRequests && bookingRequests.length > 0 && (
              <div>
                <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                  <SendHorizonal className="w-4 h-4 text-primary" /> Booking Requests
                </h3>
                <div className="space-y-2">
                  {bookingRequests.slice(0, 3).map((req: any) => {
                    const statusMap: Record<string, { label: string; cls: string }> = {
                      pending: { label: "Awaiting Approval", cls: "text-amber-400 border-amber-500/30 bg-amber-500/10" },
                      approved: { label: "Approved", cls: "text-green-400 border-green-500/30 bg-green-500/10" },
                      rejected: { label: "Declined", cls: "text-destructive border-destructive/30 bg-destructive/10" },
                    };
                    const s = statusMap[req.status] || { label: req.status, cls: "" };
                    return (
                      <Card key={req.id}>
                        <CardContent className="py-3 flex items-center justify-between gap-3">
                          <div className="min-w-0">
                            <p className="text-sm font-medium text-foreground truncate">{req.courses?.title || "Course"}</p>
                            <p className="text-xs text-muted-foreground">
                              {req.start_date
                                ? format(new Date(req.start_date + "T00:00:00"), "EEE d MMM yyyy")
                                : "—"}
                              {req.venues?.name && ` · ${req.venues.name}`}
                            </p>
                          </div>
                          <Badge variant="outline" className={`text-[10px] shrink-0 ${s.cls}`}>{s.label}</Badge>
                        </CardContent>
                      </Card>
                    );
                  })}
                </div>
              </div>
            )}

            {SHOW_COMPLIANCE && requirements?.requirements?.length > 0 && (
              <div>
                <div className="flex items-center justify-between mb-3">
                  <h3 className="text-sm font-semibold text-foreground flex items-center gap-2">
                    <Target className="w-4 h-4 text-primary" /> Training Requirements
                  </h3>
                  <Badge variant={compliancePercent === 100 ? "default" : "outline"} className="text-[10px]">
                    {compliancePercent}% compliant
                  </Badge>
                </div>
                <Card>
                  <CardContent className="py-3 space-y-1.5">
                    {requirements!.requirements.map((req: any) => {
                      const status = getRequirementStatus(req.course_id);
                      const config = {
                        valid: { icon: CheckCircle2, cls: "text-green-500", bg: "bg-green-500/10" },
                        expiring: { icon: Clock, cls: "text-amber-500", bg: "bg-amber-500/10" },
                        expired: { icon: AlertCircle, cls: "text-destructive", bg: "bg-destructive/10" },
                        missing: { icon: AlertCircle, cls: "text-destructive", bg: "bg-destructive/10" },
                      }[status];
                      const Icon = config.icon;
                      return (
                        <div key={`${req.job_role_id}-${req.course_id}`} className={`flex items-center gap-3 p-2.5 rounded-lg ${config.bg}`}>
                          <Icon className={`w-4 h-4 shrink-0 ${config.cls}`} />
                          <p className="text-sm text-foreground flex-1 truncate">{req.courses?.title || "Course"}</p>
                          {(status === "missing" || status === "expired") && req.courses?.slug && (
                            <Button size="sm" variant="ghost" className="h-6 text-[10px] text-primary" onClick={() => router.visit(`/course/${req.courses.slug}`)}>
                              Book <ExternalLink className="w-3 h-3 ml-0.5" />
                            </Button>
                          )}
                        </div>
                      );
                    })}
                  </CardContent>
                </Card>
              </div>
            )}

            {enrolments && enrolments.length > 0 && (
              <div>
                <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                  <Monitor className="w-4 h-4 text-primary" /> E-Learning Progress
                </h3>
                <div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
                  {enrolments.slice(0, 4).map((e: any) => {
                    const isLaunchable = Boolean(e.videotile_user_course_id);
                    const launchUrl = `/elearning/${e.id}/launch`;
                    return (
                      <Card key={e.id} className="hover:border-primary/40 transition-colors">
                        <CardContent className="py-3 flex items-center gap-3">
                          <div className="w-9 h-9 rounded-lg bg-primary/10 flex items-center justify-center shrink-0">
                            <Monitor className="w-4 h-4 text-primary" />
                          </div>
                          <div className="flex-1 min-w-0">
                            <p className="text-xs font-medium text-foreground truncate">{e.course?.title || "Course"}</p>
                            <div className="flex items-center gap-2 mt-1">
                              <Progress value={e.progress_percent} className="h-1 flex-1" />
                              <span className="text-[10px] text-muted-foreground font-medium">{e.progress_percent}%</span>
                            </div>
                          </div>
                          {isLaunchable ? (
                            <Button size="sm" variant="default" className="h-7 text-[10px] px-2" asChild>
                              <a href={launchUrl} target="_blank" rel="noopener noreferrer">
                                {e.progress_percent > 0 ? "Continue" : "Start"} <ExternalLink className="w-3 h-3 ml-1" />
                              </a>
                            </Button>
                          ) : (
                            <span className="text-[10px] text-muted-foreground italic">Pending sync</span>
                          )}
                        </CardContent>
                      </Card>
                    );
                  })}
                </div>
              </div>
            )}
          </TabsContent>

          <TabsContent value="courses" className="mt-0 space-y-6">
            <div>
              <h3 className="text-sm font-semibold text-foreground mb-3 flex items-center gap-2">
                <Search className="w-4 h-4 text-primary" /> Find & Request a Course
              </h3>
              <CourseLookup />
            </div>

            <Tabs defaultValue="upcoming">
              <TabsList className="bg-muted/50 mb-4">
                <TabsTrigger value="upcoming" className="text-xs">
                  <Calendar className="w-3 h-3 mr-1" /> Upcoming ({upcomingOrders.length})
                </TabsTrigger>
                <TabsTrigger value="history" className="text-xs">
                  <History className="w-3 h-3 mr-1" /> History ({completedOrders.length})
                </TabsTrigger>
              </TabsList>

              <TabsContent value="upcoming" className="space-y-3 mt-0">
                {ordersLoading ? (
                  <div className="space-y-3">
                    {[1, 2].map(i => (
                      <Card key={i} className="animate-pulse">
                        <CardContent className="py-4">
                          <div className="h-4 rounded w-2/3 mb-2 bg-muted" />
                          <div className="h-3 rounded w-1/3 bg-muted" />
                        </CardContent>
                      </Card>
                    ))}
                  </div>
                ) : !upcomingOrders.length ? (
                  <Card>
                    <CardContent className="py-16 text-center">
                      <div className="w-16 h-16 rounded-2xl bg-muted/50 flex items-center justify-center mx-auto mb-4">
                        <BookOpen className="w-8 h-8 text-muted-foreground/40" />
                      </div>
                      <p className="text-sm font-semibold text-foreground mb-1">No upcoming courses</p>
                      <p className="text-xs text-muted-foreground mb-5">Browse our catalogue to find your next course</p>
                      <Button size="sm" onClick={() => {
                        if (preview.active) { window.open("/courses", "_blank"); } else { router.visit("/courses"); }
                      }}>
                        <Search className="w-4 h-4 mr-1.5" /> Browse Courses
                      </Button>
                    </CardContent>
                  </Card>
                ) : (
                  upcomingOrders.map((order: any) => {
                    const isOnline = !order.start_date;
                    const isToday = order.start_date === format(new Date(), "yyyy-MM-dd");
                    const isCurrent = order.id === orderId;
                    const daysUntil = isOnline
                      ? null
                      : differenceInDays(new Date(order.start_date + "T00:00:00"), new Date());
                    return (
                      <Card key={order.id} className={isCurrent ? "border-primary" : ""}>
                        <CardContent className="py-4">
                          <div className="flex items-start gap-4">
                            <div className="w-11 h-11 rounded-xl bg-primary/10 flex items-center justify-center shrink-0">
                              <BookOpen className="w-5 h-5 text-primary" />
                            </div>
                            <div className="flex-1 min-w-0">
                              <div className="flex items-start justify-between gap-2">
                                <h3 className="text-sm font-semibold text-foreground leading-snug">{order.courses?.title || "Course"}</h3>
                                <div className="flex gap-1.5 shrink-0">
                                  {isOnline && <Badge className="bg-primary/15 text-primary border-0 text-[10px]">Online</Badge>}
                                  {!isOnline && isToday && <Badge className="bg-green-600 text-white text-[10px]">Today</Badge>}
                                  {!isOnline && !isToday && daysUntil !== null && daysUntil <= 7 && <Badge variant="outline" className="text-[10px]">{daysUntil} day{daysUntil !== 1 ? "s" : ""} away</Badge>}
                                  <Badge variant={(order.status === "confirmed" || order.status === "paid") ? "default" : "secondary"} className="text-[10px] capitalize">{order.status}</Badge>
                                </div>
                              </div>
                              <div className="flex flex-wrap gap-x-4 gap-y-1 mt-1.5">
                                <span className="text-xs flex items-center gap-1 text-muted-foreground">
                                  <Calendar className="w-3 h-3" />
                                  {order.start_date
                                    ? format(new Date(order.start_date + "T00:00:00"), "EEE d MMM yyyy")
                                    : "Online — start anytime"}
                                </span>
                                {order.venues && (
                                  <span className="text-xs flex items-center gap-1 text-muted-foreground">
                                    <MapPin className="w-3 h-3" />
                                    {order.venues.name}{order.venues.city ? `, ${order.venues.city}` : ""}
                                  </span>
                                )}
                                {order.courses?.days && (
                                  <span className="text-xs flex items-center gap-1 text-muted-foreground">
                                    <Clock className="w-3 h-3" />
                                    {order.courses.days} day{order.courses.days > 1 ? "s" : ""}
                                  </span>
                                )}
                              </div>
                            </div>
                          </div>
                          {(order.status === "confirmed" || order.status === "paid") && (() => {
                            // For VT-linked orders, surface a launch link to
                            // the matching enrolment (looked up by course_id
                            // since the dashboard's enrolments are already
                            // scoped to the current user).
                            const enr = isOnline
                              ? enrolments?.find((e: any) => e.course_id === order.course_id && e.videotile_user_course_id)
                              : null;
                            return (
                              <div className="mt-3 pt-3 border-t border-border flex flex-wrap items-center gap-2">
                                {enr && (
                                  <Button size="sm" className="h-8 text-xs" asChild>
                                    <a href={`/elearning/${enr.id}/launch`} target="_blank" rel="noopener noreferrer">
                                      {enr.progress_percent > 0 ? "Continue" : "Start"} on VideoTile
                                      <ExternalLink className="w-3 h-3 ml-1.5" />
                                    </a>
                                  </Button>
                                )}
                                <BookingActions order={order} queryKeys={[["delegate-orders", effectiveEmail || ""]]} />
                              </div>
                            );
                          })()}
                        </CardContent>
                      </Card>
                    );
                  })
                )}
              </TabsContent>

              <TabsContent value="history" className="space-y-3 mt-0">
                {!completedOrders.length ? (
                  <Card>
                    <CardContent className="py-16 text-center">
                      <History className="w-12 h-12 mx-auto mb-3 text-muted-foreground/30" />
                      <p className="text-sm font-medium text-foreground">No training history yet</p>
                    </CardContent>
                  </Card>
                ) : (
                  completedOrders.map((order: any) => (
                    <Card key={order.id} className="opacity-75 hover:opacity-100 transition-opacity">
                      <CardContent className="py-3 flex items-center gap-4">
                        <div className="w-10 h-10 rounded-lg bg-muted flex items-center justify-center shrink-0">
                          <BookOpen className="w-5 h-5 text-muted-foreground" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium text-foreground truncate">{order.courses?.title || "Course"}</p>
                          <p className="text-xs text-muted-foreground">
                            {order.start_date
                              ? format(new Date(order.start_date + "T00:00:00"), "d MMM yyyy")
                              : "Online"}
                            {order.venues && ` · ${order.venues.name}`}
                          </p>
                        </div>
                        <div className="flex items-center gap-2 shrink-0">
                          <Badge variant="secondary" className="text-[10px] capitalize">{order.status}</Badge>
                          {order.courses?.slug && (
                            <Button variant="ghost" size="sm" className="h-7 text-xs text-primary" onClick={() => router.visit(`/course/${order.courses.slug}`)}>
                              <RefreshCw className="w-3 h-3 mr-1" /> Rebook
                            </Button>
                          )}
                        </div>
                      </CardContent>
                    </Card>
                  ))
                )}
              </TabsContent>
            </Tabs>
          </TabsContent>

          <TabsContent value="certificates" className="mt-0">
            <CertificateWallet email={effectiveEmail} />
          </TabsContent>

          <TabsContent value="notifications" className="mt-0 space-y-2">
            {(!notifications || notifications.length === 0) ? (
              <Card>
                <CardContent className="py-16 text-center">
                  <Bell className="w-12 h-12 mx-auto mb-3 text-muted-foreground/30" />
                  <p className="text-sm font-medium text-foreground">All caught up!</p>
                  <p className="text-xs text-muted-foreground">No notifications right now.</p>
                </CardContent>
              </Card>
            ) : (
              notifications.map((notif: any) => (
                <Card key={notif.id} className={!notif.is_read ? "border-primary/30 bg-primary/5" : ""}>
                  <CardContent className="py-3 flex items-start gap-3">
                    <div className={`w-2 h-2 rounded-full mt-1.5 shrink-0 ${!notif.is_read ? "bg-primary" : "bg-muted"}`} />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium text-foreground">{notif.title}</p>
                      {notif.message && <p className="text-xs text-muted-foreground mt-0.5">{notif.message}</p>}
                      <p className="text-[10px] text-muted-foreground mt-1">{format(new Date(notif.created_at), "d MMM yyyy, HH:mm")}</p>
                    </div>
                    <div className="flex items-center gap-1 shrink-0">
                      {notif.link && (
                        <Button variant="ghost" size="sm" className="h-7 text-xs" onClick={() => router.visit(notif.link)}>
                          View <ArrowRight className="w-3 h-3 ml-1" />
                        </Button>
                      )}
                      {!notif.is_read && (
                        <Button variant="ghost" size="sm" className="h-7 text-xs text-muted-foreground" onClick={() => markReadMutation.mutate(notif.id)}>
                          Dismiss
                        </Button>
                      )}
                    </div>
                  </CardContent>
                </Card>
              ))
            )}
          </TabsContent>

          <TabsContent value="referrals" className="mt-0">
            <ReferralModule />
          </TabsContent>

          <TabsContent value="guide" className="mt-0">
            <SopManual
              effectiveRoles={["delegate"]}
              title="Delegate Guide"
              description="Step-by-step help for booking courses, completing your onboarding forms, e-learning, and managing your certificates."
              showDownload={false}
              enableTutorials={false}
            />
          </TabsContent>
        </Tabs>
      </div>
    </div>
  );
};

export default DelegateDashboard;
