"use client";

import { useState, useMemo, useEffect } from "react";
import { useTranslations } from "next-intl";
import { useQueryClient } from "@tanstack/react-query";
import ViewReportModal from "./modals/ViewReportModal";
import ScreeningReportsModal from "./modals/ScreeningReportsModal";
import { getDashboardControllerGetDashboardStatsV1QueryKey } from "@/api/user/practitioner-dashboard/practitioner-dashboard";
import {
  usePractitionerDashboardControllerGetPendingScreeningsV1,
  usePractitionerDashboardControllerGetCompletedScreeningsV1,
  getPractitionerDashboardControllerGetPendingScreeningsV1QueryKey,
} from "@/api/user/practitioner-dashboard/practitioner-dashboard";
import { useClientsControllerSendReminderV1 } from "@/api/user/practitioner-clients/practitioner-clients";
import toast from "react-hot-toast";
import ReminderSentModal from "./modals/ReminderSentModal";
import { PendingScreeningData, CompletedScreeningData } from "@/api/user/generated.schemas";

interface ScreeningRecord {
  id: string;
  clientId: number;
  screeningId: number;
  clientName: string;
  email: string;
  screeningDate: string;
  age: number | null;
  gender: string | null;
  screeningStatus: "Pending" | "Completed";
  suicideRiskCategory: string | null;
}

function StatusBadge({ status, t }: { status: "Pending" | "Completed"; t: (key: string) => string }) {
  const styles = {
    Pending: "bg-yellow-50 text-yellow-700 border-yellow-200",
    Completed: "bg-green-50 text-green-700 border-green-200",
  };

  const statusLabels = {
    Pending: t("screening.pending"),
    Completed: t("screening.completed"),
  };

  return (
    <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-full border ${styles[status]}`}>
      <span className={`w-1.5 h-1.5 rounded-full ${status === "Pending" ? "bg-yellow-500" : "bg-green-500"}`}></span>
      {statusLabels[status]}
    </span>
  );
}

function RiskBadge({ risk }: { risk: string | null }) {
  const t = useTranslations("practitioner");
  if (!risk) return <span className="text-gray-400">-</span>;

  const normalized = risk.toLowerCase();

  const getBadgeStyle = () => {
    if (normalized.includes("high")) return "bg-red-50 text-red-600 border-red-100";
    if (normalized.includes("moderate")) return "bg-red-50 text-red-600 border-red-100";
    if (normalized.includes("mild")) return "bg-yellow-50 text-yellow-600 border-yellow-100";
    if (normalized.includes("low")) return "bg-green-50 text-green-600 border-green-100";
    return "bg-gray-50 text-gray-600 border-gray-100";
  };

  const getDotColor = () => {
    if (normalized.includes("high")) return "bg-red-500";
    if (normalized.includes("moderate")) return "bg-red-500";
    if (normalized.includes("mild")) return "bg-yellow-500";
    if (normalized.includes("low")) return "bg-green-500";
    return "bg-gray-500";
  };

  const getLabel = () => {
    if (normalized.includes("high")) return t("modals.screeningReports.highRisk");
    if (normalized.includes("moderate")) return t("modals.screeningReports.moderateRisk");
    if (normalized.includes("mild")) return t("modals.screeningReports.mildRisk");
    if (normalized.includes("low")) return t("modals.screeningReports.lowRisk");
    return risk;
  };

  return (
    <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-full border ${getBadgeStyle()}`}>
      <span className={`w-1.5 h-1.5 rounded-full ${getDotColor()}`}></span>
      {getLabel()}
    </span>
  );
}

export default function ScreeningTable() {
  const t = useTranslations("practitioner");
  const queryClient = useQueryClient();
  const [searchQuery, setSearchQuery] = useState("");
  const [sortBy, setSortBy] = useState("newest");
  const [filterOpen, setFilterOpen] = useState(false);
  const [filterStatus, setFilterStatus] = useState("");
  const [filterGender, setFilterGender] = useState("");
  const [tempFilterStatus, setTempFilterStatus] = useState("");
  const [tempFilterGender, setTempFilterGender] = useState("");
  const [autoDownloadClientId, setAutoDownloadClientId] = useState<number | null>(null);
  const [autoDownloadScreeningId, setAutoDownloadScreeningId] = useState<number | null>(null);
  const [viewingClientId, setViewingClientId] = useState<number | null>(null);
  const [viewingScreeningId, setViewingScreeningId] = useState<number | null>(null);
  const [viewingRisk, setViewingRisk] = useState<string | null>(null);
  const [viewingClientName, setViewingClientName] = useState<string | null>(null);
  const [viewingClientAge, setViewingClientAge] = useState<number | null>(null);
  const [screeningReportsClientId, setScreeningReportsClientId] = useState<number | null>(null);
  const [screeningReportsClientName, setScreeningReportsClientName] = useState<string>("");
  const [screeningReportsClientAge, setScreeningReportsClientAge] = useState<number | null>(null);
  const [reminderSentOpen, setReminderSentOpen] = useState(false);
  const [reminderEmailNotice, setReminderEmailNotice] = useState(false);
  const [sendingReminderId, setSendingReminderId] = useState<string | null>(null);

  // Send reminder mutation - callbacks at hook level for reliable state updates
  const { mutate: sendReminder } = useClientsControllerSendReminderV1({
    mutation: {
      onSuccess: (data: any) => {
        setSendingReminderId(null);
        setReminderEmailNotice(!!data?.email_notice);
        setReminderSentOpen(true);
        queryClient.invalidateQueries({ queryKey: getPractitionerDashboardControllerGetPendingScreeningsV1QueryKey() });
        queryClient.invalidateQueries({ queryKey: getDashboardControllerGetDashboardStatsV1QueryKey() });
      },
      onError: (error: any) => {
        console.error("Reminder API error:", error);
        setSendingReminderId(null);
        toast.error(error?.response?.data?.message || t("modals.reminderError"));
      },
    },
  });

  // Fetch pending screenings
  const { data: pendingResponse, isLoading: isPendingLoading } = usePractitionerDashboardControllerGetPendingScreeningsV1(
    { page: 1, limit: 100 }
  );

  // Fetch completed screenings
  const { data: completedResponse, isLoading: isCompletedLoading } = usePractitionerDashboardControllerGetCompletedScreeningsV1(
    { page: 1, limit: 100 }
  );

  const isLoading = isPendingLoading || isCompletedLoading;

  // Transform and merge data
  const allScreenings = useMemo(() => {
    const pending: ScreeningRecord[] = ((pendingResponse as any)?.data || []).map((item: PendingScreeningData) => ({
      id: `pending-${item.screening_id}`,
      clientId: item.client_id,
      screeningId: item.screening_id,
      clientName: item.client_name,
      email: item.client_email || "-",
      screeningDate: item.created_at,
      age: item.age || null,
      gender: item.gender || null,
      screeningStatus: "Pending" as const,
      suicideRiskCategory: null,
    }));

    const completed: ScreeningRecord[] = ((completedResponse as any)?.data || []).map((item: CompletedScreeningData) => ({
      id: `completed-${item.screening_id}`,
      clientId: item.client_id,
      screeningId: item.screening_id,
      clientName: item.client_name,
      email: item.client_email || "-",
      screeningDate: item.completed_at,
      age: item.age || null,
      gender: item.gender || null,
      screeningStatus: "Completed" as const,
      suicideRiskCategory: item.suicide_risk_category || null,
    }));

    return [...pending, ...completed];
  }, [pendingResponse, completedResponse]);

  // Format date helper
  const formatDate = (dateString: string) => {
    if (!dateString) return "-";
    const date = new Date(dateString);
    return date.toLocaleDateString("en-US", { day: "2-digit", month: "short", year: "numeric" });
  };

  const handleViewReport = (clientId: number, screeningId: number, risk: string | null, name: string, age: number | null) => {
    setViewingClientId(clientId);
    setViewingScreeningId(screeningId);
    setViewingRisk(risk);
    setViewingClientName(name);
    setViewingClientAge(age);
  };

  const handleSendReminder = (clientId: number, recordId: string) => {
    setSendingReminderId(recordId);
    sendReminder({ id: clientId });
  };

  // Filter and sort data
  const filteredData = useMemo(() => {
    let data = allScreenings.filter((record) =>
      record.clientName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      record.email.toLowerCase().includes(searchQuery.toLowerCase())
    );

    if (filterStatus) data = data.filter((r) => r.screeningStatus === filterStatus);
    if (filterGender) data = data.filter((r) => r.gender?.toLowerCase() === filterGender.toLowerCase());

    // Sort data
    if (sortBy === "newest") {
      data = [...data].sort((a, b) => new Date(b.screeningDate).getTime() - new Date(a.screeningDate).getTime());
    } else if (sortBy === "name") {
      data = [...data].sort((a, b) => a.clientName.localeCompare(b.clientName));
    } else if (sortBy === "date") {
      data = [...data].sort((a, b) => new Date(a.screeningDate).getTime() - new Date(b.screeningDate).getTime());
    } else if (sortBy === "status") {
      data = [...data].sort((a, b) => a.screeningStatus.localeCompare(b.screeningStatus));
    }

    return data;
  }, [allScreenings, searchQuery, sortBy, filterStatus, filterGender]);

  const handleOpenFilter = () => {
    setTempFilterStatus(filterStatus);
    setTempFilterGender(filterGender);
    setFilterOpen(true);
  };
  const handleApplyFilters = () => {
    setFilterStatus(tempFilterStatus);
    setFilterGender(tempFilterGender);
    setFilterOpen(false);
  };
  const handleClearFilters = () => {
    setTempFilterStatus("");
    setTempFilterGender("");
  };
  const activeFilterCount = [filterStatus, filterGender].filter(Boolean).length;

  useEffect(() => {
    if (!filterOpen) return;
    const handler = (e: MouseEvent) => {
      if (!(e.target as HTMLElement).closest(".filter-dropdown-st")) setFilterOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [filterOpen]);

  return (
    <div className="bg-white rounded-xl border border-gray-200 shadow-sm">
      {/* Header */}
      <div className="p-5 border-b border-gray-200">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <h3 className="text-lg font-semibold text-gray-900">{t("screening.title")}</h3>
          <div className="flex flex-col sm:flex-row gap-3">
            {/* Search */}
            <div className="relative">
              <svg
                className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400"
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
              <input
                type="text"
                placeholder={t("common.search")}
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="pl-10 pr-4 py-2 w-full sm:w-64 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]/20 focus:border-[#3B9EC9]"
              />
            </div>
            {/* Sort */}
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value)}
              className="px-4 py-2 text-sm text-gray-600 border border-gray-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-[#3B9EC9]/20 cursor-pointer"
            >
              <option value="newest">{t("common.sortBy")}</option>
              <option value="name">{t("common.name")}</option>
              <option value="date">{t("screening.date")}</option>
              <option value="status">{t("screening.status")}</option>
            </select>
            {/* Filter */}
            <div className="relative filter-dropdown-st">
              <button
                onClick={handleOpenFilter}
                className={`inline-flex items-center gap-2 px-4 py-2 text-sm border rounded-lg transition cursor-pointer ${activeFilterCount > 0 ? "border-[#3B9EC9] text-[#3B9EC9] bg-[#3B9EC9]/5" : "border-gray-200 text-gray-600 hover:bg-gray-50"}`}
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.5}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 6h9.75M10.5 6a1.5 1.5 0 11-3 0m3 0a1.5 1.5 0 10-3 0M3.75 6H7.5m3 12h9.75m-9.75 0a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m-3.75 0H7.5m9-6h3.75m-3.75 0a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m-9.75 0h9.75" />
                </svg>
                {t("common.filter")}
                {activeFilterCount > 0 && (
                  <span className="ml-1 px-2 py-0.5 bg-[#3B9EC9] text-white text-xs rounded-full">{activeFilterCount}</span>
                )}
              </button>

              {filterOpen && (
                <div className="absolute right-0 top-11 z-50 w-60 bg-white border border-gray-200 rounded-xl shadow-lg p-4 filter-dropdown-st">
                  <div className="flex items-center justify-between mb-3">
                    <h3 className="text-sm font-semibold text-gray-900">{t("common.filters")}</h3>
                    <button onClick={() => setFilterOpen(false)} className="text-gray-400 hover:text-gray-600 cursor-pointer">
                      <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                      </svg>
                    </button>
                  </div>

                  {/* Status */}
                  <div className="mb-3">
                    <label className="block text-xs font-medium text-gray-700 mb-1">{t("screening.screeningStatus")}</label>
                    <div className="relative">
                      <select
                        value={tempFilterStatus}
                        onChange={(e) => setTempFilterStatus(e.target.value)}
                        className="appearance-none w-full pl-3 pr-8 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] cursor-pointer"
                      >
                        <option value="">{t("common.all")}</option>
                        <option value="Pending">{t("screening.pending")}</option>
                        <option value="Completed">{t("screening.completed")}</option>
                      </select>
                      <svg className="pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                      </svg>
                    </div>
                  </div>

                  {/* Gender */}
                  <div className="mb-4">
                    <label className="block text-xs font-medium text-gray-700 mb-1">{t("clients.gender")}</label>
                    <div className="relative">
                      <select
                        value={tempFilterGender}
                        onChange={(e) => setTempFilterGender(e.target.value)}
                        className="appearance-none w-full pl-3 pr-8 py-2 border border-gray-200 rounded-lg text-sm text-gray-600 focus:outline-none focus:ring-2 focus:ring-[#3B9EC9] cursor-pointer"
                      >
                        <option value="">{t("common.all")}</option>
                        <option value="Male">{t("clients.male")}</option>
                        <option value="Female">{t("clients.female")}</option>
                        <option value="Other">{t("clients.other")}</option>
                      </select>
                      <svg className="pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                      </svg>
                    </div>
                  </div>

                  <div className="flex gap-2">
                    <button onClick={handleClearFilters} className="flex-1 py-1.5 text-sm border border-gray-200 rounded-lg text-gray-600 hover:bg-gray-50 transition cursor-pointer">
                      {t("common.clear")}
                    </button>
                    <button onClick={handleApplyFilters} className="flex-1 py-1.5 text-sm bg-[#3B9EC9] text-white rounded-lg hover:bg-[#2D8AB5] transition cursor-pointer">
                      {t("common.apply")}
                    </button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* Table */}
      <div className="overflow-x-auto border border-gray-200 rounded-lg mx-5 my-5">
        <table className="w-full min-w-[800px]">
          <thead>
            <tr className="bg-gray-50 border-b border-gray-200">
              <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-r border-gray-200">{t("clients.clientName")}</th>
              <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-r border-gray-200">{t("screening.screeningDate")}</th>
              <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-r border-gray-200">{t("clients.age")}</th>
              <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-r border-gray-200">{t("clients.gender")}</th>
              <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-r border-gray-200">{t("screening.screeningStatus")}</th>
              <th className="text-left px-5 py-3 text-sm font-medium text-gray-600 border-r border-gray-200">{t("screening.suicideRiskCategory")}</th>
              <th className="text-left px-5 py-3 text-sm font-medium text-gray-600">{t("screening.action")}</th>
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              <tr>
                <td colSpan={7} className="py-8 text-center text-gray-500">
                  <div className="flex justify-center">
                    <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div>
                  </div>
                </td>
              </tr>
            ) : filteredData.length === 0 ? (
              <tr>
                <td colSpan={7} className="py-8 text-center text-gray-500">
                  {t("screening.noData")}
                </td>
              </tr>
            ) : (
              filteredData.map((record, index) => (
              <tr key={record.id} className={`${index !== filteredData.length - 1 ? 'border-b border-gray-200' : ''} hover:bg-gray-50/50 transition`}>
                <td className="px-5 py-4 border-r border-gray-200">
                  <div className="flex items-center gap-3">
                    <div className="w-10 h-10 rounded-full bg-gray-200 flex items-center justify-center overflow-hidden flex-shrink-0">
                      <svg className="w-6 h-6 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                      </svg>
                    </div>
                    <div>
                      <p className="text-sm font-medium text-gray-900">{record.clientName}</p>
                      <p className="text-xs text-gray-500">{record.email}</p>
                    </div>
                  </div>
                </td>
                <td className="px-5 py-4 text-sm text-gray-600 border-r border-gray-200">{formatDate(record.screeningDate)}</td>
                <td className="px-5 py-4 text-sm text-gray-600 border-r border-gray-200">{record.age || "-"}</td>
                <td className="px-5 py-4 text-sm text-gray-600 border-r border-gray-200">{record.gender || "-"}</td>
                <td className="px-5 py-4 border-r border-gray-200">
                  <StatusBadge status={record.screeningStatus} t={t} />
                </td>
                <td
                  className={`px-5 py-4 border-r border-gray-200${record.screeningStatus === "Completed" && record.suicideRiskCategory ? " cursor-pointer" : ""}`}
                  onClick={() => {
                    if (record.screeningStatus === "Completed" && record.suicideRiskCategory) {
                      setScreeningReportsClientId(record.clientId);
                      setScreeningReportsClientName(record.clientName);
                      setScreeningReportsClientAge(record.age);
                    }
                  }}
                >
                  <RiskBadge risk={record.suicideRiskCategory} />
                </td>
                <td className="px-5 py-4">
                  <div className="flex items-center justify-center gap-3">
                    {record.screeningStatus === "Completed" && (
                      <button
                        onClick={() => handleViewReport(record.clientId, record.screeningId, record.suicideRiskCategory, record.clientName, record.age)}
                        className="w-9 h-9 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition cursor-pointer"
                        title={t("screening.viewReport")}
                      >
                        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                          <path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                          <path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                        </svg>
                      </button>
                    )}
                    {record.screeningStatus === "Pending" ? (
                      <button
                        onClick={() => handleSendReminder(record.clientId, record.id)}
                        disabled={sendingReminderId === record.id}
                        className="w-9 h-9 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                        title={t("screening.sendReminder")}
                      >
                        {sendingReminderId === record.id ? (
                          <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-[#3B9EC9]"></div>
                        ) : (
                          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
                          </svg>
                        )}
                      </button>
                    ) : (
                      <button
                        onClick={() => { setAutoDownloadClientId(record.clientId); setAutoDownloadScreeningId(record.screeningId); }}
                        disabled={autoDownloadScreeningId === record.screeningId}
                        className="w-9 h-9 flex items-center justify-center rounded-full border border-[#3B9EC9] text-[#3B9EC9] hover:bg-[#3B9EC9]/5 transition cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                        title={t("screening.download")}
                      >
                        {autoDownloadScreeningId === record.screeningId ? (
                          <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-[#3B9EC9]"></div>
                        ) : (
                          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                            <path strokeLinecap="round" strokeLinejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
                          </svg>
                        )}
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            ))
            )}
          </tbody>
        </table>
      </div>

      {/* Hidden auto-download (no modal) */}
      {autoDownloadScreeningId && (
        <ViewReportModal
          isOpen={false}
          autoDownload
          clientId={autoDownloadClientId ?? undefined}
          screeningId={autoDownloadScreeningId}
          onClose={() => { setAutoDownloadClientId(null); setAutoDownloadScreeningId(null); }}
        />
      )}

      {/* View Report Modal */}
      <ViewReportModal
        isOpen={!!viewingScreeningId}
        onClose={() => { setViewingClientId(null); setViewingScreeningId(null); setViewingRisk(null); setViewingClientName(null); setViewingClientAge(null); }}
        clientId={viewingClientId ?? undefined}
        screeningId={viewingScreeningId}
        suicideRisk={viewingRisk || undefined}
        clientName={viewingClientName || undefined}
        clientAge={viewingClientAge}
      />

      {/* Screening Reports Modal (opened from risk badge) */}
      <ScreeningReportsModal
        isOpen={!!screeningReportsClientId}
        onClose={() => { setScreeningReportsClientId(null); setScreeningReportsClientName(""); setScreeningReportsClientAge(null); }}
        clientId={screeningReportsClientId ?? undefined}
        clientName={screeningReportsClientName}
        clientAge={screeningReportsClientAge}
      />

      {/* Reminder Sent Modal */}
      <ReminderSentModal
        isOpen={reminderSentOpen}
        onClose={() => setReminderSentOpen(false)}
        showEmailNotice={reminderEmailNotice}
      />
    </div>
  );
}
