"use client";

import { useRef, useState } from "react";
import Image from "next/image";
import mbhsLogo from "@/public/images/mbhs-logo.png";
import { useRouter, useParams } from "next/navigation";
import { Link } from "@/i18n/navigation";
import { useTranslations, useLocale } from "next-intl";
import { useRouter as useIntlRouter, usePathname } from "@/i18n/navigation";
import {
  usePMScreeningControllerGetReportV1,
} from "@/api/user/practice-manager-screening/practice-manager-screening";
import type { PMItemResponse } from "@/types/therapist-report";
import { computeSuicideRisk } from "@/lib/suicideRiskAlgorithm";

// 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 DynamicReportPage() {
  const router = useRouter();
  const params = useParams();
  const t = useTranslations();
  const locale = useLocale();
  const intlRouter = useIntlRouter();
  const pathname = usePathname();
  const reportRef = useRef<HTMLDivElement>(null);
  const [isDownloading, setIsDownloading] = useState(false);

  const reportId = params.id as string;

  // Fetch report data from API
  const { data: reportResponse, isLoading, error } = usePMScreeningControllerGetReportV1(
    reportId,
    {
      query: {
        enabled: !!reportId,
      },
    }
  );


  const reportData = (reportResponse as any)?.data || null;
  const itemResponses: PMItemResponse[] = Array.isArray(reportData?.item_responses)
    ? (reportData.item_responses as PMItemResponse[])
    : [];

  // PDF download — capture the DOM directly so the PDF always matches what is displayed on screen
  const handleDownloadPDF = async () => {
    if (isDownloading || !reportData || !reportRef.current) return;

    setIsDownloading(true);
    try {
      const html2canvas = (await import("html2canvas-pro")).default;
      const jsPDF = (await import("jspdf")).default;
      const canvasScale = 2;
      const element = reportRef.current;

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

      // A4 dimensions in mm
      const pdfWidth = 210;
      const pdfHeight = 297;
      const margin = 10;
      const availableWidth = pdfWidth - margin * 2;
      const availableHeight = pdfHeight - margin * 2;

      const imgWidthPx = canvas.width;
      const imgHeightPx = canvas.height;
      const ratio = availableWidth / imgWidthPx;
      const pageHeightPx = availableHeight / ratio;

      // Collect section break points from data-pdf-section elements
      const sectionElements = element.querySelectorAll("[data-pdf-section]");
      const elementRect = element.getBoundingClientRect();
      const breakPoints: number[] = [];
      sectionElements.forEach((el) => {
        const rect = el.getBoundingClientRect();
        const yPx = Math.round((rect.top - elementRect.top) * canvasScale);
        if (yPx > 0 && yPx < imgHeightPx) breakPoints.push(yPx);
      });
      const uniqueBreakPoints = [...new Set(breakPoints)].sort((a, b) => a - b);

      // Page-breaking algorithm:
      // - Fill each page to pageHeightPx (avoid blank space at page bottom).
      // - Snap page boundary to the last data-pdf-section break ≤ idealEnd.
      // - Lookahead: if snapping leaves a sparse last page (< 30% fill),
      //   find an earlier break so the remaining content is ≥ 30% of a page.
      const MIN_LAST_PAGE_FILL = 0.3;

      const pages: { startY: number; endY: number }[] = [];
      let currentY = 0;
      while (currentY < imgHeightPx) {
        const idealEnd = currentY + pageHeightPx;
        if (idealEnd >= imgHeightPx) {
          pages.push({ startY: currentY, endY: imgHeightPx });
          break;
        }

        // Find the last break point that fits within this page
        let bestBreak = -1;
        for (const bp of uniqueBreakPoints) {
          if (bp <= currentY) continue;
          if (bp <= idealEnd) bestBreak = bp;
          else break;
        }

        if (bestBreak > currentY) {
          // Lookahead: would the remaining content after this break be too sparse?
          const remaining = imgHeightPx - bestBreak;
          if (remaining > 0 && remaining < pageHeightPx * MIN_LAST_PAGE_FILL) {
            // Pull back the break so the last page gets ≥ MIN_LAST_PAGE_FILL
            const maxEnd = imgHeightPx - pageHeightPx * MIN_LAST_PAGE_FILL;
            let saferBreak = -1;
            for (const bp of uniqueBreakPoints) {
              if (bp <= currentY) continue;
              if (bp <= maxEnd) saferBreak = bp;
              else break;
            }
            if (saferBreak > currentY) {
              pages.push({ startY: currentY, endY: saferBreak });
              currentY = saferBreak;
            } else {
              // No safe break found — hard cut at idealEnd
              pages.push({ startY: currentY, endY: Math.round(idealEnd) });
              currentY = Math.round(idealEnd);
            }
          } else {
            pages.push({ startY: currentY, endY: bestBreak });
            currentY = bestBreak;
          }
        } else {
          // No break point in range — hard cut at idealEnd
          pages.push({ startY: currentY, endY: Math.round(idealEnd) });
          currentY = Math.round(idealEnd);
        }
      }
      if (pages.length === 0) pages.push({ startY: 0, endY: imgHeightPx });

      const pdf = new jsPDF({ orientation: "portrait", unit: "mm", format: "a4", compress: true });
      for (let i = 0; i < pages.length; i++) {
        if (i > 0) pdf.addPage();
        const { startY, endY } = pages[i];
        const sliceH = endY - startY;
        if (sliceH <= 0) continue;
        const sliceCanvas = document.createElement("canvas");
        sliceCanvas.width = imgWidthPx;
        sliceCanvas.height = Math.ceil(sliceH);
        const ctx = sliceCanvas.getContext("2d");
        if (!ctx) continue;
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, sliceCanvas.width, sliceCanvas.height);
        ctx.drawImage(canvas, 0, startY, imgWidthPx, sliceH, 0, 0, imgWidthPx, Math.ceil(sliceH));
        const sliceHeightMm = sliceH * ratio;
        pdf.addImage(sliceCanvas.toDataURL("image/png"), "PNG", margin, margin, availableWidth, sliceHeightMm, undefined, "FAST");
      }

      const clientNameSafe = (reportData?.client?.name || "Client").replace(/[^a-zA-Z0-9]/g, "_");
      const now = new Date();
      const dateStr = `${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}${String(now.getMinutes()).padStart(2,"0")}${String(now.getSeconds()).padStart(2,"0")}`;
      pdf.save(`MBHS-Screening-Report-${clientNameSafe}-${dateStr}.pdf`);
    } catch (err) {
      console.error("Error generating PDF:", err);
    } finally {
      setIsDownloading(false);
    }
  };

  const getRiskLabel = (risk: string) => {
    if (!risk) return "-";
    const normalized = risk?.toLowerCase();
    if (normalized?.includes("at least moderate") || normalized?.includes("high") || normalized?.includes("moderate")) return t("practiceManager.common.high");
    if (normalized?.includes("mild")) return t("practiceManager.common.mild");
    if (normalized?.includes("low")) return t("practiceManager.common.low");
    return risk;
  };

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

  // Use full MBHS 3.0 24-condition algorithm for suicide risk
  // suicide_risk_category now returned directly by the report endpoint
  const getOverallRiskLevel = (): string => {
    return computeSuicideRisk({
      itemResponses: itemResponses as Array<{ item_number?: number; question_order?: number; score?: number; answer_value?: number }>,
      results: (reportData?.results || []) as Array<{ scale_name: string; raw_score?: number; percentile?: number | string; risk_level?: string }>,
      backendRisk: reportData?.suicide_risk_category || "",
    });
  };

  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>
  );

  const ArrowLeftIcon = () => (
    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M10.5 19.5L3 12m0 0l7.5-7.5M3 12h18" />
    </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("practiceManager.common.loading")}</p>
        </div>
      </div>
    );
  }

  if (error || !reportData) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-xl font-semibold text-gray-900 mb-2">{t("practiceManager.report.notFound")}</h2>
          <p className="text-gray-600 mb-4">{t("practiceManager.report.notFoundDescription")}</p>
          <button
            onClick={() => router.push("/practice-manager/dashboard")}
            className="px-6 py-2.5 bg-[#3B9EC9] text-white rounded-full hover:bg-[#2D8AB5] transition"
          >
            {t("practiceManager.report.backToDashboard")}
          </button>
        </div>
      </div>
    );
  }

  const overallRisk = getOverallRiskLevel();
  const clientInfo = reportData.client || {};
  const rawResults: any[] = reportData.results || [];

  // Map and sort scale results for display
  const scaleResults = rawResults
    .map((scale: any) => {
      const key: string = scale.scale_name || scale.name || "unknown";
      return {
        name: SCALE_DISPLAY_NAMES[key] || key,
        key,
        percentage: Math.round(parseFloat(String(scale.percentile || scale.percentage || "0"))),
        rawScore: scale.raw_score ?? null,
        sortOrder: SCALE_ORDER.indexOf(key),
      };
    })
    .sort((a, b) => {
      if (a.sortOrder === -1) return 1;
      if (b.sortOrder === -1) return -1;
      return a.sortOrder - b.sortOrder;
    })
    .map(({ name, key, percentage, rawScore }) => ({ name, key, percentage, rawScore }));

  const formatDate = (dateStr: string) => {
    try {
      const date = new Date(dateStr);
      return date.toLocaleDateString(locale === "es" ? "es-ES" : "en-US", {
        day: "2-digit",
        month: "short",
        year: "numeric",
      });
    } catch {
      return dateStr;
    }
  };

  // Inline colour helpers (used in inline styles — no Tailwind needed)
  const riskBg = (risk: string) => {
    const n = risk?.toLowerCase() || "";
    if (n.includes("high") || n.includes("moderate")) return "#fef2f2";
    if (n.includes("mild")) return "#fffbeb";
    if (n.includes("low")) return "#f0fdf4";
    return "#f9fafb";
  };
  const riskBadgeBg = (risk: string) => {
    const n = risk?.toLowerCase() || "";
    if (n.includes("high") || n.includes("moderate")) return "#FEE2E2";
    if (n.includes("mild")) return "#FEF9C3";
    if (n.includes("low")) return "#DCFCE7";
    return "#F3F4F6";
  };
  const riskBadgeColor = (risk: string) => {
    const n = risk?.toLowerCase() || "";
    if (n.includes("high") || n.includes("moderate")) return "#DC2626";
    if (n.includes("mild")) return "#CA8A04";
    if (n.includes("low")) return "#16A34A";
    return "#6b7280";
  };

  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">
            <div 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>
            </div>

            <nav className="hidden md:flex items-center gap-8">
              <Link href="/practice-manager/dashboard" className="text-sm font-medium text-gray-600 hover:text-gray-900">
                {t("practiceManager.nav.dashboard")}
              </Link>
              <Link href="/practice-manager/patients" className="text-sm font-medium text-gray-600 hover:text-gray-900">
                {t("practiceManager.nav.clients")}
              </Link>
              <Link href="/practice-manager/subscription" className="text-sm font-medium text-gray-600 hover:text-gray-900">
                {t("practiceManager.nav.subscription")}
              </Link>
            </nav>

            <div className="flex items-center gap-4">
              <button
                onClick={() => intlRouter.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"
              >
                <span className="text-base">{locale === "en" ? "\u{1F1FA}\u{1F1F8}" : "\u{1F1EA}\u{1F1F8}"}</span>
                <span>{locale === "en" ? "EN" : "ES"}</span>
              </button>
              <button className="relative p-2 text-gray-400 hover:text-gray-600">
                <svg className="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0" />
                </svg>
                <span className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
              </button>
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center">
                  <svg className="w-5 h-5 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>
                <span className="text-sm font-medium text-gray-700">Practice Manager</span>
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Top Bar */}
        <div className="flex items-center justify-between mb-6">
          <button
            onClick={() => router.push("/practice-manager/dashboard")}
            className="flex items-center gap-2 text-gray-600 hover:text-gray-900 transition"
          >
            <ArrowLeftIcon />
            <span className="text-sm font-medium">{t("practiceManager.report.backToDashboard")}</span>
          </button>
          <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"
          >
            {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("practiceManager.report.downloading")}</span>
              </>
            ) : (
              <>
                <span className="text-sm font-medium">{t("practiceManager.report.downloadPDF")}</span>
                <DownloadIcon />
              </>
            )}
          </button>
        </div>

        {/* Report Card — Using inline styles for PDF compatibility */}
        <div style={{ borderRadius: '12px', border: '1px solid #e5e7eb' }}>
        <div ref={reportRef} style={{ backgroundColor: '#ffffff', borderRadius: '12px', padding: '32px' }}>

          {/* Report Header */}
          <div data-pdf-section="header" 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("practiceManager.report.selfScreeningReport")}</p>
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <p style={{ fontSize: '14px', color: '#6b7280', margin: 0 }}>
                {locale === "en" ? "Date" : "Fecha"}: {formatDate(reportData.completed_at || reportData.created_at)}
              </p>
              <p style={{ fontSize: '14px', fontWeight: 500, color: '#374151', marginTop: '4px' }}>{clientInfo.name}</p>
              <p style={{ fontSize: '12px', color: '#6b7280', margin: 0 }}>{clientInfo.email}</p>
              {clientInfo.age && (
                <p style={{ fontSize: '12px', color: '#6b7280', marginTop: '4px' }}>
                  {clientInfo.age} {t("practiceManager.common.years")}
                  {clientInfo.gender ? ` | ${clientInfo.gender}` : ""}
                </p>
              )}
            </div>
          </div>

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

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

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

                {/* Scale Rows */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                  {scaleResults.map((scale, index) => {
                    const barColor = index < 2 ? "#00B0F0" : index < 6 ? "#0070C0" : "#7030A0";
                    return (
                      <div key={index} data-pdf-section={`scale-${scale.key}`} 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' }}>
                          {/* Bar track */}
                          <div style={{
                            height: '28px',
                            backgroundColor: '#e5e7eb',
                            borderRadius: '4px',
                            position: 'relative',
                            overflow: 'hidden',
                          }}>
                            {/* Progress */}
                            <div style={{
                              height: '100%',
                              backgroundColor: barColor,
                              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 }}>No scale data available for this screening.</p>
              </div>
            )}
          </div>

          {/* Suicide Risk Classification */}
          <div data-pdf-section="suicide-risk" style={{
            backgroundColor: riskBg(overallRisk),
            borderRadius: '12px',
            padding: '24px',
            marginTop: '32px',
            marginBottom: '0',
          }}>
            <h2 style={{ fontSize: '16px', fontWeight: 700, color: '#111827', marginBottom: '12px' }}>
              {t("practiceManager.report.suicideRiskClassification")}
            </h2>
            <span style={{
              display: 'inline-block',
              padding: '8px 16px',
              backgroundColor: riskBadgeBg(overallRisk),
              color: riskBadgeColor(overallRisk),
              fontSize: '14px',
              fontWeight: 600,
              borderRadius: '9999px',
              marginBottom: '12px',
            }}>
              {t("practiceManager.report.suicideRiskCategory")}: {getRiskLabel(overallRisk)}
            </span>
            <p style={{ fontSize: '14px', color: '#4b5563', lineHeight: 1.6, margin: 0 }}>
              {(reportData as any)?.suicide_risk_narrative || getSuicideRiskNarrative()}
            </p>
          </div>

          {/* Self-Directed Client Resources */}
          <div data-pdf-section="single-session" style={{ marginTop: '32px', backgroundColor: '#f9fafb', borderRadius: '12px', padding: '20px' }}>
            <h2 style={{ fontSize: '18px', fontWeight: 700, color: '#111827', marginBottom: '12px' }}>
              {t("practiceManager.report.singleSessionTitle")}
            </h2>
            <p style={{ fontSize: '14px', color: '#4b5563', lineHeight: 1.6 }}>
              {t("practiceManager.report.singleSessionDescPart1")}
              <a href="https://www.schleiderlab.org/" target="_blank" rel="noopener noreferrer" style={{ color: '#3B9EC9', textDecoration: 'underline' }}>
                {t("practiceManager.report.singleSessionLabLinkText")}
              </a>
              {t("practiceManager.report.singleSessionDescPart2")}
              <a href="https://tryprojectyes.org/" target="_blank" rel="noopener noreferrer" style={{ color: '#3B9EC9', textDecoration: 'underline' }}>
                {t("practiceManager.report.singleSessionCoursesLinkText")}
              </a>
              {t("practiceManager.report.singleSessionDescPart3")}
            </p>
          </div>

          {/* Important Information */}
          <div data-pdf-section="important-info" style={{ marginTop: '32px' }}>
            <h2 style={{ fontSize: '20px', fontWeight: 700, color: '#111827', marginBottom: '16px' }}>
              {t("practiceManager.report.importantInformation")}
            </h2>
            <div style={{ backgroundColor: '#f9fafb', borderRadius: '12px', padding: '20px', border: '1px solid #e5e7eb' }}>
              <ul style={{ margin: 0, paddingLeft: '20px', listStyleType: 'disc' }}>
                <li style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6, marginBottom: '6px', display: 'list-item' }}>{t("practiceManager.report.noMedicalDiagnosis")}</li>
                <li style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6, marginBottom: '6px', display: 'list-item' }}>{t("practiceManager.report.selfReportedResults")}</li>
                <li style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6, marginBottom: '6px', display: 'list-item' }}>{t("practiceManager.report.qualifiedProfessional")}</li>
                <li style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6, display: 'list-item' }}>{t("practiceManager.report.resultsChange")}</li>
              </ul>
            </div>
          </div>

          {/* Footer */}
          <div style={{
            marginTop: '32px',
            paddingTop: '16px',
            borderTop: '1px solid #e5e7eb',
            textAlign: 'center',
          }}>
            <p style={{ fontSize: '12px', color: '#9ca3af', margin: 0 }}>
              MBHS — Multidimensional Behavioral Health Screen
            </p>
          </div>

        </div>
        </div>
      </main>
    </div>
  );
}
