"use client";

import { useRef, useState, useEffect } from "react";
import Image from "next/image";
import mbhsLogo from "@/public/images/mbhs-logo.png";
import { useParams } from "next/navigation";
import { Link, useRouter, usePathname } from "@/i18n/navigation";
import FlagIcon from "@/components/ui/FlagIcon";
import { useTranslations, useLocale } from "next-intl";
import { getUserDataCookie } from "@/lib/cookies";
import jsPDF from "jspdf";
import { usePublicAssessmentControllerGetResultsV1 } from "@/api/user/public-assessment/public-assessment";
import { computeSuicideRisk } from "@/lib/suicideRiskAlgorithm";

interface ScaleResult {
  name: string;
  percentage: number;
  color: string;
}

// Scale order per MBHS specification
const SCALE_ORDER = [
  'somatization',
  'cognitive_issues',
  'demoralization',
  'anhedonia',
  'anxiety',
  'suicidal_ideation',
  'activation',
  'disconstraint',
  'substance_use_problems'
];

// Map snake_case API names to Title Case display names
const SCALE_DISPLAY_NAMES: Record<string, string> = {
  'somatization': 'Somatization',
  'cognitive_issues': 'Cognitive Issues',
  'demoralization': 'Demoralization',
  'anhedonia': 'Anhedonia',
  'anxiety': 'Anxiety',
  'suicidal_ideation': 'Suicidal Ideation',
  'activation': 'Activation',
  'disconstraint': 'Disconstraint',
  'substance_use_problems': 'Substance Use Problems'
};

export default function AssessmentResultsPage() {
  const router = useRouter();
  const params = useParams();
  const t = useTranslations();
  const locale = useLocale();
  const pathname = usePathname();
  const reportRef = useRef<HTMLDivElement>(null);
  const [isDownloading, setIsDownloading] = useState(false);

  const token = params.token as string;

  const [isPractitionerViewer, setIsPractitionerViewer] = useState(false);
  const [practitionerHomeHref, setPractitionerHomeHref] = useState("/practitioner");

  useEffect(() => {
    const userData = getUserDataCookie();
    if (!userData) return;
    if (userData?.role === "Practitioners") {
      setIsPractitionerViewer(true);
      setPractitionerHomeHref(userData?.subscription_type === "group" ? "/practice-manager/dashboard" : "/practitioner");
    }
  }, []);


  const getHomeHref = () => {
    const userData = getUserDataCookie();
    if (!userData) return "/";
    if (userData?.is_managed === true || userData?.subscription_type === "individual") {
      return "/practitioner";
    }
    if (userData?.subscription_type === "group") {
      return "/practice-manager/dashboard";
    }
    return "/practitioner";
  };

  // Fetch results from API
  const { data: response, isLoading, error } = usePublicAssessmentControllerGetResultsV1(token, {
    query: { enabled: !!token },
  });

  const reportData = (response as any)?.data;
  const isTherapistInvited = reportData?.is_therapist_invited === true;

  // Use suicide_risk_category only — do NOT fall back to highest_risk (that is highest across all scales, not suicide-specific)
  const backendRisk = reportData?.suicide_risk_category || reportData?.screening?.suicide_risk_category || reportData?.overall_risk || reportData?.screening?.overall_risk || "";
  const itemResponsesArr: any[] = reportData?.item_responses || reportData?.screening?.item_responses || [];
  const resultsArr: any[] = reportData?.results || reportData?.screening?.results || [];

  // Full MBHS 3.0 24-condition algorithm
  const suicideRisk = computeSuicideRisk({
    itemResponses: itemResponsesArr as Array<{ item_number: number; score: number }>,
    results: resultsArr as Array<{ scale_name: string; raw_score?: number; percentile?: number | string; risk_level?: string }>,
    backendRisk,
  });

  const handleDownloadPDF = async () => {
    if (!reportRef.current || isDownloading || !reportData) return;

    setIsDownloading(true);
    try {
      const html2canvas = (await import("html2canvas-pro")).default;

      const element = reportRef.current;

      const canvas = await html2canvas(element, {
        scale: 2,
        useCORS: true,
        backgroundColor: "#ffffff",
        logging: false,
      });

      const imgData = canvas.toDataURL("image/png");

      const pdf = new jsPDF({
        orientation: "portrait",
        unit: "mm",
        format: "a4",
      });

      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = pdf.internal.pageSize.getHeight();
      const imgWidth = canvas.width;
      const imgHeight = canvas.height;
      const ratio = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight);
      const imgX = (pdfWidth - imgWidth * ratio) / 2;
      const imgY = 10;

      pdf.addImage(imgData, "PNG", imgX, imgY, imgWidth * ratio, imgHeight * ratio);
      const clientName = reportData.client_name || "Client";
      pdf.save(`MBHS-Report-${clientName.replace(/\s+/g, "-")}.pdf`);
    } catch (error) {
      console.error("Error generating PDF:", error);
    } finally {
      setIsDownloading(false);
    }
  };

  const getRiskLabel = (risk: string) => {
    const normalizedRisk = risk?.toLowerCase().trim();
    // Only translate exact single-word values; pass through phrases like "At Least Moderate" as-is
    if (normalizedRisk === "at least moderate" || normalizedRisk === "high" || normalizedRisk === "moderate") return t("practitioner.common.high");
    if (normalizedRisk === "mild") return t("practitioner.common.mild");
    if (normalizedRisk === "low") return t("practitioner.common.low");
    return risk || "-";
  };

  const getSuicideRiskNarrative = () => {
    const normalized = suicideRisk?.toLowerCase() || "";
    if (normalized.includes("high") || normalized.includes("moderate"))
      return t("individual.results.suicideRiskNarrativeModerate");
    if (normalized.includes("mild"))
      return t("individual.results.suicideRiskNarrativeMild");
    return t("individual.results.suicideRiskNarrativeLow");
  };

  // Map API scale results to display format
  const getScaleResults = (): ScaleResult[] => {
    const scales = reportData?.results || reportData?.scale_results || reportData?.scales || [];
    if (!Array.isArray(scales) || scales.length === 0) {
      return [];
    }

    // Map and transform data from API format
    const mappedScales = scales.map((scale: any) => {
      const scaleName = scale.scale_name || scale.name || scale.label || 'unknown';
      return {
        name: SCALE_DISPLAY_NAMES[scaleName] || scaleName,
        percentage: Math.round(parseFloat(scale.percentile || scale.percentage || scale.score || scale.value || '0')),
        sortOrder: SCALE_ORDER.indexOf(scaleName)
      };
    });

    // Sort by correct MBHS order and return
    return mappedScales
      .sort((a, b) => {
        // Handle unknown scales by putting them at the end
        if (a.sortOrder === -1) return 1;
        if (b.sortOrder === -1) return -1;
        return a.sortOrder - b.sortOrder;
      })
      .map(({ name, percentage }) => ({ name, percentage, color: 'bg-cyan-400' }));
  };

  // 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 DownloadIcon = () => (
    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3" />
    </svg>
  );

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <svg className="animate-spin w-10 h-10 text-[#3B9EC9] mx-auto mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
          </svg>
          <p className="text-gray-600">{t("assessment.loading")}</p>
        </div>
      </div>
    );
  }

  if (error || !reportData) {
    return (
      <div className="min-h-screen bg-gray-50">
        {/* Header */}
        <header className="bg-white border-b border-gray-100 sticky top-0 z-40">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between h-16">
              <Link href={getHomeHref()} className="flex items-center gap-2">
                <Image src={mbhsLogo} alt="MBHS" width={40} height={40} className="w-10 h-10 rounded-lg" />
                <span className="text-xl font-bold text-gray-900">MBHS</span>
              </Link>
              <button
                onClick={() => router.replace(pathname, { locale: locale === "en" ? "es" : "en" })}
                className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 hover:bg-gray-200 rounded-full text-sm font-medium text-gray-700 transition cursor-pointer"
              >
                <FlagIcon locale={locale as "en" | "es"} />
                <span>{locale === "en" ? "EN" : "ES"}</span>
              </button>
            </div>
          </div>
        </header>

        <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
          <div className="flex flex-col items-center justify-center py-32">
            <div className="mb-6">
              <svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
                <circle cx="50" cy="50" r="45" stroke="#EF4444" strokeWidth="3" fill="none" />
                <path d="M35 35L65 65M65 35L35 65" stroke="#EF4444" strokeWidth="4" strokeLinecap="round" />
              </svg>
            </div>
            <h2 className="text-xl font-bold text-gray-900 mb-2">
              {t("assessment.resultsNotFound")}
            </h2>
            <p className="text-gray-500 text-sm text-center max-w-sm">
              {t("assessment.resultsNotFoundDescription")}
            </p>
          </div>
        </main>
      </div>
    );
  }

  const scaleResults = getScaleResults();

  // Therapist-invited clients should not see the report — therapist controls when/if it is shared
  if (isTherapistInvited && !isPractitionerViewer) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-[#f0f9ff] via-white to-[#f0fdf4] flex items-center justify-center px-4">
        <div className="max-w-md w-full mx-auto text-center">
          {/* Animated checkmark circle */}
          <div className="relative inline-flex items-center justify-center mb-8">
            <div className="w-24 h-24 rounded-full bg-gradient-to-br from-green-400 to-green-500 flex items-center justify-center shadow-lg shadow-green-200">
              <svg className="w-12 h-12 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" />
              </svg>
            </div>
            {/* Decorative ring */}
            <div className="absolute w-32 h-32 rounded-full border-2 border-green-200 animate-ping opacity-20" />
          </div>

          {/* Card */}
          <div className="bg-white rounded-2xl shadow-xl shadow-gray-100 border border-gray-100 px-8 py-10">
            <h1 className="text-3xl font-bold text-gray-900 mb-3">
              {t("assessment.completedTitle")}
            </h1>
            <p className="text-gray-500 text-base leading-relaxed mb-8">
              {t("assessment.completedDescription")}
            </p>
            {/* Divider */}
            <div className="border-t border-gray-100 pt-6">
              <div className="flex items-center justify-center gap-2 text-sm text-gray-400">
                <svg className="w-4 h-4 text-[#3B9EC9]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                </svg>
                <span>MBHS Mental Health Screening</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <header className="bg-white border-b border-gray-100 sticky top-0 z-40">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            <Link href={isPractitionerViewer ? practitionerHomeHref : "/"} className="flex items-center gap-2">
              <Image src={mbhsLogo} alt="MBHS" width={40} height={40} className="w-10 h-10 rounded-lg" />
              <span className="text-xl font-bold text-gray-900">MBHS</span>
            </Link>
            <button
              onClick={() => router.replace(pathname, { locale: locale === "en" ? "es" : "en" })}
              className="flex items-center gap-2 px-3 py-1.5 bg-gray-100 hover:bg-gray-200 rounded-full text-sm font-medium text-gray-700 transition cursor-pointer"
            >
              <FlagIcon locale={locale as "en" | "es"} />
              <span>{locale === "en" ? "EN" : "ES"}</span>
            </button>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Back to Dashboard link for practitioners */}
        {isPractitionerViewer && (
          <Link
            href={practitionerHomeHref}
            className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 mb-6 transition w-fit"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
            </svg>
            {t("assessment.backToDashboard")}
          </Link>
        )}
        {/* Top Bar */}
        <div className="flex items-center justify-between mb-6">
          <h1 className="text-2xl font-semibold text-gray-900">
            {t("assessment.yourResults")}
          </h1>
          <button
            onClick={handleDownloadPDF}
            disabled={isDownloading}
            className="flex items-center gap-2 px-6 py-2.5 bg-[#3B9EC9] text-white rounded-full hover:bg-[#2D8AB5] transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
          >
            {isDownloading ? (
              <>
                <svg className="animate-spin w-5 h-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                <span className="text-sm font-medium">{t("assessment.downloading")}</span>
              </>
            ) : (
              <>
                <span className="text-sm font-medium">{t("assessment.downloadReport")}</span>
                <DownloadIcon />
              </>
            )}
          </button>
        </div>

        {/* Report Card */}
        <div ref={reportRef} style={{
          backgroundColor: '#ffffff',
          borderRadius: '16px',
          boxShadow: '0 1px 3px 0 rgba(0, 0, 0, 0.1)',
          border: '1px solid #f3f4f6',
          padding: '32px'
        }}>
          {/* Report Header */}
          <div style={{
            display: 'flex',
            alignItems: 'flex-start',
            justifyContent: 'space-between',
            marginBottom: '24px',
            paddingBottom: '24px',
            borderBottom: '1px solid #f3f4f6'
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
              <Image src={mbhsLogo} alt="MBHS" width={48} height={48} style={{ width: '48px', height: '48px', borderRadius: '8px' }} />
              <div>
                <h1 style={{ fontSize: '24px', fontWeight: 700, color: '#111827', margin: 0 }}>MBHS</h1>
                <p style={{ fontSize: '12px', color: '#9ca3af', margin: 0 }}>Multidimensional Behavioral Health Screen</p>
                <p style={{ fontSize: '14px', color: '#4b5563', marginTop: '4px' }}>{t("practitioner.report.selfScreeningReport")}</p>
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <p style={{ fontSize: '14px', color: '#6b7280', margin: 0 }}>{t("practitioner.report.date")}: {formatDate(reportData.screening_date || reportData.completed_at)}</p>
              <p style={{ fontSize: '14px', fontWeight: 500, color: '#374151', marginTop: '4px' }}>{reportData.client_name}</p>
              <p style={{ fontSize: '12px', color: '#6b7280', margin: 0 }}>{reportData.client_email || "-"}</p>
            </div>
          </div>

          {/* Suicide Risk Classification */}
          <div style={{
            backgroundColor: suicideRisk?.toLowerCase()?.includes("high") || suicideRisk?.toLowerCase()?.includes("moderate") ? '#fef2f2' :
                           suicideRisk?.toLowerCase()?.includes("mild") ? '#fefce8' :
                           suicideRisk?.toLowerCase()?.includes("low") ? '#f0fdf4' : '#f9fafb',
            borderRadius: '12px',
            padding: '24px',
            marginBottom: '32px'
          }}>
            <h2 style={{ fontSize: '16px', fontWeight: 700, color: '#111827', marginBottom: '12px' }}>
              {t("practitioner.report.suicideRiskClassification")}
            </h2>
            {/* Badge — matches ScreeningReport style: h-9 px-4, filled bg-red-100, no border, no dot */}
            <span style={{
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              height: '36px',
              padding: '0 16px',
              backgroundColor: suicideRisk?.toLowerCase()?.includes("high") || suicideRisk?.toLowerCase()?.includes("moderate") ? '#fee2e2' :
                              suicideRisk?.toLowerCase()?.includes("mild") ? '#fef9c3' :
                              suicideRisk?.toLowerCase()?.includes("low") ? '#dcfce7' : '#f3f4f6',
              color: suicideRisk?.toLowerCase()?.includes("high") || suicideRisk?.toLowerCase()?.includes("moderate") ? '#dc2626' :
                     suicideRisk?.toLowerCase()?.includes("mild") ? '#ca8a04' :
                     suicideRisk?.toLowerCase()?.includes("low") ? '#16a34a' : '#4b5563',
              fontSize: '14px',
              fontWeight: 600,
              borderRadius: '9999px',
              marginBottom: '12px'
            }}>
              {t("practitioner.report.suicideRiskLevel")}: {getRiskLabel(suicideRisk)}
            </span>
            <p style={{ fontSize: '14px', color: '#4b5563', lineHeight: 1.6, margin: 0 }}>
              {getSuicideRiskNarrative()}
            </p>
          </div>

          {/* Your Results at a Glance */}
          <div style={{ marginBottom: '32px' }}>
            <h2 style={{ fontSize: '20px', fontWeight: 700, color: '#111827', marginBottom: '12px' }}>
              {t("practitioner.report.resultsGlance")}
            </h2>
            <p style={{ fontSize: '14px', color: '#4b5563', marginBottom: '16px' }}>
              {t("practitioner.report.resultsDescription")}
            </p>
            <div style={{ backgroundColor: '#f9fafb', borderRadius: '12px', padding: '16px' }}>
              <p style={{ fontSize: '14px', color: '#374151', marginBottom: '8px' }}>
                <span style={{ fontWeight: 600 }}>{t("practitioner.report.percentile50")}</span> = {t("practitioner.report.averageRange")}
              </p>
              <p style={{ fontSize: '14px', color: '#374151', margin: 0 }}>
                <span style={{ fontWeight: 600 }}>{t("practitioner.report.percentile66")}</span> = {t("practitioner.report.warrantAttention")}
              </p>
            </div>
          </div>

          {/* Detailed Results by Scale */}
          <div>
            <h2 style={{ fontSize: '20px', fontWeight: 700, color: '#111827', marginBottom: '24px' }}>
              {t("practitioner.report.detailedResults")}
            </h2>

            {scaleResults.length > 0 ? (
              <>
                {/* Scale Legend */}
                <div style={{ display: 'flex', alignItems: 'center', gap: '16px', marginBottom: '16px', fontSize: '14px', color: '#6b7280' }}>
                  <div style={{ width: '180px', minWidth: '180px', flexShrink: 0 }}></div>
                  <div style={{ flex: 1, position: 'relative', height: '36px' }}>
                    <span style={{ position: 'absolute', left: '50%', transform: 'translateX(-50%)', bottom: 0, textAlign: 'center', whiteSpace: 'nowrap', lineHeight: 1.3 }}>
                      {t("practitioner.report.averageScore")}<br />({t("practitioner.report.percentile50")})
                    </span>
                    <span style={{ position: 'absolute', left: '83%', transform: 'translateX(-50%)', bottom: 0, textAlign: 'center', whiteSpace: 'nowrap', lineHeight: 1.3 }}>
                      {t("practitioner.report.clinicalThreshold")}<br />({"\u2265"}66th percentile)
                    </span>
                  </div>
                </div>

                {/* Scale Results */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                  {scaleResults.map((scale, index) => {
                    const getBarColor = () => {
                      if (index < 2) return "#00B0F0";
                      if (index < 6) return "#0070C0";
                      return "#7030A0";
                    };
                    return (
                      <div key={index} style={{ display: 'flex', alignItems: 'center', gap: '16px' }}>
                        <span style={{
                          fontSize: '13px',
                          fontWeight: 600,
                          color: '#000000',
                          width: '180px',
                          minWidth: '180px',
                          flexShrink: 0,
                          lineHeight: 1.3,
                          WebkitTextFillColor: '#000000'
                        }}>
                          {scale.name}
                        </span>
                        <div style={{ flex: 1, position: 'relative' }}>
                          {/* Background track */}
                          <div style={{
                            height: '28px',
                            backgroundColor: '#e5e7eb',
                            borderRadius: '4px',
                            position: 'relative',
                            overflow: 'hidden'
                          }}>
                            {/* Progress bar */}
                            <div style={{
                              height: '100%',
                              backgroundColor: getBarColor(),
                              borderRadius: '4px',
                              width: `${scale.percentage}%`,
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'flex-end',
                              paddingRight: '8px',
                              minWidth: scale.percentage > 0 ? '40px' : '0'
                            }}>
                              <span style={{
                                fontSize: '12px',
                                fontWeight: 600,
                                color: '#ffffff'
                              }}>
                                {scale.percentage}%
                              </span>
                            </div>
                            {/* 50th percentile marker */}
                            <div style={{
                              position: 'absolute',
                              top: 0,
                              bottom: 0,
                              width: '1px',
                              backgroundColor: '#6b7280',
                              left: '50%'
                            }}></div>
                            {/* 66th percentile marker */}
                            <div style={{
                              position: 'absolute',
                              top: 0,
                              bottom: 0,
                              width: '1px',
                              backgroundColor: '#374151',
                              left: '66%'
                            }}></div>
                          </div>
                          {/* Scale labels */}
                          <div style={{ position: 'relative', fontSize: '12px', color: '#374151', marginTop: '4px', height: '16px' }}>
                            <span style={{ position: 'absolute', left: '50%', transform: 'translateX(-50%)', color: '#374151' }}>50</span>
                            <span style={{ position: 'absolute', left: '66%', transform: 'translateX(-50%)', color: '#374151' }}>66</span>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </>
            ) : (
              <div style={{ textAlign: 'center', padding: '32px 0', backgroundColor: '#f9fafb', borderRadius: '12px' }}>
                <p style={{ color: '#6b7280', margin: 0 }}>{t("practitioner.report.noScaleData")}</p>
              </div>
            )}
          </div>

          {/* Important Information */}
          <div data-pdf-section="important-info" style={{ marginTop: '32px' }}>
            <h2 style={{ fontSize: '20px', fontWeight: 700, color: '#111827', marginBottom: '16px' }}>
              {t("individual.results.importantInfo.title")}
            </h2>
            <div style={{ backgroundColor: '#f9fafb', borderRadius: '12px', padding: '20px', border: '1px solid #e5e7eb' }}>
              <ul style={{ margin: 0, paddingLeft: '20px', listStyleType: 'disc', display: 'flex', flexDirection: 'column', gap: '6px' }}>
                <li style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6 }}>{t("individual.results.importantInfo.bullet1")}</li>
                <li style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6 }}>{t("individual.results.importantInfo.bullet2")}</li>
                <li style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6 }}>{t("individual.results.importantInfo.bullet3")}</li>
                <li style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6 }}>{t("individual.results.importantInfo.bullet4")}</li>
              </ul>
            </div>
          </div>

          {/* Thank You Message — only for client/public viewers */}
          {!isPractitionerViewer && (
            <div style={{
              marginTop: '32px',
              padding: '24px',
              backgroundColor: '#f0fdf4',
              borderRadius: '12px',
              textAlign: 'center'
            }}>
              <h3 style={{ fontSize: '18px', fontWeight: 600, color: '#166534', marginBottom: '8px' }}>
                {t("assessment.completedTitle")}
              </h3>
              <p style={{ fontSize: '14px', color: '#166534', margin: 0 }}>
                {t("assessment.completedDescription")}
              </p>
            </div>
          )}
        </div>
      </main>

    </div>
  );
}