/* SER-OS — Service Summary PDF Viewer + Thank You Screen
   ──────────────────────────────────────────────────────
   Two exports:
     ServiceSummaryPdfScreen  — Full-screen PDF preview + action panel
     ThankYouScreen            — Post-signing confirmation + next steps
   ────────────────────────────────────────────────────── */

/* ── Date helpers (local) ─────────────────────────────── */
function pdfDateMed(iso) {
  if (!iso) return "—";
  try { return new Date(iso).toLocaleDateString("en-SG", { day: "numeric", month: "short", year: "numeric" }); }
  catch { return iso; }
}
function pdfDateLong(iso) {
  if (!iso) return "—";
  try { return new Date(iso).toLocaleDateString("en-SG", { weekday: "long", day: "numeric", month: "long", year: "numeric" }); }
  catch { return iso; }
}
function pdfTime(iso) {
  if (!iso) return "—";
  try { return new Date(iso).toLocaleTimeString("en-SG", { hour: "2-digit", minute: "2-digit" }); }
  catch { return iso; }
}

/* ── PDF sub-components ──────────────────────────────── */

function PdfSection({ title, children, first }) {
  return (
    <div className={first ? "pdf-section pdf-section-first" : "pdf-section"} style={{
      borderTop: first ? "none" : "1px solid #EAE6DF",
      paddingTop: first ? 0 : 30,
      marginTop: first ? 0 : 30,
    }}>
      {title && (
        <div className="pdf-section-title" style={{
          fontSize: 13, fontWeight: 600, color: "#1F3A60",
          letterSpacing: "-0.2px",
          marginBottom: 22,
          breakAfter: "avoid", pageBreakAfter: "avoid",
        }}>
          {title}
        </div>
      )}
      {children}
    </div>
  );
}

function PdfField({ label, value, span2 }) {
  const isEmpty = !value || value === "—";
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 5, gridColumn: span2 ? "span 2" : undefined }}>
      <span style={{ fontSize: 11, color: "#9CA8B8", fontWeight: 500, letterSpacing: "-0.05px", lineHeight: "15px" }}>
        {label}
      </span>
      <span style={{ fontSize: 13, color: isEmpty ? "#C8D0DA" : "#1F3A60", letterSpacing: "-0.1px", lineHeight: "20px", fontWeight: 400 }}>
        {isEmpty ? "—" : value}
      </span>
    </div>
  );
}

function PdfGrid({ children, cols }) {
  return (
    <div className="pdf-grid" style={{ display: "grid", gridTemplateColumns: `repeat(${cols || 3}, 1fr)`, gap: "20px 36px" }}>
      {children}
    </div>
  );
}

/* ── Contact card used in Family Contact section ──── */
function PdfContactCard({ heading, name, relationship, email, mobile, alwaysShowEmpty }) {
  /* For secondary contacts, suppress the entire card if there is no data at all */
  const hasAny = !!(name || relationship || email || mobile);
  if (!alwaysShowEmpty && !hasAny) return null;

  const lbl = {
    fontSize: 10, fontWeight: 500, color: "#9CA8B8",
    letterSpacing: "-0.05px", lineHeight: "14px",
  };
  const val = (hasValue) => ({
    fontSize: 13, letterSpacing: "-0.1px", lineHeight: "20px", fontWeight: 400,
    color: hasValue ? "#1F3A60" : "#C8D0DA",
  });

  /* For secondary: only render rows that have a value */
  const showRel     = alwaysShowEmpty || !!relationship;
  const showContact = alwaysShowEmpty || !!mobile || !!email;

  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 0 }}>
      {/* Sub-heading — L2 group title */}
      <div style={{
        fontSize: 11, fontWeight: 600, color: "#6B7A8F",
        letterSpacing: "-0.1px",
        marginBottom: 12,
      }}>
        {heading}
      </div>

      {/* Name — most prominent element */}
      <div style={{
        fontSize: 15, fontWeight: 600, letterSpacing: "-0.25px", lineHeight: "22px",
        color: name ? "#1F3A60" : "#C8D0DA",
        marginBottom: 14,
      }}>
        {name || "—"}
      </div>

      {/* Detail fields — 2-col mini-grid */}
      {(showRel || showContact) && (
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "11px 24px" }}>
          {showRel && (
            <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
              <span style={lbl}>Relationship</span>
              <span style={val(!!relationship)}>{relationship || "—"}</span>
            </div>
          )}
          {showContact && (
            <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
              <span style={lbl}>Contact</span>
              {(alwaysShowEmpty || !!mobile) && (
                <span style={val(!!mobile)}>{fmtPhone(mobile) || "—"}</span>
              )}
              {(alwaysShowEmpty || !!email) && (
                <span style={val(!!email)}>{email || "—"}</span>
              )}
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function CoverMeta({ label, value, sub }) {
  return (
    <div>
      <div style={{ fontSize: 10, color: "rgba(255,255,255,0.55)", letterSpacing: "0.12em", textTransform: "uppercase", marginBottom: 5 }}>
        {label}
      </div>
      <div style={{ fontSize: 13, color: "#FFFFFF", fontWeight: 500, letterSpacing: "-0.1px" }}>{value || "—"}</div>
      {sub && (
        <div style={{ fontSize: 11, color: "rgba(255,255,255,0.55)", marginTop: 3, letterSpacing: "-0.05px" }}>{sub}</div>
      )}
    </div>
  );
}

function PdfPricingRow({ label, sub, value, muted, total, brandBlue }) {
  const accent = brandBlue || "#003169";
  if (total) {
    return (
      <div style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        padding: "20px 24px", background: accent,
      }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 600, color: "#FFFFFF", letterSpacing: "-0.15px" }}>Total Payable</div>
          <div style={{ fontSize: 11, color: "rgba(255,255,255,0.6)", marginTop: 3 }}>All prices in SGD · GST separate</div>
        </div>
        <div style={{ fontSize: 26, fontWeight: 700, color: "#FFFFFF", letterSpacing: "-0.5px", fontFeatureSettings: "'tnum'" }}>
          {value}
        </div>
      </div>
    );
  }
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", padding: "12px 24px", borderBottom: "1px solid #F0F1F4" }}>
      <div>
        <span style={{ fontSize: 13, color: muted ? "#9CA8B8" : "#1F3A60", fontWeight: 500, letterSpacing: "-0.1px" }}>{label}</span>
        {sub && <div style={{ fontSize: 11, color: "#9CA8B8", marginTop: 2 }}>{sub}</div>}
      </div>
      <span style={{ fontSize: 13, fontWeight: 600, color: muted ? "#9CA8B8" : "#1F3A60", fontFeatureSettings: "'tnum'" }}>{value}</span>
    </div>
  );
}

function SigBox({ label, sub, signed, signatoryDisplayName, timestamp, relationship, brandBlue }) {
  const accent = brandBlue || "#003169";
  if (signed && signatoryDisplayName) {
    return (
      <div>
        {/* Signature area — filled when digitally signed */}
        <div style={{
          height: 80, borderBottom: `2px solid ${accent}`, marginBottom: 12,
          position: "relative",
          display: "flex", alignItems: "flex-end", paddingBottom: 10,
        }}>
          {/* Simulated cursive signature */}
          <span style={{
            fontFamily: "Georgia, 'Times New Roman', serif",
            fontSize: 26, fontStyle: "italic",
            color: accent, opacity: 0.78,
            letterSpacing: "0.02em", lineHeight: 1,
            userSelect: "none",
          }}>
            {signatoryDisplayName}
          </span>
          {/* Signed badge */}
          <span style={{
            position: "absolute", top: 8, right: 0,
            display: "inline-flex", alignItems: "center", gap: 4,
            padding: "3px 9px", borderRadius: 5,
            background: "#E8F0E4", border: "1px solid #C4D9B8",
            fontSize: 10, fontWeight: 700, color: "#5B7D4F",
            textTransform: "uppercase", letterSpacing: "0.08em",
          }}>
            ✓ Digitally Signed
          </span>
        </div>
        <div style={{ fontSize: 12, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.1px" }}>{label}</div>
        <div style={{ fontSize: 11, color: "#6B7A8F", marginTop: 3 }}>{signatoryDisplayName}</div>
        {relationship && (
          <div style={{ fontSize: 11, color: "#9CA8B8", marginTop: 2 }}>{relationship}</div>
        )}
        {timestamp && (
          <div style={{ fontSize: 11, color: "#9CA8B8", marginTop: 8, letterSpacing: "-0.05px" }}>
            Signed: {pdfDateMed(timestamp)} · {pdfTime(timestamp)}
          </div>
        )}
      </div>
    );
  }
  /* Unsigned state */
  return (
    <div>
      <div style={{ height: 80, borderBottom: `2px solid ${accent}`, marginBottom: 12 }} />
      <div style={{ fontSize: 12, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.1px" }}>{label}</div>
      {sub && <div style={{ fontSize: 11, color: "#6B7A8F", marginTop: 3 }}>{sub}</div>}
      <div style={{ fontSize: 11, color: "#9CA8B8", marginTop: 8, letterSpacing: "-0.05px" }}>
        Date: ___________________________
      </div>
    </div>
  );
}

/* ── The full document content ───────────────────────── */
function PdfDocumentContent({ caseDetails, serviceData, contacts, selectedPackage, selectedCasket, selectedAddOns, addOnTotal, notes, generatedAt, isSigned, confirmedAt, appliedCoupon }) {
  const contactsById = React.useMemo(
    () => Object.fromEntries((contacts || []).map((c) => [c.id, c])),
    [contacts]
  );
  const primaryContact   = serviceData?.primaryContactId   ? contactsById[serviceData.primaryContactId]   : null;
  const secondaryContact = serviceData?.secondaryContactId ? contactsById[serviceData.secondaryContactId] : null;

  const deceasedName  = serviceData?.deceasedName || caseDetails?.deceased || "—";
  const salutation    = (serviceData?.salutations || "").trim();
  const displayName   = salutation ? `${salutation} ${deceasedName}` : deceasedName;
  const religion      = titleCase(serviceData?.religion || caseDetails?.religion || "") || "—";
  const isFountains   = (caseDetails?.brand || "").toLowerCase().includes("fountain");
  const rel           = (serviceData?.religion || caseDetails?.religion || "").toLowerCase();
  const isChristian   = rel === "christian";
  const isCatholic    = rel === "catholic";
  const isBuddhist    = rel === "buddhist";
  const isTaoist      = rel === "taoist";
  const isBuddhistTaoist = isBuddhist || isTaoist;
  const isFreeThinker = rel.includes("free");

  /* Brand accent colour and display name */
  const brandBlue  = isFountains ? "#384967" : "#003169";
  const brandDark  = isFountains ? "#2B3A50" : "#002050";
  const brandShort = isFountains ? "Fountains" : "Serenity";
  const brandName  = caseDetails?.brand || (isFountains ? "Fountains Funerals" : "Serenity Casket & Funerals");

  /* Disposition type helpers */
  const dispType  = (serviceData?.cremationOrBurial || "").toLowerCase();
  const isCremation = dispType === "cremation";
  const isBurialDisp = dispType === "burial";

  /* Marital status decode */
  const maritalStatusLabel = ({ S: "Single", M: "Married", D: "Divorced", W: "Widowed" })[serviceData?.maritalStatus] || serviceData?.maritalStatus || null;

  /* Memorial / pastoral date-time formatter */
  const fmtDT = (val) => {
    if (!val) return null;
    try {
      const d = new Date(val);
      if (isNaN(d.getTime())) return val;
      return d.toLocaleDateString("en-SG", { day: "numeric", month: "long", year: "numeric" }) +
             " · " + d.toLocaleTimeString("en-SG", { hour: "2-digit", minute: "2-digit" });
    } catch { return val; }
  };

  const pkgPrice     = selectedPackage?.price    || 0;
  const casketUpgrade = selectedCasket ? (selectedCasket.included ? 0 : (selectedCasket.upgrade || 0)) : 0;
  const total        = pkgPrice + casketUpgrade + addOnTotal;
  const realAddOns   = (selectedAddOns || []).filter((it) => it.itemType !== "section" && it.itemType !== "note");
  const allAddOnRows = selectedAddOns || [];

  const genDate = generatedAt
    ? new Date(generatedAt).toLocaleDateString("en-SG", { day: "numeric", month: "long", year: "numeric" })
    : new Date().toLocaleDateString("en-SG", { day: "numeric", month: "long", year: "numeric" });

  return (
    <div style={{ fontFamily: "inherit" }}>

      {/* ══ COVER ══════════════════════════════════════════ */}
      <div className="pdf-cover" style={{
        background: `linear-gradient(155deg, ${brandBlue} 0%, ${brandDark} 100%)`,
        padding: "80px",
        position: "relative", overflow: "hidden",
      }}>
        {/* Subtle light bleed */}
        <div style={{
          position: "absolute", inset: 0, opacity: 0.08,
          background: "radial-gradient(ellipse at 5% 95%, #C8D8F0 0%, transparent 50%), radial-gradient(ellipse at 95% 5%, #7EA8C8 0%, transparent 50%)",
          pointerEvents: "none",
        }} />
        <div style={{ position: "relative", display: "flex", flexDirection: "column", gap: 28 }}>

          {/* Brand */}
          <div>
            <div style={{ fontSize: 14, fontWeight: 600, color: "#FFFFFF", letterSpacing: "0.2em", textTransform: "uppercase" }}>
              {brandShort}
            </div>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.6)", letterSpacing: "0.14em", textTransform: "uppercase", marginTop: 4 }}>
              Funeral Directors
            </div>
          </div>

          {/* Deceased */}
          <div style={{ padding: "16px 0" }}>
            <div style={{ fontSize: 11, color: "rgba(255,255,255,0.55)", letterSpacing: "0.16em", textTransform: "uppercase", marginBottom: 14 }}>
              Funeral Arrangement for
            </div>
            <h1 style={{ fontSize: 42, fontWeight: 300, color: "#FFFFFF", letterSpacing: "-0.5px", lineHeight: "1.05", margin: "0 0 10px" }}>
              {displayName}
            </h1>
            {(serviceData?.dateOfBirth || serviceData?.dateOfDeath) && (
              <div style={{ fontSize: 14, color: "rgba(255,255,255,0.55)", letterSpacing: "0.02em" }}>
                {serviceData?.dateOfBirth ? pdfDateMed(serviceData.dateOfBirth) + " – " : ""}
                {serviceData?.dateOfDeath ? pdfDateMed(serviceData.dateOfDeath) : ""}
              </div>
            )}
          </div>

          {/* Footer meta */}
          <div style={{ display: "flex", gap: 40, paddingTop: 20, borderTop: "1px solid rgba(255,255,255,0.15)", alignItems: "flex-end" }}>
            <CoverMeta label="Case Number" value={caseDetails?.quotationId} />
            <CoverMeta label="Contact" value={caseDetails?.contact} />
            <CoverMeta label="Relationship" value={caseDetails?.relationship} />
            <CoverMeta label="Religion" value={religion} />
            <CoverMeta label="Prepared on" value={genDate} />
            {isSigned && (
              <div style={{ marginLeft: "auto", flexShrink: 0 }}>
                <div style={{
                  display: "inline-flex", alignItems: "center", gap: 6,
                  padding: "5px 12px", borderRadius: 6,
                  background: "rgba(91,125,79,0.18)", border: "1px solid rgba(91,125,79,0.35)",
                }}>
                  <span style={{ width: 6, height: 6, borderRadius: "50%", background: "#8FCF7E", flexShrink: 0 }} />
                  <span style={{ fontSize: 11, fontWeight: 700, color: "#8FCF7E", letterSpacing: "0.1em", textTransform: "uppercase" }}>Signed</span>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* ══ DOCUMENT BODY ═══════════════════════════════════ */}
      <div style={{ padding: "80px", background: "#FFFFFF" }}>

        {/* Introduction */}
        <PdfSection first>
          {/* Signed confirmation banner — shown once signed */}
          {isSigned && (
            <div style={{
              display: "flex", alignItems: "center", gap: 14,
              padding: "16px 20px", borderRadius: 10, marginBottom: 28,
              background: "#E8F0E4", border: "1px solid #C4D9B8",
            }}>
              <span style={{
                width: 36, height: 36, borderRadius: "50%", flexShrink: 0,
                background: "#5B7D4F",
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>
                <SerIcons.Check size={16} color="#FFFFFF" />
              </span>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, fontWeight: 700, color: "#3A5E30", letterSpacing: "-0.1px" }}>
                  Digitally Signed &amp; Confirmed
                </div>
                <div style={{ fontSize: 12, color: "#5B7D4F", marginTop: 2, letterSpacing: "-0.05px" }}>
                  {confirmedAt
                    ? `Signed on ${pdfDateMed(confirmedAt)} at ${pdfTime(confirmedAt)} · Customer confirmed via Odoo`
                    : "Customer has reviewed and signed this Service Summary Form via Odoo"
                  }
                </div>
              </div>
            </div>
          )}
          <p style={{ fontSize: 14, color: "#574F40", lineHeight: "26px", letterSpacing: "-0.1px", margin: 0, maxWidth: 580 }}>
            {isSigned
              ? `We are honoured to have guided your family through this arrangement. The following Service Summary Form has been reviewed, agreed to, and digitally signed by the family representative.`
              : `We are honoured to accompany your family through this time. The following arrangement has been prepared by ${brandName} with care and deep respect, in accordance with the wishes and requirements discussed during our consultation. Please review the details below carefully before signing.`
            }
          </p>
        </PdfSection>

        {/* ── Deceased Details ─────────────────────────────── */}
        <PdfSection title="Deceased Details">
          <PdfGrid>
            <PdfField label="Full Name"      value={displayName} />
            <PdfField label="Gender"         value={serviceData?.gender === "M" ? "Male" : serviceData?.gender === "F" ? "Female" : serviceData?.gender} />
            <PdfField label="Age"            value={serviceData?.age ? String(serviceData.age) : null} />
            <PdfField label="Date of Birth"  value={pdfDateMed(serviceData?.dateOfBirth)} />
            <PdfField label="Date of Death"  value={pdfDateMed(serviceData?.dateOfDeath)} />
            <PdfField label="Time of Death"  value={serviceData?.timeOfDeath} />
            <PdfField label="Religion"       value={religion} />
            <PdfField label="Marital Status" value={maritalStatusLabel} />
            {isFountains && (
              <PdfField label="Dialect" value={serviceData?.dialect} />
            )}
          </PdfGrid>
        </PdfSection>

        {/* ── Case Contacts ────────────────────────────────── */}
        {(() => {
          const primaryName    = primaryContact?.name || caseDetails?.contact;
          const primaryRel     = serviceData?.primaryRelationship;
          const primaryEmail   = primaryContact?.email;
          const primaryMobile  = primaryContact?.mobile || primaryContact?.phone || caseDetails?.phone;

          const secondaryName   = secondaryContact?.name;
          const secondaryRel    = serviceData?.secondaryRelationship;
          const secondaryEmail  = secondaryContact?.email;
          const secondaryMobile = secondaryContact?.mobile || secondaryContact?.phone;
          const hasSecondary    = !!(secondaryName || secondaryRel || secondaryEmail || secondaryMobile);

          return (
            <PdfSection title="Case Contacts">
              <div style={{ display: "flex", gap: 0, alignItems: "flex-start" }}>
                {/* Primary — always present */}
                <div style={{ flex: 1 }}>
                  <PdfContactCard
                    heading="Primary Contact"
                    name={primaryName}
                    relationship={primaryRel}
                    email={primaryEmail}
                    mobile={primaryMobile}
                    alwaysShowEmpty
                  />
                </div>

                {/* Vertical rule + secondary — only when secondary data exists */}
                {hasSecondary && (
                  <React.Fragment>
                    <div style={{ width: 1, background: "#EAE6DF", alignSelf: "stretch", margin: "0 40px", flexShrink: 0 }} />
                    <div style={{ flex: 1 }}>
                      <PdfContactCard
                        heading="Secondary Contact"
                        name={secondaryName}
                        relationship={secondaryRel}
                        email={secondaryEmail}
                        mobile={secondaryMobile}
                        alwaysShowEmpty={false}
                      />
                    </div>
                  </React.Fragment>
                )}
              </div>
            </PdfSection>
          );
        })()}

        {/* ── Family Tree — Fountains workspace only ────────── */}
        {isFountains && (() => {
          const fam = serviceData?.family || {};

          /* Each group: definition + live data */
          const GROUPS = [
            { title: "Children", data: fam.children || {}, fields: [
                ["son", "Son"], ["daughter", "Daughter"],
                ["sonInLaw", "Son-in-Law"], ["daughterInLaw", "Daughter-in-Law"],
              ]},
            { title: "Siblings", data: fam.siblings || {}, fields: [
                ["elderBrother", "Elder Brother"],   ["youngerBrother", "Younger Brother"],
                ["elderSister", "Elder Sister"],     ["youngerSister", "Younger Sister"],
                ["elderBrotherInLaw", "Elder Brother-in-Law"], ["youngerBrotherInLaw", "Younger Brother-in-Law"],
                ["elderSisterInLaw", "Elder Sister-in-Law"],   ["youngerSisterInLaw", "Younger Sister-in-Law"],
              ]},
            { title: "Paternal Grandchildren", data: fam.paternal || {}, fields: [
                ["elderGrandson", "Elder Grandson"], ["grandson", "Grandson"],
                ["grandsonInLaw", "Grandson-in-Law"],
                ["elderGranddaughterInLaw", "Elder Grand-Daughter-in-Law"],
                ["granddaughter", "Grand-Daughter"], ["granddaughterInLaw", "Grand-Daughter-in-Law"],
                ["greatGrandson", "Great Grandson"],
              ]},
            { title: "Maternal Grandchildren", data: fam.maternal || {}, fields: [
                ["grandson", "Grandson"], ["granddaughter", "Grand-Daughter"],
                ["granddaughterInLaw", "Grand-Daughter-in-Law"], ["grandsonInLaw", "Grandson-in-Law"],
                ["greatGrandson", "Great Grandson"],
              ]},
          ];

          /* Only include rows with a non-zero count */
          const activeGroups = GROUPS.map((g) => ({
            ...g,
            activeFields: g.fields.filter(([k]) => (Number(g.data[k]) || 0) > 0),
          })).filter((g) => g.activeFields.length > 0);

          const hasFamilyRecord = serviceData?.survivingSpouse || serviceData?.survivingParents;
          const hasFamilyTree   = activeGroups.length > 0;
          if (!hasFamilyRecord && !hasFamilyTree) return null;

          return (
            <PdfSection title="Family Tree">
              {/* Family Record — Surviving Spouse / Parents */}
              {hasFamilyRecord && (
                <PdfGrid cols={3}>
                  {serviceData.survivingSpouse  && <PdfField label="Surviving Spouse"  value={serviceData.survivingSpouse} />}
                  {serviceData.survivingParents && <PdfField label="Surviving Parents" value={serviceData.survivingParents} />}
                </PdfGrid>
              )}

              {/* Family counts by group */}
              {hasFamilyTree && (
                <div style={{ marginTop: hasFamilyRecord ? 22 : 0, display: "flex", flexDirection: "column", gap: 0 }}>
                  {activeGroups.map((group, gi) => (
                    <div key={gi} style={{
                      borderTop: (gi > 0 || hasFamilyRecord) ? "1px solid #F0F1F4" : "none",
                      paddingTop: (gi > 0 || hasFamilyRecord) ? 16 : 0,
                      paddingBottom: 16,
                    }}>
                      {/* Group heading */}
                      <div style={{ fontSize: 12, fontWeight: 700, color: "#6B7A8F", letterSpacing: "-0.05px", marginBottom: 14 }}>
                        {group.title}
                      </div>
                      {/* Member rows — 4-up grid, only non-zero */}
                      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "12px 24px" }}>
                        {group.activeFields.map(([key, label]) => (
                          <div key={key} style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                            <span style={{ fontSize: 10, color: "#9CA8B8", fontWeight: 500, letterSpacing: "-0.05px", lineHeight: "14px" }}>
                              {label}
                            </span>
                            <span style={{ fontSize: 13, fontWeight: 400, color: "#1F3A60", letterSpacing: "-0.1px", lineHeight: "20px" }}>
                              {Number(group.data[key]) || 0}
                            </span>
                          </div>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </PdfSection>
          );
        })()}

        {/* ── Preparation & Care ───────────────────────────── */}
        <PdfSection title="Preparation & Care">
          <PdfGrid>
            {(() => {
              const t = serviceData?.transferLocationType || serviceData?.transferLocation;
              if (!t) return <PdfField label="Transfer Location" value={null} />;
              let specific = null;
              if (t === "Hospital") {
                const h = serviceData?.transferLocationHospital;
                specific = h === "Others" ? (serviceData?.transferLocationRemarks || null) : (h || null);
              } else if (t === "Hospice") {
                const h = serviceData?.transferLocationHospice;
                specific = h === "Others" ? (serviceData?.transferLocationRemarks || null) : (h || null);
              } else {
                specific = serviceData?.transferLocationRemarks || null;
              }
              return <PdfField label="Transfer Location" value={specific ? `${t} – ${specific}` : t} />;
            })()}
            {(() => {
              const opts = Array.isArray(serviceData?.embalmingOptions) ? serviceData.embalmingOptions : [];
              const labels = opts.map(id => {
                const found = (window.EMBALMING_OPTIONS || []).find(o => o.id === id);
                return found ? found.label : id;
              });
              const displayVal = labels.length > 0 ? labels.join("\n") : null;
              return <PdfField label="Embalming Options" value={displayVal} span2={labels.length > 1} />;
            })()}
            <PdfField label="Embalming Remarks" value={serviceData?.embalmingRemarks} span2={!!serviceData?.embalmingRemarks} />
          </PdfGrid>
        </PdfSection>

        {/* ── Wake & Service ───────────────────────────────── */}
        <PdfSection title="Wake & Service">
          <PdfGrid>
            <PdfField label="Wake Venue" value={(() => {
              const type = serviceData?.wakeVenueType;
              if (!type && !serviceData?.wakeVenue) return "To be confirmed";
              if (type === "Parlour") {
                const p = serviceData.wakeVenueParlour;
                if (!p) return "Parlour";
                const loc = p === "Others" ? (serviceData.wakeVenueRemarks || null) : p;
                return loc ? `Parlour – ${loc}` : "Parlour";
              }
              if (type === "Church") {
                const c = serviceData.wakeVenueChurch;
                if (!c) return "Church";
                const loc = c === "Others" ? (serviceData.wakeVenueRemarks || null) : c;
                return loc ? `Church – ${loc}` : "Church";
              }
              if (type === "HDB") {
                const addr = serviceData.wakeVenueRemarks;
                return addr ? `HDB – ${addr}` : "HDB";
              }
              if (type === "Others") {
                const custom = serviceData.wakeVenueRemarks;
                return custom ? `Others – ${custom}` : "Others";
              }
              return type || serviceData.wakeVenue || "To be confirmed";
            })()} />
            <PdfField label="Wake Commences"  value={pdfDateMed(serviceData?.wakeStartDate)} />
            <PdfField label="Wake Concludes"  value={pdfDateMed(serviceData?.wakeEndDate)} />
            <PdfField label="Duration"        value={serviceData?.wakeDuration ? `${serviceData.wakeDuration} day${serviceData.wakeDuration !== "1" ? "s" : ""}` : null} />
            <PdfField label="Visiting Hours"  value={serviceData?.visitingHours} />
          </PdfGrid>
        </PdfSection>

        {/* ── Final Resting ─────────────────────────────────── */}
        <PdfSection title="Final Resting">
          <PdfGrid>
            <PdfField label="Funeral Arrangement" value={
              isCremation ? "Cremation" : isBurialDisp ? "Burial" :
              (serviceData?.cremationOrBurial ? titleCase(serviceData.cremationOrBurial) : null)
            } />
            <PdfField label="Funeral Date" value={pdfDateMed(serviceData?.dispositionDate)} />

            {/* Cremation or Burial location — show only the relevant one */}
            {isCremation && (
              <PdfField label="Cremation Location" value={serviceData?.cremationLocation} />
            )}
            {isBurialDisp && (
              <PdfField label="Burial Location" value={serviceData?.burialLocation} />
            )}

            {isCremation && (
              <PdfField label="Final Resting" value={(() => {
                const arr = serviceData?.restingArrangement === "Others"
                  ? (serviceData?.finalRestingLocationOthers || null)
                  : (serviceData?.restingArrangement || null);
                const loc = serviceData?.finalRestingLocation === "Others"
                  ? (serviceData?.finalRestingLocationOthers || null)
                  : (serviceData?.finalRestingLocation || null);
                if (!arr && !loc) return null;
                return arr && loc ? `${arr} – ${loc}` : (arr || loc);
              })()} />
            )}
            {isCremation && (
              <PdfField label="Final Resting Date / Time" value={serviceData?.finalRestingDate ? pdfDateLong(serviceData.finalRestingDate) : null} />
            )}

            {/* Prayer service — Buddhist / Taoist / Fountains */}
            {(isFountains || isBuddhistTaoist) && (
              <PdfField label="Prayer Service" value={(() => {
                const ps = serviceData?.prayerService;
                if (Array.isArray(ps) && ps.length > 0) {
                  return ps.map(id => id === "others" ? (serviceData?.prayerServiceOthers || "Others") : id).join(", ");
                }
                return typeof ps === "string" && ps ? ps : null;
              })()} />
            )}

            {/* Disposition Remarks — full-width when present */}
            <PdfField label="Additional Information" value={serviceData?.dispositionRemarks} span2={!!serviceData?.dispositionRemarks} />
          </PdfGrid>
        </PdfSection>

        {/* ── Pastoral / Religious Care ─────────────────────
             Shown whenever there are religion-specific fields to display:
             Christian, Catholic, Buddhist, Taoist, or Fountains workspace. */}
        {(isChristian || isCatholic || isBuddhistTaoist || isFountains) && (
          <PdfSection title={isBuddhistTaoist || isFountains ? "Religious Arrangements" : "Pastoral Care"}>
            <PdfGrid>

              {/* ── Christian fields ── */}
              {isChristian && (
                <React.Fragment>
                  <PdfField label="Church"  value={serviceData?.church} />
                  <PdfField label="Pastor"  value={serviceData?.pastor} />
                  <PdfField label="Memorial Service Date / Time" value={fmtDT(serviceData?.memorialServiceDateTime)} />
                </React.Fragment>
              )}

              {/* ── Catholic fields ── */}
              {isCatholic && (
                <React.Fragment>
                  <PdfField label="Parish Church"    value={serviceData?.parish} />
                  <PdfField label="Nightly Prayers"  value={serviceData?.nightlyPrayersDateTime ? fmtDT(serviceData.nightlyPrayersDateTime) : null} />
                  <PdfField label="Church Mass"      value={serviceData?.churchMass ? "Yes — required" : null} />
                  <PdfField label="Mass Location"    value={serviceData?.churchMassDetails} span2={!!serviceData?.churchMassDetails} />
                  <PdfField label="Mass Date / Time" value={serviceData?.massDateTime ? fmtDT(serviceData.massDateTime) : null} />
                </React.Fragment>
              )}

              {/* ── Buddhist / Taoist / Fountains fields ── */}
              {(isBuddhistTaoist || isFountains) && (
                <React.Fragment>
                  <PdfField label="Ancestral Tablet Location" value={serviceData?.ancestorTabletLocation} />
                  <PdfField label="Anling / Jiling Remarks"   value={serviceData?.jilingAnlingRemarks} span2={!!serviceData?.jilingAnlingRemarks} />
                </React.Fragment>
              )}

            </PdfGrid>
          </PdfSection>
        )}

        {/* ── Selected Package ─────────────────────────────── */}
        {selectedPackage ? (
          <PdfSection title="Selected Package">
            {/* Package header: name + price */}
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 6 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 20, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.3px", marginBottom: 4 }}>
                  {selectedPackage.name}
                </div>
                {selectedPackage.venueLabel && (
                  <div style={{ fontSize: 13, color: "#6B7A8F", marginBottom: 2 }}>{selectedPackage.venueLabel}</div>
                )}
                {selectedPackage.blurb && (
                  <div style={{ fontSize: 13, color: "#9CA8B8", lineHeight: "20px" }}>{selectedPackage.blurb}</div>
                )}
              </div>
              <div style={{ fontSize: 22, fontWeight: 700, color: "#1F3A60", letterSpacing: "-0.4px", fontFeatureSettings: "'tnum'", flexShrink: 0, marginLeft: 24 }}>
                {formatPrice(pkgPrice)}
              </div>
            </div>

            {/* Package inclusions — grouped by section */}
            {selectedPackage.sections && selectedPackage.sections.length > 0 && (
              <div style={{ marginTop: 20, display: "flex", flexDirection: "column", gap: 0 }}>
                {selectedPackage.sections.map((section, si) => (
                  <div key={si} style={{ borderTop: "1px solid #EAE6DF", paddingTop: 16, paddingBottom: 16, marginTop: si === 0 ? 0 : 0 }}>
                    {/* Section name */}
                    <div style={{ fontSize: 12, fontWeight: 700, color: "#1F3A60", letterSpacing: "-0.1px", marginBottom: 12 }}>
                      {section.name}
                    </div>
                    {/* Items */}
                    <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
                      {section.items.map((item, ii) => (
                        <div key={ii} style={{ display: "flex", alignItems: "flex-start", gap: 10, fontSize: 13, color: "#574F40", lineHeight: "19px" }}>
                          <span style={{
                            width: 16, height: 16, borderRadius: "50%",
                            background: "#F0F4F0", border: "1px solid #C4D9B8",
                            display: "inline-flex", alignItems: "center", justifyContent: "center",
                            flexShrink: 0, marginTop: 1,
                          }}>
                            <SerIcons.Check size={9} color="#5B7D4F" />
                          </span>
                          {item}
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
            )}
          </PdfSection>
        ) : (
          <PdfSection title="Selected Package">
            <div style={{ padding: "20px 0", color: "#9CA8B8", fontSize: 13 }}>No package selected</div>
          </PdfSection>
        )}

        {/* ── Selected Casket ───────────────────────────────── */}
        <PdfSection title="Selected Casket">
          {selectedCasket ? (
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div>
                <div style={{ fontSize: 16, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.2px" }}>{selectedCasket.name}</div>
                <div style={{ fontSize: 13, color: "#6B7A8F", marginTop: 5 }}>
                  {selectedCasket.finish}{selectedCasket.material ? ` · ${selectedCasket.material}` : ""}
                </div>
              </div>
              <div>
                {selectedCasket.included
                  ? <span style={{ fontSize: 13, color: "#5B7D4F", fontWeight: 500 }}>Included in package</span>
                  : <span style={{ fontSize: 18, fontWeight: 700, color: "#1F3A60", fontFeatureSettings: "'tnum'" }}>+{formatPrice(casketUpgrade)}</span>
                }
              </div>
            </div>
          ) : (
            <div style={{ color: "#9CA8B8", fontSize: 13 }}>No casket selected</div>
          )}
        </PdfSection>

        {/* ── Add-on Items ─────────────────────────────────── */}
        <PdfSection title={realAddOns.length > 0 ? `Add-on Items (${realAddOns.length})` : "Add-on Items"}>
          {realAddOns.length === 0 ? (
            <div style={{ fontSize: 13, color: "#C8D0DA", letterSpacing: "-0.1px" }}>—</div>
          ) : (
            <React.Fragment>
            {/* Header */}
            <div style={{
              display: "grid", gridTemplateColumns: "1fr 60px 100px",
              padding: "6px 0 12px", borderBottom: "1.5px solid #E5E7EB",
              fontSize: 10, color: "#9CA8B8", fontWeight: 700, textTransform: "uppercase", letterSpacing: "0.12em",
            }}>
              <span>Item</span>
              <span style={{ textAlign: "center" }}>Qty</span>
              <span style={{ textAlign: "right" }}>Amount</span>
            </div>
            {allAddOnRows.map((item, i) => {
              if (item.itemType === "section") return (
                <div key={i} style={{ padding: "12px 0 4px", fontSize: 10, fontWeight: 700, color: "#9CA8B8", textTransform: "uppercase", letterSpacing: "0.12em" }}>
                  {item.name.replace(/^§\s*/, "")}
                </div>
              );
              if (item.itemType === "note") return (
                <div key={i} style={{ padding: "4px 0", fontSize: 12, color: "#9CA8B8" }}>{item.name}</div>
              );
              const lineTotal = item.chargeType === "complimentary" ? 0 : item.unitPrice * item.quantity * (item.rentalDays || 1);
              let displayTotal = lineTotal;
              if (item.discountType === "percent" && item.discountValue > 0) displayTotal = lineTotal * (1 - item.discountValue / 100);
              else if (item.discountType === "fixed"   && item.discountValue > 0) displayTotal = Math.max(0, lineTotal - item.discountValue);
              return (
                <div key={i} style={{ display: "grid", gridTemplateColumns: "1fr 60px 100px", padding: "11px 0", borderBottom: "1px solid #F0F1F4", alignItems: "center" }}>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 500, color: "#1F3A60", letterSpacing: "-0.1px" }}>{item.name}</div>
                    {item.chargeType === "complimentary" && (
                      <span style={{ fontSize: 11, color: "#5B7D4F", fontWeight: 600 }}>Complimentary</span>
                    )}
                    {item.discountValue > 0 && (
                      <span style={{ fontSize: 11, color: "#9A6B1F", fontWeight: 600, marginLeft: item.chargeType === "complimentary" ? 6 : 0 }}>
                        {item.discountType === "percent" ? `-${item.discountValue}%` : `-${formatPrice(item.discountValue)}`}
                      </span>
                    )}
                  </div>
                  <div style={{ textAlign: "center" }}>
                    <span style={{ fontSize: 13, color: "#6B7A8F" }}>{item.quantity}</span>
                    {item.rentalDays && (
                      <div style={{ fontSize: 10, color: "#9CA8B8", marginTop: 1 }}>{item.rentalDays} days</div>
                    )}
                  </div>
                  <span style={{ textAlign: "right", fontSize: 13, fontWeight: 600, fontFeatureSettings: "'tnum'", color: item.chargeType === "complimentary" ? "#5B7D4F" : "#1F3A60" }}>
                    {item.chargeType === "complimentary" ? "—" : formatPrice(displayTotal)}
                  </span>
                </div>
              );
            })}
            {/* Add-on subtotal */}
            <div style={{
              display: "grid", gridTemplateColumns: "1fr 60px 100px",
              padding: "14px 0 2px",
              borderTop: "1.5px solid #E5E7EB",
              marginTop: 2,
              alignItems: "center",
            }}>
              <span style={{ fontSize: 13, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.1px" }}>
                Add-on Items Subtotal
              </span>
              <span />
              <span style={{ textAlign: "right", fontSize: 13, fontWeight: 600, fontFeatureSettings: "'tnum'", color: "#1F3A60" }}>
                {formatPrice(addOnTotal)}
              </span>
            </div>
            </React.Fragment>
          )}
        </PdfSection>

        {/* ── Arrangement Notes ─────────────────────────────── */}
        {notes && notes.trim() && (
          <PdfSection title="Arrangement Notes">
            <p style={{ margin: 0, fontSize: 13, color: "#574F40", lineHeight: "22px", letterSpacing: "-0.1px" }}>
              {notes.trim()}
            </p>
          </PdfSection>
        )}

        {/* ── Quotation Summary ─────────────────────────────── */}
        <PdfSection title="Quotation Summary">
          {(() => {
            const coupons    = Array.isArray(appliedCoupon) ? appliedCoupon : (appliedCoupon ? [appliedCoupon] : []);
            const discountCs = coupons.filter((c) => c.type === "discount");
            const couponAmt  = discountCs.reduce((sum, c) => sum + (c.amount || 0), 0);
            const subtotal = total;
            const adjustedSubtotal = Math.max(0, subtotal - couponAmt);
            const gst = adjustedSubtotal * 0.09;
            const finalTotal = adjustedSubtotal * 1.09;
            return (
              <div className="pdf-pricing-box" style={{ border: "1px solid #E8E4DE", borderRadius: 10, overflow: "hidden" }}>
                <PdfPricingRow label="Subtotal" value={formatPrice(subtotal)} />
                {discountCs.map((c) => (
                  <PdfPricingRow
                    key={c.code}
                    label={`Coupon Discount (${c.code})`}
                    sub={`$${c.amount} deducted from subtotal`}
                    value={`−${formatPrice(c.amount || 0)}`}
                    muted
                  />
                ))}
                {couponAmt > 0 && (
                  <PdfPricingRow label="Adjusted Subtotal" value={formatPrice(adjustedSubtotal)} />
                )}
                <PdfPricingRow label="GST (9%)" value={formatPrice(gst)} muted brandBlue={brandBlue} />
                <PdfPricingRow total value={formatPrice(finalTotal)} brandBlue={brandBlue} />
              </div>
            );
          })()}
        </PdfSection>

        {/* ── Terms & Acceptance ───────────────────────────── */}
        <PdfSection title="Terms & Acceptance">
          <div style={{ fontSize: 12, color: "#8A9BAB", lineHeight: "21px", letterSpacing: "-0.05px", display: "flex", flexDirection: "column", gap: 10 }}>
            <p style={{ margin: 0 }}>
              By signing this Service Summary Form, the family representative acknowledges and agrees to the arrangement details and associated costs as presented above. {brandName} will proceed to deliver the agreed services upon confirmation.
            </p>
            <p style={{ margin: 0 }}>
              Payment terms: A deposit equivalent to 50% of the Total Payable is required upon confirmation. The remaining balance is payable upon conclusion of the funeral services. All prices shown are before GST; GST at the prevailing rate of 9% is applied separately and shown in the Quotation Summary above.
            </p>
            <p style={{ margin: 0 }}>
              Any amendments to this arrangement will require a new Service Summary Form and re-confirmation by the family representative. {brandName} reserves the right to adjust pricing in exceptional circumstances with prior notification to the family.
            </p>
          </div>
        </PdfSection>

        {/* ── Signature ────────────────────────────────────── */}
        <PdfSection title="Confirmation & Signature">
          <p style={{ fontSize: 13, color: "#6B7A8F", letterSpacing: "-0.1px", margin: "0 0 32px", lineHeight: "21px" }}>
            {isSigned
              ? "This Service Summary Form has been reviewed, agreed to, and digitally signed by the family representative. The arrangement below is now confirmed."
              : `Please review all arrangement details carefully. By signing below, you confirm that the information is accurate and authorise ${brandName} to proceed with the agreed services.`
            }
          </p>
          <div style={{ maxWidth: 360 }}>
            <SigBox
              label="Family Representative"
              sub={caseDetails?.contact}
              signed={isSigned}
              signatoryDisplayName={caseDetails?.contact}
              timestamp={isSigned ? confirmedAt : null}
              relationship={caseDetails?.relationship}
              brandBlue={brandBlue}
            />
          </div>
          <div style={{
            marginTop: 28, padding: "14px 20px", borderRadius: 8,
            fontSize: 11, letterSpacing: "-0.05px", lineHeight: "18px",
            background: isSigned ? "#E8F0E4" : "#F9F8F5",
            border: isSigned ? "1px solid #C4D9B8" : "none",
            color: isSigned ? "#5B7D4F" : "#9CA8B8",
          }}>
            {isSigned
              ? "This Service Summary Form has been digitally signed via Odoo and constitutes the binding confirmation of the funeral arrangement."
              : "This document is signed digitally via Odoo. Once signed, this Service Summary Form constitutes the binding confirmation of the funeral arrangement."
            }
          </div>
        </PdfSection>

      </div>
    </div>
  );
}

/* ── Odoo signing step indicator ────────────────────── */
function SigningStep({ label, state }) {
  return (
    <div style={{
      display: "flex", alignItems: "center", gap: 10,
      padding: "9px 14px", borderRadius: 8,
      background: state === "done" ? "#E8F0E4" : state === "active" ? "#F0F4F8" : "#FAFAFA",
      border: `1px solid ${state === "done" ? "#C4D9B8" : state === "active" ? "#CBD5E1" : "#E5E7EB"}`,
      transition: "all 300ms ease",
    }}>
      {state === "done" ? (
        <SerIcons.Check size={14} color="#5B7D4F" />
      ) : state === "active" ? (
        <span style={{
          width: 14, height: 14, borderRadius: "50%", flexShrink: 0,
          border: "2px solid #CBD5E1", borderTopColor: "#1F3A60",
          animation: "seros-spin 0.75s linear infinite", display: "inline-block",
        }} />
      ) : (
        <span style={{ width: 14, height: 14, borderRadius: "50%", background: "#E5E7EB", flexShrink: 0 }} />
      )}
      <span style={{ fontSize: 13, color: state === "done" ? "#5B7D4F" : state === "active" ? "#1F3A60" : "#9CA8B8", letterSpacing: "-0.1px" }}>
        {label}
      </span>
    </div>
  );
}

/* ══════════════════════════════════════════════════════
   EmailShareOverlay
   Gmail-style recipient chips + contact-aware sharing UX.
   ══════════════════════════════════════════════════════ */
function EmailShareOverlay({ caseDetails, serviceData, contacts, onClose, onUpdateContact, onSent }) {
  const contactsById = React.useMemo(
    () => Object.fromEntries((contacts || []).map((c) => [c.id, c])),
    [contacts]
  );
  const primaryContact   = serviceData?.primaryContactId   ? contactsById[serviceData.primaryContactId]   : null;
  const secondaryContact = serviceData?.secondaryContactId ? contactsById[serviceData.secondaryContactId] : null;
  const primaryEmail     = serviceData?.primaryContactEmail   || primaryContact?.email   || "";
  const secondaryEmail   = serviceData?.secondaryContactEmail || secondaryContact?.email || "";

  /* Recipients list — pre-seed with primary contact if email is known */
  const [recipients, setRecipients] = React.useState(() =>
    primaryEmail ? [{ key: primaryEmail, name: primaryContact?.name || caseDetails?.contact || "Primary Contact", email: primaryEmail, contactId: primaryContact?.id || null }] : []
  );
  const [input,         setInput]         = React.useState("");
  const [addEmailFor,   setAddEmailFor]   = React.useState(null); // { contactId, name }
  const [addEmailInput, setAddEmailInput] = React.useState("");
  const [sending,       setSending]       = React.useState(false);
  const [sent,          setSent]          = React.useState(false);
  const inputRef = React.useRef(null);

  const addRecipient = (name, email, contactId = null) => {
    if (!email) return;
    const normalised = email.toLowerCase().trim();
    setRecipients((rs) => rs.some((r) => r.email.toLowerCase() === normalised) ? rs
      : [...rs, { key: normalised, name: name || email, email: normalised, contactId }]
    );
  };
  const removeRecipient = (key) => setRecipients((rs) => rs.filter((r) => r.key !== key));

  const commitInput = () => {
    const val = input.trim();
    if (val.includes("@")) { addRecipient(val, val); setInput(""); }
  };
  const handleInputKeyDown = (e) => {
    if (e.key === "Enter" || e.key === ",") { e.preventDefault(); commitInput(); }
    else if (e.key === "Backspace" && !input && recipients.length) setRecipients((rs) => rs.slice(0, -1));
    else if (e.key === "Escape") onClose();
  };

  const handleSaveAndAddEmail = async () => {
    const email = addEmailInput.trim();
    if (!email.includes("@") || !addEmailFor) return;
    if (onUpdateContact && addEmailFor.contactId) {
      const c = contactsById[addEmailFor.contactId];
      if (c) await onUpdateContact(addEmailFor.contactId, { ...c, email });
    }
    addRecipient(addEmailFor.name, email, addEmailFor.contactId);
    setAddEmailFor(null);
    setAddEmailInput("");
  };

  const handleSend = () => {
    if (!recipients.length || sending || sent) return;
    setSending(true);
    setTimeout(() => { setSent(true); setTimeout(() => { onSent && onSent(); onClose(); }, 800); }, 900);
  };

  /* Suggestion contacts — those NOT yet in the recipients list */
  const suggestionCandidates = [
    primaryContact   ? { contact: primaryContact,   email: primaryEmail,   isPrimary: true  } : null,
    secondaryContact ? { contact: secondaryContact, email: secondaryEmail, isPrimary: false } : null,
  ].filter(Boolean).filter(({ email }) =>
    !recipients.some((r) => r.email.toLowerCase() === (email || "").toLowerCase())
  );

  const deceased = caseDetails?.deceased || "Deceased";
  const quotId   = caseDetails?.quotationId || "";
  const subject  = `Service Summary Form – ${deceased} (${quotId})`;
  const msgPreview = `Dear Family,\n\nPlease find the Service Summary Form for the funeral arrangement of ${deceased} attached.\n\nKindly review all details and proceed to sign at your earliest convenience.\n\nIf you have any questions, please reach out to your Funeral Director directly.`;

  const InitialsAvatar = ({ name, size = 24, muted }) => (
    <span style={{
      width: size, height: size, borderRadius: "50%",
      background: muted ? "#F0F1F4" : "rgba(31,58,96,0.10)",
      color: muted ? "#B8C4D0" : "#1F3A60",
      display: "inline-flex", alignItems: "center", justifyContent: "center",
      fontSize: size * 0.38, fontWeight: 600, flexShrink: 0,
      letterSpacing: "0",
    }}>
      {(name || "?").split(/\s+/).slice(0, 2).map((w) => w[0]).join("").toUpperCase()}
    </span>
  );

  return (
    <div
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{
        position: "fixed", inset: 0, background: "rgba(10,18,30,0.50)",
        display: "flex", alignItems: "center", justifyContent: "center",
        zIndex: 300, padding: 24,
      }}
    >
      <div style={{
        width: "100%", maxWidth: 548, background: "#FFFFFF",
        borderRadius: 16, boxShadow: "0 24px 56px -12px rgba(10,18,30,0.30)",
        display: "flex", flexDirection: "column", overflow: "hidden",
      }}>

        {/* ── Header ── */}
        <div style={{
          display: "flex", alignItems: "center", justifyContent: "space-between",
          padding: "18px 24px", borderBottom: "1px solid #F0F1F4",
        }}>
          <span style={{ fontSize: 16, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.25px" }}>
            Email Service Summary Form
          </span>
          <button onClick={onClose} style={{ background: "transparent", border: "none", cursor: "pointer", color: "#9CA8B8", padding: 4, display: "flex" }}>
            <SerIcons.Close size={20} />
          </button>
        </div>

        {/* ── Recipient chips + input ── */}
        <div
          onClick={() => inputRef.current?.focus()}
          style={{
            padding: "10px 24px", borderBottom: "1px solid #F0F1F4",
            display: "flex", flexWrap: "wrap", alignItems: "center", gap: 6,
            minHeight: 52, cursor: "text",
          }}
        >
          <span style={{ fontSize: 12, color: "#9CA8B8", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.07em", marginRight: 4, flexShrink: 0 }}>
            To
          </span>
          {recipients.map((r) => (
            <span key={r.key} style={{
              display: "inline-flex", alignItems: "center", gap: 5,
              padding: "4px 8px 4px 8px",
              background: "#EEF2F8", border: "1px solid #C8D8EE",
              borderRadius: 20, fontSize: 13, color: "#1F3A60",
            }}>
              <InitialsAvatar name={r.name} size={18} />
              <span style={{ fontWeight: 500 }}>{r.name !== r.email ? r.name : ""}</span>
              {r.name !== r.email &&
                <span style={{ fontSize: 11, color: "#6B7A8F" }}>{r.email}</span>
              }
              {r.name === r.email &&
                <span style={{ fontSize: 13 }}>{r.email}</span>
              }
              <button
                onClick={(e) => { e.stopPropagation(); removeRecipient(r.key); }}
                style={{ background: "transparent", border: "none", cursor: "pointer", color: "#9CA8B8", padding: "0 2px", display: "flex", marginLeft: 2 }}
              >
                <SerIcons.Close size={12} />
              </button>
            </span>
          ))}
          <input
            ref={inputRef}
            type="email"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={handleInputKeyDown}
            onBlur={commitInput}
            placeholder={recipients.length === 0 ? "Type an email address…" : ""}
            style={{
              border: "none", outline: "none", fontSize: 13,
              color: "#1F3A60", flex: "1 1 120px", minWidth: 80,
              background: "transparent", fontFamily: "inherit",
              letterSpacing: "-0.1px", padding: "2px 0",
            }}
          />
        </div>

        {/* ── Quick-add suggestions ── */}
        {(suggestionCandidates.length > 0 || addEmailFor) && (
          <div style={{ padding: "10px 24px", borderBottom: "1px solid #F0F1F4", display: "flex", flexDirection: "column", gap: 8 }}>
            {!addEmailFor && suggestionCandidates.length > 0 && (
              <span style={{ fontSize: 11, color: "#9CA8B8", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.07em" }}>Quick add</span>
            )}
            {!addEmailFor && (
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {suggestionCandidates.map(({ contact, email, isPrimary }) => (
                  email ? (
                    /* Has email — clickable chip */
                    <button
                      key={contact.id}
                      onClick={() => addRecipient(contact.name, email, contact.id)}
                      style={{
                        all: "unset", cursor: "pointer",
                        display: "inline-flex", alignItems: "center", gap: 7,
                        padding: "5px 10px", borderRadius: 8,
                        background: "#F4F7FB", border: "1px solid #DDE6F0",
                        fontSize: 13, transition: "background 120ms",
                      }}
                      onMouseEnter={(e) => e.currentTarget.style.background = "#E8EFF8"}
                      onMouseLeave={(e) => e.currentTarget.style.background = "#F4F7FB"}
                    >
                      <InitialsAvatar name={contact.name} size={22} />
                      <span style={{ color: "#1F3A60", fontWeight: 500 }}>{contact.name}</span>
                      <span style={{ fontSize: 11, color: "#6B7A8F" }}>{email}</span>
                      <SerIcons.Plus size={14} color="#6B7A8F" />
                    </button>
                  ) : (
                    /* No email — disabled chip + "Add email" */
                    <span key={contact.id} style={{
                      display: "inline-flex", alignItems: "center", gap: 7,
                      padding: "5px 10px", borderRadius: 8,
                      background: "#F8F9FB", border: "1px dashed #DDE3EA",
                      fontSize: 13, color: "#9CA8B8",
                    }}>
                      <InitialsAvatar name={contact.name} size={22} muted />
                      <span>{contact.name}</span>
                      <span style={{ fontSize: 11 }}>— No email added</span>
                      <button
                        onClick={() => setAddEmailFor({ contactId: contact.id, name: contact.name })}
                        style={{
                          all: "unset", cursor: "pointer",
                          fontSize: 12, color: "#4A6E9A", fontWeight: 600,
                          textDecoration: "underline", textUnderlineOffset: 2, marginLeft: 2,
                        }}
                      >Add email →</button>
                    </span>
                  )
                ))}
              </div>
            )}

            {/* "Add email" inline mini-form */}
            {addEmailFor && (
              <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <span style={{ fontSize: 13, color: "#1F3A60", fontWeight: 500 }}>
                  Add email for {addEmailFor.name}
                </span>
                <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
                  <input
                    type="email"
                    value={addEmailInput}
                    onChange={(e) => setAddEmailInput(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === "Enter") handleSaveAndAddEmail();
                      if (e.key === "Escape") { setAddEmailFor(null); setAddEmailInput(""); }
                    }}
                    placeholder="name@example.com"
                    autoFocus
                    style={{
                      flex: 1, height: 38, padding: "0 12px",
                      border: "1.5px solid #1F3A60", borderRadius: 7, outline: "none",
                      fontFamily: "inherit", fontSize: 13, color: "#1F3A60", background: "#FFFFFF",
                    }}
                  />
                  <Button
                    variant="primary-navy" size="sm"
                    onClick={handleSaveAndAddEmail}
                    disabled={!addEmailInput.includes("@")}
                  >Save & Add</Button>
                  <button
                    onClick={() => { setAddEmailFor(null); setAddEmailInput(""); }}
                    style={{ all: "unset", cursor: "pointer", fontSize: 12, color: "#9CA8B8", padding: "0 4px" }}
                  >Cancel</button>
                </div>
                <span style={{ fontSize: 11, color: "#9CA8B8" }}>
                  This email will be saved to {addEmailFor.name}'s contact record.
                </span>
              </div>
            )}
          </div>
        )}

        {/* ── Subject + message preview + attachment ── */}
        <div style={{ padding: "16px 24px", borderBottom: "1px solid #F0F1F4", display: "flex", flexDirection: "column", gap: 12 }}>
          <div style={{ display: "flex", gap: 12, alignItems: "baseline" }}>
            <span style={{ fontSize: 12, color: "#9CA8B8", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.07em", width: 58, flexShrink: 0 }}>Subject</span>
            <span style={{ fontSize: 13, color: "#1F3A60", letterSpacing: "-0.1px" }}>{subject}</span>
          </div>
          <div style={{
            background: "#F8F9FB", border: "1px solid #ECEEF2", borderRadius: 8,
            padding: "12px 14px", fontSize: 13, color: "#574F40",
            lineHeight: "22px", letterSpacing: "-0.1px", whiteSpace: "pre-line",
          }}>
            {msgPreview}
          </div>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "7px 12px", borderRadius: 6,
            background: "#EEF3FB", border: "1px solid #CCDAED",
            alignSelf: "flex-start",
          }}>
            <SerIcons.Document size={14} color="#4A6E9A" />
            <span style={{ fontSize: 12, color: "#4A6E9A", fontWeight: 500, letterSpacing: "-0.05px" }}>
              Service_Summary_{quotId}.pdf
            </span>
          </div>
        </div>

        {/* ── Footer ── */}
        <div style={{
          padding: "14px 24px",
          display: "flex", justifyContent: "space-between", alignItems: "center",
        }}>
          <button onClick={onClose} style={{ all: "unset", cursor: "pointer", fontSize: 13, color: "#6B7A8F", fontWeight: 500 }}>
            Cancel
          </button>
          <Button
            variant="primary-navy" size="md"
            icon={<SerIcons.Mail size={18} />}
            onClick={handleSend}
            disabled={recipients.length === 0 || sending}
          >
            {sent ? "Sent ✓" : sending ? "Sending…" : "Send Service Summary Form"}
          </Button>
        </div>
      </div>
    </div>
  );
}

/* ══════════════════════════════════════════════════════
   ServiceSummaryPdfScreen
   Full-screen PDF viewer with sticky action panel.
   ══════════════════════════════════════════════════════ */
function ServiceSummaryPdfScreen({
  caseDetails,
  serviceData,
  contacts,
  selectedPackage,
  selectedCasket,
  selectedAddOns = [],
  addOnTotal = 0,
  notes = "",
  confirmationStatus = "awaiting",
  generatedAt,
  confirmedAt,
  backLabel = "Back",
  onBack,
  onSign,
  onEdit,
  onSendToCustomer,
  onCancelCase,
  onUpdateContact,
  appliedCoupon = null,
}) {
  const [showEmailOverlay, setShowEmailOverlay] = React.useState(false);
  const [copySuccess,      setCopySuccess]      = React.useState(false);
  const [showMore,         setShowMore]         = React.useState(false);
  const [signingState,     setSigningState]     = React.useState(null);
  // null | "redirecting" | "signing" | "syncing"
  const moreRef = React.useRef(null);

  React.useEffect(() => {
    if (!showMore) return;
    const h = (e) => { if (moreRef.current && !moreRef.current.contains(e.target)) setShowMore(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, [showMore]);

  const handleSign = () => {
    setSigningState("redirecting");
    setTimeout(() => {
      setSigningState("signing");
      setTimeout(() => {
        setSigningState("syncing");
        setTimeout(() => {
          setSigningState(null);
          onSign && onSign();
        }, 1200);
      }, 2200);
    }, 900);
  };

  const handleDownloadPdf = () => {
    const paperEl = document.getElementById("ser-pdf-paper");
    if (!paperEl) { window.print(); return; }
    const printWin = window.open("", "_blank", "width=900,height=900");
    if (!printWin) return;

    const qid = caseDetails?.quotationId || "";

    printWin.document.write(`<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Service Summary Form — ${qid}</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400&display=swap" rel="stylesheet">
  <style>
    *, *::before, *::after { box-sizing: border-box; }
    html, body {
      margin: 0; padding: 0;
      font-family: Inter, -apple-system, sans-serif;
      background: #FFFFFF;
      -webkit-print-color-adjust: exact;
      print-color-adjust: exact;
    }

    @media print {
      @page {
        margin: 10mm 0;
        size: A4;
      }

      /* Page 1 only: no top margin so blue cover starts flush */
      @page :first {
        margin-top: 0;
      }

      /* Paper card chrome — remove on print */
      #ser-pdf-paper {
        border: none !important;
        border-radius: 0 !important;
        box-shadow: none !important;
        overflow: visible !important;
      }

      /* Cover: bottom cushion before body begins */
      .pdf-cover {
        padding-bottom: 20px !important;
      }

      /* Sections: override inline React styles */
      .pdf-section {
        margin-top: 20px !important;
        padding-top: 20px !important;
      }

      /* First section: flush — no extra top space above signed banner */
      .pdf-section-first {
        margin-top: 0px !important;
        padding-top: 0px !important;
        break-inside: auto;
        page-break-inside: auto;
        orphans: 4;
        widows: 4;
      }

      /* Section titles: stay with their first content row */
      .pdf-section-title {
        break-after: avoid;
        page-break-after: avoid;
        margin-bottom: 28px !important;
        orphans: 4;
        widows: 4;
      }

      /* Field grids: more vertical breathing room between rows */
      .pdf-grid {
        row-gap: 12px !important;
      }

      /* Pricing box: never split across pages */
      .pdf-pricing-box {
        break-inside: avoid;
        page-break-inside: avoid;
      }
    }
  </style>
</head>
<body>
  ${paperEl.outerHTML}
  <script>
    window.onload = function() { setTimeout(function() { window.print(); }, 600); };
  </script>
</body>
</html>`);
    printWin.document.close();
  };

  const handleCopyLink = () => {
    const signingUrl = `https://serenity.odoo.com/sign/${caseDetails?.quotationId || ""}`;
    try { navigator.clipboard.writeText(signingUrl); } catch (_) {}
    setCopySuccess(true);
    setTimeout(() => setCopySuccess(false), 2800);
  };

  const isSigned = confirmationStatus === "confirmed" || confirmationStatus === "confirmed_updated";

  return (
    <div style={{ minHeight: "calc(100vh - 84px)", background: "#F4F2EE" }}>

      {/* ── Odoo Signing Overlay ─────────────────────────── */}
      {signingState && (
        <div style={{
          position: "fixed", inset: 0, background: "rgba(10,18,30,0.75)",
          display: "flex", alignItems: "center", justifyContent: "center",
          zIndex: 200, animation: "fadeIn 200ms ease-out",
        }}>
          <div style={{
            background: "#FFFFFF", borderRadius: 16,
            padding: "48px 52px", maxWidth: 440, width: "100%",
            boxShadow: "0 24px 48px rgba(0,0,0,0.22)",
            textAlign: "center", display: "flex", flexDirection: "column", gap: 24,
          }}>
            {/* Spinner */}
            <div style={{ position: "relative", width: 64, height: 64, margin: "0 auto" }}>
              <div style={{
                position: "absolute", inset: 0, borderRadius: "50%",
                border: "3px solid #E5E7EB", borderTopColor: "#1F3A60",
                animation: "seros-spin 0.9s linear infinite",
              }} />
              <span style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
                <SerIcons.Document size={24} color="#1F3A60" />
              </span>
            </div>

            <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
              <SigningStep label="Redirecting to Odoo signing portal…"          state={signingState === "redirecting" ? "active" : "done"} />
              <SigningStep label="Customer reviewing and signing in Odoo…"       state={signingState === "signing" ? "active" : signingState === "redirecting" ? "pending" : "done"} />
              <SigningStep label="Syncing confirmation status back to FD App…"   state={signingState === "syncing" ? "active" : "pending"} />
            </div>

            <p style={{ margin: 0, fontSize: 12, color: "#9CA8B8", letterSpacing: "-0.05px" }}>
              {signingState === "redirecting" && "Opening Odoo digital signing portal…"}
              {signingState === "signing"     && "Customer is signing the Service Summary Form in Odoo…"}
              {signingState === "syncing"     && "Signature confirmed — syncing back to FD App…"}
            </p>
          </div>
        </div>
      )}

      {/* ── Sticky Action Header ─────────────────────────── */}
      <div style={{
        position: "sticky", top: 84, zIndex: 50,
        background: "#FFFFFF", borderBottom: "1px solid #E5E7EB",
        boxShadow: "0 1px 4px rgba(15,23,42,0.05)",
      }}>
        <div style={{
          maxWidth: 1440, margin: "0 auto", padding: "0 48px",
          display: "flex", alignItems: "center", gap: 14, height: 68,
        }}>
          {/* Left */}
          <Button
            variant="outline" size="sm"
            icon={<SerIcons.ChevronLeft size={13} color="#574F40" />}
            onClick={onBack}
            style={{ color: "#574F40", flexShrink: 0 }}>
            {backLabel}
          </Button>
          <div style={{ width: 1, height: 28, background: "#E5E7EB", flexShrink: 0 }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.15px" }}>
              Service Summary Form
            </div>
            <div style={{ fontSize: 11, color: "#9CA8B8" }}>
              {caseDetails?.quotationId} · {caseDetails?.deceased}
            </div>
          </div>

          {/* Right: unified toolbar — consistent across all states */}
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>

            <Button
              variant="outline" size="sm"
              icon={<SerIcons.Mail size={18} />}
              onClick={() => setShowEmailOverlay(true)}
              style={{ flexShrink: 0 }}>
              Send Email
            </Button>

            <Button
              variant="outline" size="sm"
              icon={<SerIcons.Link size={16} />}
              onClick={handleCopyLink}
              disabled={isSigned}
              style={{ flexShrink: 0 }}>
              {copySuccess ? "Copied ✓" : "Copy Signing Link"}
            </Button>

            <Button
              variant="primary-navy" size="sm"
              iconRight={<SerIcons.Arrow size={14} />}
              onClick={handleSign}
              disabled={isSigned}
              style={{ minWidth: 120 }}>
              Sign in Odoo
            </Button>

          </div>
        </div>

        {/* Sub-bar — status-aware */}
        <div style={{
          maxWidth: 1440, margin: "0 auto", padding: "0 48px 10px",
          display: "flex", alignItems: "center", gap: 6,
          fontSize: 11, color: "#B8C4D0",
        }}>
          <SerIcons.Building size={11} color="#B8C4D0" />
          <span>
            {isSigned
              ? "Service Summary Form · Generated by FD App · Digitally signed via Odoo"
              : "Service Summary Form · Generated by FD App · Ready for customer review and digital signature in Odoo"
            }
          </span>
          {isSigned ? (
            <span style={{ marginLeft: 8, display: "inline-flex", alignItems: "center", gap: 4, color: "#5B7D4F" }}>
              <span style={{ width: 5, height: 5, borderRadius: "50%", background: "#5B7D4F", display: "inline-block" }} />
              Signed &amp; Confirmed
            </span>
          ) : (
            <span style={{ marginLeft: 8, display: "inline-flex", alignItems: "center", gap: 4, color: "#9A6B1F" }}>
              <span style={{ width: 5, height: 5, borderRadius: "50%", background: "#E8A832", display: "inline-block" }} />
              Awaiting signature
            </span>
          )}
        </div>
      </div>

      {/* ── Document area ────────────────────────────────── */}
      <div style={{ maxWidth: 1000, margin: "0 auto", padding: "36px 40px 80px" }}>
        {/* Page label row */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10, marginBottom: 20 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <SerIcons.Document size={14} color="#9CA8B8" />
            <span style={{ fontSize: 12, color: "#9CA8B8", letterSpacing: "-0.05px" }}>
              Service Summary Form · {caseDetails?.quotationId}
              {isSigned ? " · Signed document" : " · Review before signing"}
            </span>
          </div>
          {/* Download PDF — shown once signed */}
          {isSigned && (
            <button
              onClick={handleDownloadPdf}
              onMouseEnter={(e) => {
                e.currentTarget.style.background = "#1F3A60";
                e.currentTarget.style.color = "#FFFFFF";
                e.currentTarget.style.borderColor = "#1F3A60";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.background = "#FFFFFF";
                e.currentTarget.style.color = "#1F3A60";
                e.currentTarget.style.borderColor = "#E5E7EB";
              }}
              style={{
                all: "unset", cursor: "pointer",
                display: "inline-flex", alignItems: "center", gap: 7,
                padding: "8px 16px", borderRadius: 9999,
                background: "#FFFFFF",
                border: "1px solid #E5E7EB",
                boxShadow: "0 2px 8px rgba(15,23,42,0.08)",
                fontSize: 13, fontWeight: 500, color: "#1F3A60",
                letterSpacing: "-0.1px",
                fontFamily: "inherit",
                transition: "background 140ms, color 140ms, border-color 140ms",
                flexShrink: 0,
              }}
            >
              <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ flexShrink: 0 }}>
                <path d="M7 1v8M4 6.5l3 3 3-3M2 11.5h10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
              Save as PDF
            </button>
          )}
        </div>

        {/* Paper frame */}
        <div id="ser-pdf-paper" style={{
          background: "#FFFFFF",
          border: "1px solid #DDD9D1",
          borderRadius: 12, overflow: "hidden",
          boxShadow: "0 4px 24px rgba(15,23,42,0.08), 0 1px 4px rgba(15,23,42,0.04)",
        }}>
          <PdfDocumentContent
            caseDetails={caseDetails}
            serviceData={serviceData}
            contacts={contacts}
            selectedPackage={selectedPackage}
            selectedCasket={selectedCasket}
            selectedAddOns={selectedAddOns}
            addOnTotal={addOnTotal}
            notes={notes}
            generatedAt={generatedAt}
            isSigned={isSigned}
            confirmedAt={confirmedAt}
            appliedCoupon={appliedCoupon}
          />
        </div>
      </div>

      {/* ── Email Share Overlay ─────────────────────────── */}
      {showEmailOverlay && (
        <EmailShareOverlay
          caseDetails={caseDetails}
          serviceData={serviceData}
          contacts={contacts}
          onClose={() => setShowEmailOverlay(false)}
          onUpdateContact={onUpdateContact}
          onSent={() => {}}
        />
      )}

      {/* ── Copy Signing Link Snackbar ─────────────────── */}
      <div style={{
        position: "fixed", bottom: 32, left: "50%",
        transform: `translateX(-50%) translateY(${copySuccess ? "0" : "16px"})`,
        opacity: copySuccess ? 1 : 0,
        pointerEvents: "none",
        transition: "opacity 200ms ease, transform 200ms ease",
        background: "#1F3A60", color: "#FFFFFF",
        padding: "11px 20px", borderRadius: 40,
        fontSize: 13, fontWeight: 500, letterSpacing: "-0.1px",
        boxShadow: "0 8px 24px rgba(10,18,30,0.22)",
        display: "flex", alignItems: "center", gap: 8,
        zIndex: 500,
        whiteSpace: "nowrap",
      }}>
        <SerIcons.Check size={14} color="#8FCF7E" />
        Signing link copied
      </div>
    </div>
  );
}

/* ══════════════════════════════════════════════════════
   ThankYouScreen
   Post-signing confirmation + next steps
   ══════════════════════════════════════════════════════ */
function ThankYouScreen({
  caseDetails,
  confirmedAt,
  selectedPackage,
  selectedCasket,
  selectedAddOns = [],
  addOnTotal = 0,
  appliedCoupon = null,
  onReturnToCases,
  onViewSignedForm,
  onViewCase,
  onEditCase,
  onStartNewCase,
}) {
  const pkgPrice         = selectedPackage?.price || 0;
  const casketUpgrade    = selectedCasket ? (selectedCasket.included ? 0 : (selectedCasket.upgrade || 0)) : 0;
  const subtotal         = pkgPrice + casketUpgrade + addOnTotal;
  const coupons          = Array.isArray(appliedCoupon) ? appliedCoupon : (appliedCoupon ? [appliedCoupon] : []);
  const discountCoupons  = coupons.filter((c) => c.type === "discount");
  const couponAmt        = discountCoupons.reduce((sum, c) => sum + (c.amount || 0), 0);
  const adjustedSubtotal = Math.max(0, subtotal - couponAmt);
  const gst              = adjustedSubtotal * 0.09;
  const finalTotal       = adjustedSubtotal * 1.09;

  const confDate = confirmedAt ? pdfDateLong(confirmedAt)  : pdfDateLong(new Date().toISOString());
  const confTime = confirmedAt ? pdfTime(confirmedAt)      : pdfTime(new Date().toISOString());

  return (
    <div style={{ minHeight: "calc(100vh - 84px)", background: "#FAFAFA", display: "flex", justifyContent: "center", padding: "60px 48px 80px" }}>
      <div style={{ maxWidth: 620, width: "100%", display: "flex", flexDirection: "column", gap: 28 }}>

        {/* ── Success header ────────────────────────────── */}
        <div style={{ textAlign: "center", display: "flex", flexDirection: "column", alignItems: "center", gap: 20 }}>
          {/* Check circle */}
          <div style={{
            width: 76, height: 76, borderRadius: "50%",
            background: "linear-gradient(135deg, #EBF3E6 0%, #D4E8CC 100%)",
            border: "2px solid #C4D9B8",
            display: "flex", alignItems: "center", justifyContent: "center",
          }}>
            <SerIcons.CheckCircle size={34} color="#5B7D4F" />
          </div>

          <div>
            <h1 style={{ fontSize: 28, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.5px", margin: "0 0 10px" }}>
              Service Summary Form Signed
            </h1>
            <p style={{ fontSize: 15, color: "#6B7A8F", margin: 0, letterSpacing: "-0.15px", lineHeight: "24px" }}>
              The arrangement has been confirmed and signed by the family representative.
              <br />Serenity is here to guide every step forward.
            </p>
          </div>

          {/* Confirmation timestamp */}
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 8,
            padding: "10px 20px", borderRadius: 9999,
            background: "#E8F0E4", border: "1px solid #C4D9B8",
            fontSize: 13, fontWeight: 500, color: "#5B7D4F",
          }}>
            <SerIcons.Check size={14} color="#5B7D4F" />
            Confirmed via Odoo · {confTime} · {confDate}
          </div>
        </div>

        {/* ── Confirmed arrangement card ─────────────────── */}
        <div style={{ background: "#FFFFFF", border: "1px solid #E5E7EB", borderRadius: 12, overflow: "hidden" }}>
          <div style={{ padding: "14px 24px", borderBottom: "1px solid #F0F1F4", display: "flex", alignItems: "center", gap: 8 }}>
            <SerIcons.CheckCircle size={16} color="#5B7D4F" />
            <span style={{ fontSize: 14, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.15px" }}>Confirmed Arrangement</span>
          </div>
          <div style={{ padding: "20px 24px" }}>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "14px 28px", marginBottom: 20 }}>
              <TYField label="Case Number"         value={caseDetails?.quotationId} />
              <TYField label="Deceased"            value={caseDetails?.deceased} />
              <TYField label="Family Representative" value={caseDetails?.contact} />
              <TYField label="Package"             value={selectedPackage?.name} />
              {selectedCasket && <TYField label="Casket" value={selectedCasket.name} />}
            </div>
            <div style={{ borderTop: "1px solid #F0F1F4", paddingTop: 18 }}>
              {/* Breakdown rows */}
              <div style={{ display: "flex", flexDirection: "column", gap: 6, marginBottom: 14 }}>
                {couponAmt > 0 && (
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                    <span style={{ fontSize: 12, color: "#9CA8B8" }}>Subtotal (before GST)</span>
                    <span style={{ fontSize: 13, color: "#9CA8B8", fontFeatureSettings: "'tnum'" }}>{formatPrice(subtotal)}</span>
                  </div>
                )}
                {discountCoupons.map((c) => (
                  <div key={c.code} style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                    <span style={{ fontSize: 12, color: "#9A6B1F" }}>Coupon ({c.code})</span>
                    <span style={{ fontSize: 13, color: "#9A6B1F", fontFeatureSettings: "'tnum'" }}>−{formatPrice(c.amount || 0)}</span>
                  </div>
                ))}
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                  <span style={{ fontSize: 12, color: "#9CA8B8" }}>{couponAmt > 0 ? "Adjusted Subtotal" : "Subtotal (before GST)"}</span>
                  <span style={{ fontSize: 13, color: "#9CA8B8", fontFeatureSettings: "'tnum'" }}>{formatPrice(adjustedSubtotal)}</span>
                </div>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                  <span style={{ fontSize: 12, color: "#9CA8B8" }}>GST (9%)</span>
                  <span style={{ fontSize: 13, color: "#9CA8B8", fontFeatureSettings: "'tnum'" }}>{formatPrice(gst)}</span>
                </div>
              </div>
              {/* Total row */}
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", borderTop: "1px solid #F0F1F4", paddingTop: 12 }}>
                <div>
                  <div style={{ fontSize: 13, color: "#6B7A8F" }}>Total Arrangement</div>
                  <div style={{ fontSize: 11, color: "#9CA8B8", marginTop: 2 }}>All prices in SGD · incl. 9% GST</div>
                </div>
                <span style={{ fontSize: 26, fontWeight: 700, color: "#1F3A60", letterSpacing: "-0.5px", fontFeatureSettings: "'tnum'" }}>
                  {formatPrice(finalTotal)}
                </span>
              </div>
            </div>
          </div>
        </div>

        {/* ── Next steps ────────────────────────────────── */}
        <div style={{ background: "#FFFFFF", border: "1px solid #E5E7EB", borderRadius: 12, overflow: "hidden" }}>
          <div style={{ padding: "14px 24px", borderBottom: "1px solid #F0F1F4" }}>
            <span style={{ fontSize: 14, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.15px" }}>Next Steps</span>
          </div>
          <div style={{ padding: "20px 24px", display: "flex", flexDirection: "column", gap: 14 }}>
            <TYNextStep icon={<SerIcons.Document size={14} />}
              text="The signed Service Summary Form has been saved to this case and is available for reference at any time." />
            <TYNextStep icon={<SerIcons.Mail size={14} />}
              text="Send the signed copy to the family representative's email or WhatsApp for their records." />
            <TYNextStep icon={<SerIcons.Building size={14} />}
              text="Arrangement details have been synced to Odoo. The operations team will be notified to begin preparation." />
            <TYNextStep icon={<SerIcons.CheckCircle size={14} />}
              text="You may now coordinate logistics, assign personnel, and begin operational preparation for the service." />
          </div>
        </div>

        {/* ── Actions ───────────────────────────────────── */}
        <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>

          {/* ① Primary: view the signed document */}
          <Button
            variant="primary-navy" size="md"
            icon={<SerIcons.Document size={18} />}
            style={{ width: "100%" }}
            onClick={onViewSignedForm}>
            View Signed Form
          </Button>

          {/* ② Case management: read-only details + edit mode */}
          <div style={{ display: "flex", gap: 10 }}>
            <Button
              variant="outline" size="md"
              icon={<SerIcons.CheckCircle size={16} />}
              style={{ flex: 1 }}
              onClick={onViewCase}>
              View Case
            </Button>
            <Button
              variant="outline" size="md"
              icon={<SerIcons.Edit size={16} />}
              style={{ flex: 1 }}
              onClick={onEditCase}>
              Edit Case
            </Button>
          </div>

          {/* Divider — separates case actions from navigation */}
          <div style={{ height: 1, background: "#ECEEF2", margin: "4px 0" }} />

          {/* ③ Navigation — low-emphasis text links */}
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 4 }}>
            <button
              onClick={onStartNewCase}
              onMouseEnter={(e) => { e.currentTarget.style.color = "#1F3A60"; e.currentTarget.style.background = "#F4F6F9"; }}
              onMouseLeave={(e) => { e.currentTarget.style.color = "#6B7A8F"; e.currentTarget.style.background = "transparent"; }}
              style={{
                all: "unset", cursor: "pointer",
                fontSize: 13, fontWeight: 500, color: "#6B7A8F", letterSpacing: "-0.1px",
                padding: "6px 12px", borderRadius: 6, fontFamily: "inherit",
                transition: "color 120ms, background 120ms",
              }}>
              Start New Case
            </button>
            <span style={{ width: 3, height: 3, borderRadius: "50%", background: "#D1D5DB", flexShrink: 0 }} />
            <button
              onClick={onReturnToCases}
              onMouseEnter={(e) => { e.currentTarget.style.color = "#1F3A60"; e.currentTarget.style.background = "#F4F6F9"; }}
              onMouseLeave={(e) => { e.currentTarget.style.color = "#6B7A8F"; e.currentTarget.style.background = "transparent"; }}
              style={{
                all: "unset", cursor: "pointer",
                fontSize: 13, fontWeight: 500, color: "#6B7A8F", letterSpacing: "-0.1px",
                padding: "6px 12px", borderRadius: 6, fontFamily: "inherit",
                transition: "color 120ms, background 120ms",
              }}>
              Return to My Cases
            </button>
          </div>

        </div>

        {/* Closing note */}
        <p style={{ textAlign: "center", fontSize: 13, color: "#B8C4D0", letterSpacing: "-0.1px", lineHeight: "20px", margin: 0 }}>
          Thank you for conducting this consultation with care and professionalism.<br />
          Serenity is here to support the family through every step ahead.
        </p>

      </div>
    </div>
  );
}

function TYField({ label, value }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
      <span style={{ fontSize: 11, color: "#9CA8B8", fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.07em" }}>{label}</span>
      <span style={{ fontSize: 14, fontWeight: 500, color: "#1F3A60", letterSpacing: "-0.15px" }}>{value || "—"}</span>
    </div>
  );
}

function TYNextStep({ icon, text }) {
  return (
    <div style={{ display: "flex", gap: 12, alignItems: "flex-start" }}>
      <span style={{
        width: 30, height: 30, borderRadius: 8, background: "#F0F4F8",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        flexShrink: 0, color: "#6B7A8F",
      }}>
        {icon}
      </span>
      <p style={{ fontSize: 13, color: "#574F40", margin: 0, lineHeight: "21px", letterSpacing: "-0.1px", paddingTop: 5 }}>
        {text}
      </p>
    </div>
  );
}

Object.assign(window, { ServiceSummaryPdfScreen, ThankYouScreen, PdfDocumentContent });
