"use client";

import { useRef, useState } 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 jsPDF from "jspdf";
import { useDashboardControllerGetScreeningDetailV1 } from "@/api/user/practitioner-dashboard/practitioner-dashboard";
import { usePractitionerScreeningControllerGetReportV1 } from "@/api/user/practitioner-screening/practitioner-screening";
import { computeSuicideRisk } from "@/lib/suicideRiskAlgorithm";

interface ScaleResult {
  name: string;
  key: string;
  percentage: number;
  color: string;
  rawScore?: number | null;
}

// 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'
};

const SCALE_INTERPRETATION_KEYS: Record<string, string> = {
  somatization: "somatizationInterpretation",
  cognitive_issues: "cognitiveIssuesInterpretation",
  demoralization: "demoralizationInterpretation",
  anhedonia: "anhedoniaInterpretation",
  anxiety: "anxietyInterpretation",
  suicidal_ideation: "suicidalIdeationInterpretation",
  activation: "activationInterpretation",
  disconstraint: "disconstraintInterpretation",
  substance_use_problems: "substanceUseInterpretation",
};

export default function DynamicReportPage() {
  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 screeningParamRaw = params.screeningId as string;
  const isUuidParam = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(screeningParamRaw);
  const clientId = Number(params.clientId);
  const screeningId = isUuidParam ? 0 : Number(screeningParamRaw);

  // Numeric ID fetch (Send Now flow)
  const { data: response, isLoading: isLoadingNumeric } = useDashboardControllerGetScreeningDetailV1(
    clientId,
    screeningId,
    { query: { enabled: !isUuidParam && !!(clientId && screeningId) } }
  );

  // UUID fetch (Send Later / in-person flow)
  const { data: uuidResponse, isLoading: isLoadingUuid } = usePractitionerScreeningControllerGetReportV1(
    screeningParamRaw,
    { query: { enabled: isUuidParam } }
  );

  const isLoading = isUuidParam ? isLoadingUuid : isLoadingNumeric;
  const reportData = isUuidParam ? (uuidResponse as any)?.data : (response as any)?.data;

  // Both endpoints now return suicide_risk_category directly (backend MBHS 3.0 algorithm)
  const rawBackendRisk = reportData?.suicide_risk_category || "";

  // Full MBHS 3.0 24-condition suicide risk algorithm (frontend safety net)
  const suicideRisk = computeSuicideRisk({
    itemResponses: (reportData?.item_responses || []) 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: rawBackendRisk,
  });

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

    setIsDownloading(true);
    try {
      const html2canvas = (await import("html2canvas-pro")).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);

      // Build page slices by finding the best break point near each page boundary
      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;
        }

        let bestBreak = -1;
        for (const bp of uniqueBreakPoints) {
          if (bp <= currentY) continue;
          if (bp <= idealEnd) {
            bestBreak = bp;
          } else {
            break;
          }
        }

        if (bestBreak > currentY) {
          pages.push({ startY: currentY, endY: bestBreak });
          currentY = bestBreak;
        } else {
          pages.push({ startY: currentY, endY: Math.min(idealEnd, imgHeightPx) });
          currentY = Math.min(idealEnd, imgHeightPx);
        }
      }

      if (pages.length === 0) {
        pages.push({ startY: 0, endY: imgHeightPx });
      }

      // Create PDF and render each page slice
      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 sliceHeightMm = sliceH * ratio;

        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 sliceData = sliceCanvas.toDataURL("image/png");
        pdf.addImage(sliceData, "PNG", margin, margin, availableWidth, sliceHeightMm, undefined, "FAST");
      }

      // Filename: MBHS-Report-ClientName_YYYYMMDD_HHMMSSmmm.pdf
      const now = new Date();
      const timestamp = `${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")}${String(now.getMilliseconds()).padStart(3, "0")}`;
      const clientName = ((reportData.client as any)?.name || reportData.client_name || "Client").replace(/[^a-zA-Z0-9]/g, "");
      pdf.save(`MBHS-Report-${clientName}_${timestamp}.pdf`);
    } catch (error) {
      console.error("Error generating PDF:", error);
    } finally {
      setIsDownloading(false);
    }
  };

  const getRiskLabel = (risk: string) => {
    if (!risk) return "-";
    const normalizedRisk = risk?.toLowerCase();
    if (normalizedRisk?.includes("at least moderate") || normalizedRisk?.includes("high") || normalizedRisk?.includes("moderate") || normalizedRisk?.includes("medium")) return t("practitioner.common.high");
    if (normalizedRisk?.includes("mild")) return t("practitioner.common.mild");
    if (normalizedRisk?.includes("low")) return t("practitioner.common.low");
    // Return the original value if no match (capitalize first letter)
    return risk.charAt(0).toUpperCase() + risk.slice(1).toLowerCase();
  };

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

  // Map API scale results to display format (handle multiple field name variations)
  const getScaleResults = (): ScaleResult[] => {
    // Try multiple possible field names for scale results
    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,
        key: scaleName,
        percentage: Math.round(parseFloat(scale.percentile || scale.percentage || scale.score || scale.value || '0')),
        color: "bg-cyan-400",
        rawScore: scale.raw_score ?? null,
        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, key, percentage, color, rawScore }) => ({ name, key, percentage, color, rawScore }));
  };

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

  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("practitioner.common.loading")}</p>
        </div>
      </div>
    );
  }

  if (!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("practitioner.report.notFound")}</h2>
          <p className="text-gray-600 mb-4">{t("practitioner.report.notFoundDescription")}</p>
          <button
            onClick={() => router.push('/practitioner')}
            className="px-6 py-2.5 bg-[#3B9EC9] text-white rounded-full hover:bg-[#2D8AB5] transition cursor-pointer"
          >
            {t("practitioner.report.backToDashboard")}
          </button>
        </div>
      </div>
    );
  }

  const scaleResults = getScaleResults();

  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">
            {/* Logo */}
            <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>

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

            {/* Right side */}
            <div className="flex items-center gap-4">
              {/* Language Toggle Button */}
              <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"
              >
                <FlagIcon locale={locale as "en" | "es"} />
                <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">Oliver James</span>
                <svg className="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>
        </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('/practitioner')}
            className="flex items-center gap-2 text-gray-600 hover:text-gray-900 transition cursor-pointer"
          >
            <ArrowLeftIcon />
            <span className="text-sm font-medium">{t("practitioner.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 disabled:cursor-not-allowed"
          >
            {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("practitioner.report.downloading")}</span>
              </>
            ) : (
              <>
                <span className="text-sm font-medium">{t("practitioner.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("practitioner.report.selfScreeningReport")}</p>
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <p style={{ fontSize: '14px', color: '#6b7280', margin: 0 }}>{locale === "en" ? "Date" : "Fecha"}: {formatDate(reportData.screening_date || reportData.completed_at)}</p>
              <p style={{ fontSize: '14px', fontWeight: 500, color: '#374151', marginTop: '4px' }}>{(reportData.client as any)?.name || reportData.client_name}</p>
              <p style={{ fontSize: '12px', color: '#6b7280', margin: 0 }}>{(reportData.client as any)?.email || reportData.client_email || "-"}</p>
            </div>
          </div>

          {/* Your Results at a Glance - Using inline styles for PDF */}
          <div data-pdf-section="results-glance" 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 - Using inline styles for PDF */}
          <div data-pdf-section="detailed-results">
            <h2 style={{ fontSize: '20px', fontWeight: 700, color: '#111827', marginBottom: '24px' }}>
              {t("practitioner.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("practitioner.report.averageScore")}<br />{`(${t("practitioner.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("practitioner.report.clinicalThreshold")}<br />(≥66th percentile)
                    </span>
                  </div>
                </div>

                {/* Scale Results - Using inline styles for PDF compatibility */}
                <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                  {scaleResults.map((scale, index) => {
                    // Color: first 2 light blue, next 4 dark blue, last 3 purple
                    const getBarColor = () => {
                      if (index < 2) return "#00B0F0"; // Light blue/cyan
                      if (index < 6) return "#0070C0"; // Blue
                      return "#7030A0"; // Purple
                    };
                    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' }}>
                          {/* 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>

          {/* Suicide Risk Classification - Using inline styles for PDF */}
          <div data-pdf-section="suicide-risk" style={{
            backgroundColor: suicideRisk?.toLowerCase()?.includes("high") || suicideRisk?.toLowerCase()?.includes("moderate") ? '#fef2f2' :
                             suicideRisk?.toLowerCase()?.includes("mild") ? '#fffbeb' :
                             suicideRisk?.toLowerCase()?.includes("low") ? '#f0fdf4' : '#f9fafb',
            borderRadius: '12px',
            padding: '24px',
            marginTop: '32px',
            marginBottom: '0'
          }}>
            <h2 style={{ fontSize: '16px', fontWeight: 700, color: '#111827', marginBottom: '12px' }}>
              {t("practitioner.report.suicideRiskClassification")}
            </h2>
            <span style={{
              display: 'inline-block',
              padding: '8px 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' : '#6b7280',
              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 }}>
              {(reportData as any)?.suicide_risk_narrative || getSuicideRiskNarrative()}
            </p>
          </div>

          {/* Scale Interpretations */}
          {scaleResults.length > 0 && (
            <div data-pdf-section="interpretations-header" style={{ marginTop: '32px' }}>
              <h2 style={{ fontSize: '20px', fontWeight: 700, color: '#111827', marginBottom: '20px' }}>
                {t("practitioner.report.scaleInterpretations")}
              </h2>
              <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
                {scaleResults.map((scale) => {
                  const isElevated = scale.percentage >= 66;
                  const textKey = SCALE_INTERPRETATION_KEYS[scale.key];
                  return (
                    <div
                      key={scale.key}
                      data-pdf-section={`interpretation-${scale.key}`}
                      style={{
                        borderLeft: isElevated ? '4px solid #3B9EC9' : 'none',
                        paddingLeft: isElevated ? '16px' : '0',
                      }}
                    >
                      <h3 style={{ fontSize: '15px', fontWeight: 700, color: '#111827', margin: '0 0 4px 0' }}>
                        {scale.name} - {isElevated ? t("practitioner.report.elevated") : t("practitioner.report.notElevated")}
                      </h3>
                      {textKey && (
                        <p style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6, margin: 0 }}>
                          {t(`practitioner.report.${textKey}`)}
                        </p>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {/* SSI-Based Clinical Resources — hidden for first release, retain for future use */}
          {false && scaleResults.length > 0 && (
            <div data-pdf-section="ssi-resources" style={{ marginTop: '32px' }}>
              <h2 style={{ fontSize: '20px', fontWeight: 700, color: '#111827', marginBottom: '16px' }}>
                {t("practitioner.report.ssiResources")}
              </h2>
              <div style={{ backgroundColor: '#f9fafb', borderRadius: '12px', padding: '20px' }}>
                {/* Demoralization */}
                <div data-pdf-section="ssi-demoralization" style={{ marginBottom: '20px' }}>
                  <h3 style={{ fontSize: '15px', fontWeight: 700, color: '#111827', marginBottom: '4px' }}>
                    {t("practitioner.report.ssiDemoralizationTitle")}
                  </h3>
                  <p style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6, margin: '0 0 8px 0' }}>
                    {t("practitioner.report.ssiDemoralizationDescription")}
                  </p>
                  <button
                    style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '6px',
                      padding: '6px 14px',
                      fontSize: '13px',
                      fontWeight: 500,
                      color: '#374151',
                      backgroundColor: '#ffffff',
                      border: '1px solid #d1d5db',
                      borderRadius: '8px',
                      cursor: 'pointer',
                    }}
                  >
                    <svg style={{ width: '14px', height: '14px' }} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
                    </svg>
                    {t("practitioner.report.viewSSIResource")}
                  </button>
                </div>
                {/* Anhedonia */}
                <div data-pdf-section="ssi-anhedonia">
                  <h3 style={{ fontSize: '15px', fontWeight: 700, color: '#111827', marginBottom: '4px' }}>
                    {t("practitioner.report.ssiAnhedoniaTitle")}
                  </h3>
                  <p style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6, margin: '0 0 8px 0' }}>
                    {t("practitioner.report.ssiAnhedoniaDescription")}
                  </p>
                  <button
                    style={{
                      display: 'inline-flex',
                      alignItems: 'center',
                      gap: '6px',
                      padding: '6px 14px',
                      fontSize: '13px',
                      fontWeight: 500,
                      color: '#374151',
                      backgroundColor: '#ffffff',
                      border: '1px solid #d1d5db',
                      borderRadius: '8px',
                      cursor: 'pointer',
                    }}
                  >
                    <svg style={{ width: '14px', height: '14px' }} fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                      <path strokeLinecap="round" strokeLinejoin="round" d="M13.5 6H5.25A2.25 2.25 0 003 8.25v10.5A2.25 2.25 0 005.25 21h10.5A2.25 2.25 0 0018 18.75V10.5m-10.5 6L21 3m0 0h-5.25M21 3v5.25" />
                    </svg>
                    {t("practitioner.report.viewSSIResource")}
                  </button>
                </div>
              </div>
            </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("practitioner.report.singleSessionTitle")}
            </h2>
            <p style={{ fontSize: '14px', color: '#4b5563', lineHeight: 1.6 }}>
              {t("practitioner.report.singleSessionDescPart1")}
              <a href="https://www.schleiderlab.org/" target="_blank" rel="noopener noreferrer" style={{ color: '#3B9EC9', textDecoration: 'underline' }}>
                {t("practitioner.report.singleSessionLabLinkText")}
              </a>
              {t("practitioner.report.singleSessionDescPart2")}
              <a href="https://tryprojectyes.org/" target="_blank" rel="noopener noreferrer" style={{ color: '#3B9EC9', textDecoration: 'underline' }}>
                {t("practitioner.report.singleSessionCoursesLinkText")}
              </a>
              {t("practitioner.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("practitioner.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("practitioner.report.noMedicalDiagnosis")}</li>
                <li style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6, marginBottom: '6px', display: 'list-item' }}>{t("practitioner.report.selfReportedResults")}</li>
                <li style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6, marginBottom: '6px', display: 'list-item' }}>{t("practitioner.report.qualifiedProfessional")}</li>
                <li style={{ fontSize: '13px', color: '#4b5563', lineHeight: 1.6, display: 'list-item' }}>{t("practitioner.report.resultsChange")}</li>
              </ul>
            </div>
          </div>

          {/* Footer */}
          <div
            data-pdf-section="footer"
            style={{
              marginTop: '32px',
              paddingTop: '16px',
              borderTop: '1px solid #e5e7eb',
              textAlign: 'center',
            }}
          >
            <p style={{ fontSize: '13px', fontWeight: 600, color: '#374151', margin: 0 }}>
              {t("practitioner.report.mbhsVersion")}
            </p>
            <p style={{ fontSize: '12px', color: '#9ca3af', marginTop: '4px' }}>
              {t("practitioner.report.copyright")}
            </p>
          </div>
        </div>
        </div>
      </main>
    </div>
  );
}