"use client";

import { useState, useRef, useEffect } from "react";
import { useRouter } from "@/i18n/navigation";
import { useTranslations, useLocale } from "next-intl";
import { useGetResults, useGetAnswers, useGetQuestions } from "@/api/user/individual-screening/individual-screening";
import { useProfile } from "@/api/user/user-profile/user-profile";
import { generatePDFFromElement } from "@/lib/generateScreeningPDF";
import { computeSuicideRisk } from "@/lib/suicideRiskAlgorithm";

// Base64 encoded MBHS logo for PDF generation compatibility
const MBHS_LOGO_BASE64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAYAAADimHc4AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAACxLAAAsSwGlPZapAAAAB3RJTUUH6gEBBRIclOky5gAABktJREFUeNrtnUtsVFUYx3/fuWce7fQhoVIiGCEGpEUQRazF+IzBx0IXPhO3xpU7X2DiSrTExJULNT4WLoyJiajRaDQao4bS+EJBWo0iihR8DNaWTtuZzv1cDK0ClRZl5tw79/wmM4uZOZn/Pf9773e+75y5VzgBqx/t46tNv3DulvYmFVYpdAHrgA5gCdAKGJJNCOSBvcBOhW0CvRDugfQ4DLN745X/2lhmenP1Y31MFJWUJafIBQo3A1cDZwHZI+3k39onEP3H809gD/A26FbVcJexqWJp+A++fXjDcQ2DY99Y2dNLUC6JWrtMkXuAjcAGoB1IU9njfecfzVR/GKABOAPoBlkvIhkNdW/v3Zcdfq31Wn5/77njGk7TsaUPIBD0CpBNwKVUOt3z3zkMvK7oI00NTbtHCiMMbOqe/nD6COjs6UOUQITrQbYA3cxwhHhOmjTQKcjSYrG4u3vR2oOFddeSf/954EgA7XxsG22vXASGq4DNwHmuVdcZAXCdGNm8ffCLjoassOzhTyofdPb0ISIUOvYvB3kEWO9abZ0iwNkiNIah+dgGjB265HyMCIhKM8hdwOWuVdY5AXATcFNZCZZn12I0SBFW9vrb8AG3FpwG3GnQ5U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FTkSuQmCC";

interface ScaleResult {
  scale_name: string;
  percentile: number;
  risk_level: string;
  raw_score?: number;
}

interface ScreeningReportProps {
  screeningId: string;
  isPaid?: boolean;
  isModal?: boolean;
  onClose?: () => void;
  autoDownload?: boolean;
}

// Map backend scale names (snake_case) to frontend translation keys (camelCase)
const scaleNameMap: Record<string, string> = {
  somatization: "scales.somatization",
  cognitive_issues: "scales.cognitiveIssues",
  demoralization: "scales.demoralization",
  anhedonia: "scales.anhedonia",
  anxiety: "scales.anxiety",
  suicidal_ideation: "scales.suicidalIdeation",
  activation: "scales.activation",
  disconstraint: "scales.disconstraint",
  substance_use_problems: "scales.substanceUseProblems",
};

// Map backend scale names to interpretation key prefix (camelCase without "scales." prefix)
const interpretationKeyMap: Record<string, string> = {
  somatization: "somatization",
  cognitive_issues: "cognitiveIssues",
  demoralization: "demoralization",
  anhedonia: "anhedonia",
  anxiety: "anxiety",
  suicidal_ideation: "suicidalIdeation",
  activation: "activation",
  disconstraint: "disconstraint",
  substance_use_problems: "substanceUseProblems",
};

// Scale groups for narrative organization
const SCALE_GROUPS = [
  { key: "somaticCognitive", scales: ["somatization", "cognitive_issues"] },
  { key: "internalizing", scales: ["demoralization", "anhedonia", "anxiety", "suicidal_ideation"] },
  { key: "externalizing", scales: ["activation", "disconstraint", "substance_use_problems"] },
];

export default function ScreeningReport({ screeningId, isPaid, isModal, onClose, autoDownload }: ScreeningReportProps) {
  const router = useRouter();
  const t = useTranslations("individual");
  const locale = useLocale();
  const [isDownloading, setIsDownloading] = useState(false);
  const reportRef = useRef<HTMLDivElement>(null);
  const hasAutoDownloaded = useRef(false);

  // Fetch profile for PDF filename
  const { data: profileData } = useProfile();
  const userFullName = (profileData?.data?.user as any)?.name || "";

  // Fetch results from backend
  const { data: resultsData, isLoading, error } = useGetResults(screeningId);

  // Fetch answers + questions as fallback for Q29 detection (only for self-paid screenings;
  // therapist/PM-assigned screenings (isPaid=false) gate these endpoints behind a payment check)
  const { data: answersData } = useGetAnswers(screeningId, {
    query: { enabled: !!screeningId && !isLoading && isPaid !== false },
  });
  const { data: questionsData } = useGetQuestions(screeningId, {
    query: { enabled: !!screeningId && !isLoading && isPaid !== false },
  });

  const screeningData = (resultsData as any)?.data?.screening;
  const results: ScaleResult[] = (screeningData?.results || []) as ScaleResult[];
  const completedAt = screeningData?.completed_at || screeningData?.started_at || new Date().toISOString();
  const isTherapistInvited: boolean = screeningData?.is_therapist_invited ?? false;

  // Format date
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleDateString(locale === "es" ? "es-ES" : "en-GB", {
      day: "numeric",
      month: "short",
      year: "numeric",
    });
  };

  const handleBackToDashboard = () => {
    router.push("/individual");
  };

  const handleDownloadPDF = async () => {
    if (isDownloading || !reportRef.current) return;
    setIsDownloading(true);
    try {
      await generatePDFFromElement(reportRef.current, screeningId, userFullName);
    } catch (error) {
      console.error("Failed to download PDF:", error);
    } finally {
      setIsDownloading(false);
    }
  };

  // Auto-trigger download when opened via download button
  useEffect(() => {
    if (!autoDownload || isLoading || hasAutoDownloaded.current || !reportRef.current) return;
    hasAutoDownloaded.current = true;
    handleDownloadPDF().then(() => onClose?.());
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [autoDownload, isLoading]);

  // Use API-provided suicide risk classification
  const backendRisk: string = screeningData?.suicide_risk_category ||
    results.find((r) => r.scale_name === "suicidal_ideation")?.risk_level || "";

  // Build item responses array — primary source from API, fallback via answers+questions
  const itemResponsesArr: any[] = (
    (resultsData as any)?.data?.item_responses ||
    screeningData?.item_responses ||
    []
  ) as any[];

  const questions: any[] = (
    (questionsData as any)?.data?.questions ||
    (questionsData as any)?.data?.data?.questions ||
    (Array.isArray((questionsData as any)?.data) ? (questionsData as any)?.data : null) ||
    (questionsData as any)?.questions ||
    []
  ) as any[];
  const answers: any[] = (
    (answersData as any)?.data?.answers ||
    (answersData as any)?.data?.data?.answers ||
    (Array.isArray((answersData as any)?.data) ? (answersData as any)?.data : null) ||
    (answersData as any)?.answers ||
    []
  ) as any[];

  // Build effective item responses for algorithm — add Q29 and Q25 from answers if not in item_responses
  // Support both old field names (item_number/score) and new field names (question_order/answer_value)
  const effectiveItemResponses = [...itemResponsesArr] as Array<{
    item_number?: number; question_order?: number; score?: number; answer_value?: number;
  }>;
  if (!effectiveItemResponses.find(i => (i.item_number ?? i.question_order) === 29) && questions.length === 29) {
    // Q29: count-type question (last question, index 28)
    const q29Question = questions.find((q: any) => q.response_type === "count") || questions[28];
    const q29Id = q29Question?.uuid || q29Question?.id;
    const q29Answer = q29Id ? answers.find((a: any) => a.question_uuid === q29Id || a.uuid === q29Id) : null;
    if (q29Answer) effectiveItemResponses.push({ item_number: 29, score: Number(q29Answer.answer || 0) });
  }
  if (!effectiveItemResponses.find(i => (i.item_number ?? i.question_order) === 25) && questions.length === 29) {
    // Q25: positional (index 24 of 29 questions)
    const q25Question = questions[24];
    const q25Id = q25Question?.uuid || q25Question?.id;
    const q25Answer = q25Id ? answers.find((a: any) => a.question_uuid === q25Id || a.uuid === q25Id) : null;
    if (q25Answer) effectiveItemResponses.push({ item_number: 25, score: Number(q25Answer.answer || 0) });
  }

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

  const getRiskInfo = () => {
    const normalized = suicideRisk.toLowerCase();
    if (normalized.includes("at least moderate") || normalized.includes("high") || normalized.includes("moderate")) return { level: t("results.riskHigh"), textColor: "text-red-600", bgColor: "bg-red-50", badgeColor: "bg-red-100 text-red-600" };
    if (normalized.includes("mild")) return { level: t("results.riskMild"), textColor: "text-amber-700", bgColor: "bg-yellow-50", badgeColor: "bg-yellow-100 text-yellow-600" };
    if (normalized.includes("low")) return { level: t("results.riskLow"), textColor: "text-green-600", bgColor: "bg-green-50", badgeColor: "bg-green-100 text-green-600" };
    return { level: t("results.riskLow"), textColor: "text-green-600", bgColor: "bg-green-50", badgeColor: "bg-green-100 text-green-600" };
  };

  const riskInfo = getRiskInfo();

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

  // Loading state
  if (isLoading) {
    const loadingContent = (
      <div className="p-8 text-center">
        <div className="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-[#3B9EC9]"></div>
        <p className="mt-4 text-gray-600">{t("loadingResults")}</p>
      </div>
    );
    if (isModal) return loadingContent;
    return (
      <main className="pt-20 pb-8">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100">
            {loadingContent}
          </div>
        </div>
      </main>
    );
  }

  // Error state
  if (error || results.length === 0) {
    const errorContent = (
      <div className="p-8 text-center">
        <div className="text-[#D12E34] mb-4">
          <svg className="w-12 h-12 mx-auto" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
        </div>
        <h2 className="text-xl font-semibold text-gray-900 mb-2">{t("resultsNotAvailable")}</h2>
        <p className="text-gray-600 mb-6">{t("unableToLoadResults")}</p>
        <button
          onClick={() => isModal && onClose ? onClose() : router.push("/individual")}
          className="px-6 py-3 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/90 transition cursor-pointer"
        >
          {isModal ? t("close") : t("backToDashboard")}
        </button>
      </div>
    );
    if (isModal) return errorContent;
    return (
      <main className="pt-20 pb-8">
        <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="bg-white rounded-2xl shadow-sm border border-gray-100">
            {errorContent}
          </div>
        </div>
      </main>
    );
  }

  const reportContent = (
          <div
            ref={reportRef}
            className={isModal ? "bg-white" : "bg-white p-4 sm:p-8 w-full max-w-[800px] mx-auto"}
          >
            {/* Report Header */}
            <div data-pdf-section="header" className="flex items-start justify-between mb-6">
              <div className="flex items-center gap-3">
                <img
                  src={MBHS_LOGO_BASE64}
                  alt="MBHS"
                  width={48}
                  height={48}
                  className="rounded-lg"
                />
                <div>
                  <h1 className="text-2xl font-bold text-gray-900">MBHS</h1>
                  <p className="text-xs text-gray-500">
                    Multidimensional Behavioral Health Screen
                  </p>
                </div>
              </div>
              <p className="text-sm text-gray-600">{t("results.date")} {formatDate(completedAt)}</p>
            </div>

            {userFullName && (
              <p className="text-sm font-medium text-gray-700 mb-2">{userFullName}</p>
            )}

            <p className="text-sm text-gray-600 mb-6">
              {isTherapistInvited ? t("results.reportTitleTherapistInvited") : t("results.reportTitle")}
            </p>

            {isTherapistInvited && (
              <div className="mb-6 px-4 py-3 bg-sky-50 border border-[#3B9EC9] rounded-lg text-sm text-[#3B9EC9] font-medium">
                {t("results.therapistInvitedBanner")}
              </div>
            )}

            <div className="mb-8"></div>

            {/* Your Results at a Glance */}
            <div data-pdf-section="results-glance" className="mb-8">
              <h2 className="text-xl font-semibold text-gray-900 mb-3">
                {t("results.resultsGlance")}
              </h2>
              <p className="text-sm text-gray-600 mb-4">
                {t("results.resultsDescription")}
              </p>
              <div className="bg-slate-50 rounded-xl p-4">
                <p className="text-sm text-gray-600 mb-1">
                  <span className="font-semibold text-slate-700">{t("results.percentile50")}</span> = {t("results.averageRange")}
                </p>
                <p className="text-sm text-gray-600">
                  <span className="font-semibold text-slate-700">{t("results.percentile66")}</span>{" "}
                  = {t("results.warrantAttention")}
                </p>
              </div>
            </div>

            {/* Detailed Results by Scale */}
            <div data-pdf-section="detailed-results">
              <h2 className="text-xl font-semibold text-gray-900 mb-4">
                {t("results.detailedResults")}
              </h2>
              <div className="bg-gray-50 rounded-xl p-6">
                {/* Scale Headers */}
                <div className="flex items-center mb-6">
                  <div className="w-40"></div>
                  <div className="flex-1 relative text-gray-500" style={{ height: "36px", fontSize: "12px" }}>
                    <span
                      className="absolute text-center leading-tight"
                      style={{ left: "50%", transform: "translateX(-50%)", bottom: 0, whiteSpace: "nowrap" }}
                    >
                      {t("results.averageScore")}
                      <br />
                      ({t("results.percentile50")})
                    </span>
                    <span
                      className="absolute text-center leading-tight"
                      style={{ left: "83%", transform: "translateX(-50%)", bottom: 0, whiteSpace: "nowrap" }}
                    >
                      {t("results.clinicalThreshold")}
                      <br />
                      ({t("results.percentile66")})
                    </span>
                  </div>
                </div>

                {/* Scale Bars */}
                <div className="space-y-4">
                  {results.map((result, index) => {
                    // Color based on row position: first 2 light blue, middle 4 blue, last 3 purple
                    const getBarColor = () => {
                      if (index < 2) return "bg-[#00B0F0]"; // Light blue/cyan (somatization, cognitive_issues)
                      if (index < 6) return "bg-[#0070C0]"; // Blue (demoralization, anhedonia, anxiety, suicidal_ideation)
                      return "bg-[#7030A0]"; // Purple (activation, disconstraint, substance_use_problems)
                    };

                    // Get translated scale name
                    const translationKey = scaleNameMap[result.scale_name] || result.scale_name;
                    const scaleName = t(translationKey);

                    return (
                      <div key={result.scale_name} data-pdf-section={`scale-${result.scale_name}`} className="flex items-center">
                        <div className="w-40 text-sm font-medium text-gray-700 pr-4">
                          {scaleName}
                        </div>
                        <div className="flex-1 relative">
                          {/* Background bar */}
                          <div className="h-7 bg-gray-200 rounded-sm relative overflow-hidden">
                            {/* Filled bar */}
                            <div
                              className={`absolute left-0 top-0 h-full rounded-sm flex items-center justify-end pr-2 ${getBarColor()}`}
                              style={{ width: `${result.percentile}%` }}
                            >
                              <span className="text-xs font-semibold text-white">
                                {Math.round(result.percentile)}%
                              </span>
                            </div>
                            {/* 50th percentile marker */}
                            <div
                              className="absolute top-0 bottom-0 w-px bg-gray-500"
                              style={{ left: "50%" }}
                            />
                            {/* 66th percentile marker */}
                            <div
                              className="absolute top-0 bottom-0 w-px bg-gray-700"
                              style={{ left: "66%" }}
                            />
                          </div>
                          {/* Scale labels */}
                          <div className="relative text-xs text-gray-400 mt-1 h-4">
                            <span className="absolute" style={{ left: "50%", transform: "translateX(-50%)" }}>50</span>
                            <span className="absolute" style={{ left: "66%", transform: "translateX(-50%)" }}>66</span>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>

            {/* Suicide Risk Classification */}
            <div data-pdf-section="suicide-risk" className={`rounded-xl p-6 mt-8 ${riskInfo.bgColor}`}>
              <h2 className="text-sm font-bold text-gray-900 uppercase tracking-wide mb-3">
                {t("results.suicideRiskTitle")}
              </h2>
              <span className={`inline-flex items-center justify-center h-9 px-4 text-sm font-semibold ${riskInfo.badgeColor} rounded-full mb-3`}>
                {t("results.riskCategory")} {riskInfo.level}
              </span>
              <p className="text-sm text-gray-700">
                {getSuicideRiskNarrative()}
              </p>
            </div>

            {/* Scale Interpretations */}
            <div data-pdf-section="interpretations-header" className="mt-8">
              <h2 className="text-xl font-semibold text-gray-900 mb-4">
                {t("results.interpretationsTitle")}
              </h2>
              {SCALE_GROUPS.map((group) => {
                // Find matching results for this group's scales
                const groupResults = group.scales
                  .map((scaleName) => results.find((r) => r.scale_name === scaleName))
                  .filter(Boolean) as ScaleResult[];

                if (groupResults.length === 0) return null;

                return (
                  <div key={group.key} className="mb-6">
                    <h3 className="text-base font-semibold text-gray-800 mb-3 border-b border-gray-200 pb-1">
                      {t(`results.scaleGroups.${group.key}`)}
                    </h3>
                    <div className="space-y-5">
                      {groupResults.map((result) => {
                        const translationKey = scaleNameMap[result.scale_name] || result.scale_name;
                        const scaleName = t(translationKey);
                        const interpKey = interpretationKeyMap[result.scale_name] || result.scale_name;
                        const isElevated = result.percentile >= 66;

                        return (
                          <div
                            key={result.scale_name}
                            data-pdf-section={`interpretation-${result.scale_name}`}
                            className={isElevated ? "border-l-4 border-[#3B9EC9] pl-4" : "pl-4"}
                          >
                            <h4 className="text-sm font-bold text-gray-900 mb-1">
                              {scaleName} - {isElevated ? t("results.elevated") : t("results.notElevated")}
                            </h4>
                            <p className="text-sm text-gray-600 leading-relaxed mb-1">
                              {t(`results.interpretations.${interpKey}Description`)}
                            </p>
                            <p className={`text-sm leading-relaxed ${isElevated ? "text-gray-800 font-medium" : "text-gray-600"}`}>
                              {isElevated
                                ? t(`results.interpretations.${interpKey}`)
                                : t(`results.interpretations.${interpKey}NotElevated`)}
                            </p>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Recommended Next Steps — shown only when suicide risk is elevated (not Low) */}
            {!suicideRisk.toLowerCase().includes("low") && (
            <div data-pdf-section="next-steps" className="mt-8 bg-sky-50 border-2 border-[#3B9EC9] rounded-xl p-6">
              <h2 className="text-lg font-bold text-gray-900 mb-3">
                {t("results.nextSteps.title")}
              </h2>
              <p className="text-sm text-gray-600 mb-4">
                {t("results.nextSteps.intro")}
              </p>
              <ul className="space-y-2">
                <li className="flex items-start gap-2 text-sm text-gray-700">
                  <span className="mt-1.5 w-1.5 h-1.5 bg-gray-500 rounded-full flex-shrink-0"></span>
                  {t("results.nextSteps.bullet1")}
                </li>
                <li className="flex items-start gap-2 text-sm text-gray-700">
                  <span className="mt-1.5 w-1.5 h-1.5 bg-gray-500 rounded-full flex-shrink-0"></span>
                  {t("results.nextSteps.bullet2")}
                </li>
                <li className="flex items-start gap-2 text-sm text-gray-700">
                  <span className="mt-1.5 w-1.5 h-1.5 bg-gray-500 rounded-full flex-shrink-0"></span>
                  {t("results.nextSteps.bullet3")}
                </li>
              </ul>
            </div>
            )}

            {/* Single-Session Support Option — shown for self-screening users only */}
            {!isTherapistInvited && (
            <div data-pdf-section="single-session" className="mt-8 bg-gray-50 rounded-xl p-6">
              <h2 className="text-lg font-bold text-gray-900 mb-3">
                {t("results.singleSession.title")}
              </h2>
              <p className="text-sm text-gray-600 mb-4">
                {t("results.singleSession.description")}
              </p>
              <a
                href="https://www.tryprojectyes.org"
                target="_blank"
                rel="noopener noreferrer"
                data-html2canvas-ignore="true"
                className="inline-block px-6 py-2.5 text-sm font-medium text-[#3B9EC9] border-2 border-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/5 transition cursor-pointer"
              >
                {t("results.singleSession.consultNow")}
              </a>
            </div>
            )}

            {/* Important Information */}
            <div data-pdf-section="important-info" className="mt-8">
              <h2 className="text-lg font-bold text-gray-900 mb-3">{t("results.importantInfo.title")}</h2>
              <div className="bg-gray-50 rounded-xl p-4 border border-gray-200">
                <ul className="space-y-2">
                  <li className="flex items-start gap-2 text-sm text-gray-600">
                    <span className="mt-1.5 w-1.5 h-1.5 bg-gray-400 rounded-full flex-shrink-0"></span>
                    {t("results.importantInfo.bullet1")}
                  </li>
                  <li className="flex items-start gap-2 text-sm text-gray-600">
                    <span className="mt-1.5 w-1.5 h-1.5 bg-gray-400 rounded-full flex-shrink-0"></span>
                    {t("results.importantInfo.bullet2")}
                  </li>
                  <li className="flex items-start gap-2 text-sm text-gray-600">
                    <span className="mt-1.5 w-1.5 h-1.5 bg-gray-400 rounded-full flex-shrink-0"></span>
                    {t("results.importantInfo.bullet3")}
                  </li>
                  <li className="flex items-start gap-2 text-sm text-gray-600">
                    <span className="mt-1.5 w-1.5 h-1.5 bg-gray-400 rounded-full flex-shrink-0"></span>
                    {t("results.importantInfo.bullet4")}
                  </li>
                </ul>
              </div>
            </div>

            {/* Footer */}
            <div data-pdf-section="footer" className="mt-10 pt-6 border-t border-gray-200 text-center">
              <p className="text-sm font-medium text-gray-700">
                {t("results.footer.version")}
              </p>
              <p className="text-xs text-gray-500 mt-1">
                {t("results.footer.copyright")}
              </p>
            </div>
          </div>
  );

  if (isModal) {
    return (
      <div>
        {/* Download button in modal */}
        <div className="flex justify-end mb-4">
          <button
            onClick={handleDownloadPDF}
            disabled={isDownloading}
            className="flex items-center gap-2 px-5 py-2.5 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/90 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
          >
            {isDownloading ? (
              <>
                <svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <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" />
                </svg>
                {t("downloading")}
              </>
            ) : (
              <>
                {t("results.downloadPDF")}
                <svg className="w-4 h-4" 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>
        {reportContent}
      </div>
    );
  }

  return (
    <main className="pt-20 pb-8">
      <div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Top Navigation */}
        <div className="flex items-center justify-between mb-6">
          <button
            onClick={handleBackToDashboard}
            className="flex items-center gap-2 text-sm text-gray-600 hover:text-gray-900 transition cursor-pointer"
          >
            <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("results.backToDashboard")}
          </button>
          <button
            onClick={handleDownloadPDF}
            disabled={isDownloading}
            className="flex items-center gap-2 px-5 py-2.5 text-sm font-medium text-white bg-[#3B9EC9] rounded-full hover:bg-[#3B9EC9]/90 transition disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
          >
            {isDownloading ? (
              <>
                <svg className="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
                  <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" />
                </svg>
                {t("downloading")}
              </>
            ) : (
              <>
                {t("results.downloadPDF")}
                <svg className="w-4 h-4" 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>
        {reportContent}
      </div>
    </main>
  );
}
