/* SER-OS — Service Summary
   ──────────────────────────────────────────────────────────────────
   Odoo Sales Order–aligned data capture. Each input maps 1:1 to an
   Odoo res.partner / sale.order field — see the trailing comments
   on `SERVICE_DATA_BLANK` for the mapping table.

   Tab structure mirrors Odoo (with Family Tree kept as its own tab
   to avoid an excessively long Care Information page):

     • Care Information           — always
     • Family Tree                — Fountains only
     • Funeral Arrangement        — always (incl. Disposition & Final Resting)
     • Pastoral Care              — Serenity + (Christian or Catholic)
   ────────────────────────────────────────────────────────────────── */

const SERVICE_TABS = [
{ id: "care", label: "Care Information", visible: () => true },
{ id: "tree", label: "Family Tree", visible: ({ workspace }) => workspace === "fountains" },
{ id: "funeral", label: "Funeral Arrangement", visible: () => true },
{ id: "pastoral", label: "Pastoral Care", visible: ({ workspace, religion }) =>
  workspace === "serenity" && /christian|catholic/i.test(religion || "") }];


function visibleTabs(ctx) {return SERVICE_TABS.filter((t) => t.visible(ctx));}

/* ────────────────────────────────────────────────────
   Empty data shape — Odoo field mapping in comments.
   ──────────────────────────────────────────────────── */
function makeBlankServiceData() {
  const today = new Date();
  const todayISO = today.toISOString().slice(0, 10);
  const defaultEnd = new Date(today);
  defaultEnd.setDate(defaultEnd.getDate() + 2); // 3-day duration
  const defaultEndISO = defaultEnd.toISOString().slice(0, 10);
  return {
  /* ── Deceased Profile ──────────────────────────── */
  salutations: "", // sale.order → x_salutations  (Selection)
  deceasedName: "", // sale.order → x_deceased_name  (Char) *required
  gender: "", // sale.order → x_gender  (Selection: M / F / Prefer not to mention)
  maritalStatus: "", // sale.order → x_marital_status  (Selection S/M/D/W — Fountains)
  religion: "", // sale.order → x_religion_id  (Selection, brand-specific) *required
  dialect: "", // sale.order → x_dialect  (Selection — Fountains)

  /* ── Life Information ──────────────────────────── */
  dateOfDeath: todayISO, // sale.order → x_date_of_death  (Date) *required
  timeOfDeath: "", // sale.order → x_time_of_death  (Char/DateTime — paired with date)
  dateOfBirth: "", // res.partner → birthdate  (Date)
  age: "", // sale.order → x_age  (Integer)

  /* ── Preparation & Care ────────────────────────── */
  transferLocationType: "", // Hospital | Home | Hospice | Nursing Home | Coroner | Other
  transferLocationHospital: "", // when type = Hospital
  transferLocationHospice: "", // when type = Hospice
  transferLocationRemarks: "", // when type = Home | Nursing Home | Coroner | Other
  transferLocation: "", // legacy / computed display value
  embalmingOptions: [], // sale.order → x_embalming  (Multi-select)
  embalmingRemarks: "", // sale.order → x_embalming_remarks  (Text)

  /* ── Case Contacts (Many2one → res.partner) ────── */
  primaryRelationship: "", // sale.order → x_relationship_1  (Selection)
  primaryContactId: null, // sale.order → x_family_contact_1  (Many2one → res.partner)
  primaryContactEmail: "", // derived from contact email; editable override
  secondaryRelationship: "", // sale.order → x_relationship_2  (Selection)
  secondaryContactId: null, // sale.order → x_family_contact_2  (Many2one → res.partner)
  secondaryContactEmail: "", // derived from contact email; editable override

  /* ── Family Record — Fountains only ────────────── */
  survivingSpouse: "", // sale.order → x_surviving_spouse  (Char Y/N)
  survivingParents: "", // sale.order → x_surviving_parents  (Char Y/N)

  /* ── Family Tree — Fountains only ────────────── */
  family: {
    children: { son: 0, daughter: 0, sonInLaw: 0, daughterInLaw: 0 },
    siblings: {
      elderBrother: 0, youngerBrother: 0, elderSister: 0, youngerSister: 0,
      elderBrotherInLaw: 0, youngerBrotherInLaw: 0,
      elderSisterInLaw: 0, youngerSisterInLaw: 0
    },
    paternal: {
      elderGrandson: 0, grandson: 0, grandsonInLaw: 0,
      elderGranddaughterInLaw: 0, granddaughter: 0, granddaughterInLaw: 0,
      greatGrandson: 0
    },
    maternal: {
      grandson: 0, granddaughter: 0, granddaughterInLaw: 0,
      grandsonInLaw: 0, greatGrandson: 0
    }
  },

  /* ── Funeral Arrangement — Wake Details ────────── */
  wakeVenueType: "", // Parlour | Church | HDB | Others
  wakeVenueParlour: "", // when type = Parlour
  wakeVenueChurch: "", // when type = Church (Serenity only)
  wakeVenueRemarks: "", // when type = HDB | Others
  wakeVenue: "", // legacy / computed display value
  wakeStartDate: todayISO, // sale.order → x_wake_start_date  (Date)
  wakeEndDate: defaultEndISO, // sale.order → x_wake_end_date  (Date)
  wakeDuration: "3", // sale.order → x_wake_duration  (Integer days, default 3)
  visitingHours: "", // sale.order → x_visiting_hours  (Char)

  /* ── Funeral Arrangement — Final Resting Information ── */
  cremationOrBurial: "", // header — picks Cremation or Burial flow *required
  dispositionDate: "", // sale.order → x_cremation_date  (Date)
  cremationLocation: "", // sale.order → x_cremation_location  (Selection)
  burialLocation: "", // sale.order → x_burial_location  (Selection)
  restingArrangement: "", // sale.order → x_resting_arrangement  (Selection — Land/Sea/Columbarium/Home/Others)
  finalRestingLocation: "", // sale.order → x_final_resting_location  (Selection)
  finalRestingLocationOthers: "", // sale.order → x_final_resting_location_others  (Char — shown when arrangement or location = Others)
  finalRestingDate: "", // sale.order → x_final_resting_dt  (DateTime)
  prayerService: [], // sale.order → x_prayer_service  (Multi-select)
  prayerServiceOthers: "", // free-text when prayer service "others" is selected
  ancestorTabletLocation: "", // sale.order → x_ancestor_tablet_location  (Char — Fountains)
  jilingAnlingRemarks: "", // sale.order → x_jiling_anling_remarks  (Text — Fountains)
  dispositionRemarks: "", // sale.order → x_columbarium_remarks  (Text)

  /* ── Pastoral Care — Serenity + Christian/Catholic ── */
  church: "", // sale.order → x_church  (Char — Christian)
  pastor: "", // sale.order → x_pastor  (Char — Christian)
  memorialServiceDateTime: "", // sale.order → x_memorial_service_dt  (DateTime — Christian)
  parish: "", // sale.order → x_parish  (Char — Catholic)
  nightlyPrayersDateTime: "", // sale.order → x_nightly_prayers_dt  (DateTime — Catholic)
  churchMass: false, //sale.order → x_church_mass  (Boolean — Catholic)
  churchMassDetails: "", // sale.order → x_church_mass_details  (Char — Catholic)
  massDateTime: "" // sale.order → x_mass_dt  (DateTime — Catholic)
}; }
const SERVICE_DATA_BLANK = makeBlankServiceData();

/* ────────────────────────────────────────────────────
   Selection option lists — kept centralised so the
   ContactPicker / FormField select inputs stay in sync.
   ──────────────────────────────────────────────────── */
const SALUTATION_OPTIONS = ["Mr", "Mrs", "Mdm", "Miss", "Dr", "Others"];
const GENDER_OPTIONS = ["M", "F", "Prefer not to mention"];

const TRANSFER_LOCATION_TYPES = ["Hospital", "Home", "Hospice", "Nursing Home", "Coroner", "Other"];

const HOSPITAL_OPTIONS = [
  "Alexandra Hospital (AH)",
  "Changi General Hospital (CGH)",
  "Changi General Hospital (Integrated Building)",
  "Crawfurd Hospital",
  "Farrer Park Hospital",
  "Gleneagles Hospital",
  "Institute of Mental Health (IMH)",
  "KK Women's and Children's Hospital (KKH)",
  "Khoo Teck Puat Hospital (KTPH)",
  "Mount Alvernia Hospital",
  "Mount Elizabeth Hospital (Novena)",
  "Mount Elizabeth Hospital (Orchard)",
  "National Centre for Infectious Diseases (NCID)",
  "National University Hospital (NUH)",
  "Ng Teng Fong General Hospital (NTFGH)",
  "Parkway East Hospital",
  "Raffles Hospital",
  "Sengkang General Hospital (SKGH)",
  "Singapore General Hospital (Mortuary @ HSA)",
  "Singapore General Hospital (Ward)",
  "Tan Tock Seng Hospital (TTSH)",
  "Thomson Medical Centre",
  "Woodlands Hospital (WH)",
  "Yishun Community Hospital (YCH)",
  "Others",
];

const HOSPICE_OPTIONS = [
  "Assisi Hospice",
  "Dover Park Hospice",
  "Ren Ci Hospital",
  "St Andrew's Community Hospital",
  "St Luke's Hospital",
  "Thye Hua Kwan (THK)",
  "Others",
];

const WAKE_VENUE_TYPES = ["Parlour", "Church", "HDB", "Others"];
const WAKE_VENUE_TYPES_FOUNTAINS = ["Parlour", "HDB", "Others"];

const PARLOUR_OPTIONS = {
  serenity: [
    "AYS Remembrance Hall (AYS)",
    "Mount Vernon Sanctuary (MVS)",
    "Singapore Funeral Parlour (SFP)",
    "The Garden of Remembrance (TGOR)",
    "Woodlands Memorial (WM)",
    "Others",
  ],
  fountains: [
    "AYS Remembrance Hall (AYS)",
    "Mount Vernon Sanctuary (MVS)",
    "Singapore Funeral Parlour (SFP)",
    "Teochew Funeral Parlour",
    "Woodlands Memorial (WM)",
    "Others",
  ],
};

const CHURCH_OPTIONS = [
  "Church of Christ the King",
  "Church of Immaculate Heart of Mary",
  "Church of Our Lady of Lourdes",
  "Church of Our Lady Queen of Peace",
  "Church of St Anthony",
  "Church of St Francis Xavier",
  "Church of St Ignatius",
  "Church of St Mary of The Angels",
  "Church of St Stephen",
  "Church of St Teresa",
  "Church of the Epiphany",
  "Church of the Holy Cross",
  "Church of the Holy Spirit",
  "St. Joseph's Church (Bukit Timah)",
  "St. Joseph's Church (Victoria Street)",
  "Others",
];
const MARITAL_OPTIONS = [
{ value: "S", label: "Single" },
{ value: "M", label: "Married" },
{ value: "D", label: "Divorced" },
{ value: "W", label: "Widowed" }];

const DIALECT_OPTIONS = ["Hokkien", "Teochew", "Cantonese", "Hakka", "Hainanese", "Mandarin", "Other"];
const RELATIONSHIP_OPTIONS = [
  "Spouse",
  "Son", "Daughter",
  "Father", "Mother",
  "Brother", "Sister",
  "Son-in-Law", "Daughter-in-Law",
  "Grandson", "Granddaughter",
  "Relative", "Friend", "Other",
];

const CREMATION_LOCATIONS = {
  serenity:  ["Mandai Crematorium", "Mandai North Crematorium"],
  fountains: ["Mandai Crematorium", "Mandai North Crematorium", "Kong Meng San Phor Kark See Monastery (Bright Hill)", "Tse Tho Aum Temple (Sin Ming Drive)"],
};
const BURIAL_LOCATIONS = {
  serenity:  ["CCK Christian Cemetery", "CCK Lawn"],
  fountains: ["CCK Lawn", "CCK Chinese Cemetery"],
};
const RESTING_ARRANGEMENTS = ["Inland Scattering", "Sea Scattering", "Columbarium", "Home", "Others"];

/* Final Resting Location options — keyed by [arrangement][workspace].
   "both" applies to all workspaces; otherwise use workspace-specific key. */
const RESTING_LOCATIONS = {
  "Inland Scattering": {
    both: ["Garden of Peace (GOP)", "Garden of Serenity (GOS)", "Others"],
  },
  "Sea Scattering": {
    both: ["Changi Point Ferry Terminal (CPFT)", "Marina South Pier (MSP)", "Others"],
  },
  "Columbarium": {
    serenity: [
      "All Saints Memorial Chapel (Kovan)",
      "Choa Chu Kang Columbarium (CCK)",
      "Church of Christ the King (Ang Mo Kio)",
      "Church of Our Lady of Perpetual Succour (Siglap)",
      "Church of St Anthony (Woodlands)",
      "Church of St Francis of Assisi (Boon Lay)",
      "Church of St Francis Xavier (Serangoon)",
      "Church of St Ignatius (Farrer Road)",
      "Church of St Mary of the Angels (Bukit Batok)",
      "Church of St Michael (Serangoon)",
      "Church of St Teresa (Kampong Bahru)",
      "Church of the Holy Family (Katong)",
      "Church of the Holy Spirit (Upper Thomson)",
      "Church of the Holy Trinity (Tampines)",
      "Church of the Immaculate Heart of Mary (Kovan)",
      "Church of the Sacred Heart (Fort Canning)",
      "Faith Methodist Church (Queenstown)",
      "Mandai Columbarium (Mandai)",
      "Spiritual Grace Memorial Garden (Sembawang)",
      "St Anne's Church (Sengkang)",
      "St Joseph's Church (Bukit Timah)",
      "The Garden of Remembrance (CCK)",
      "Trinity Methodist Church (Serangoon)",
      "Woodlands Memorial (Woodlands)",
      "Others",
    ],
    fountains: [
      "Choa Chu Kang Columbarium (CCK)",
      "Kong Meng San Phor Kark See Monastery (Bright Hill)",
      "Mandai Columbarium (Mandai)",
      "Nirvana Garden Memorial (CCK)",
      "Tse Tho Aum Temple (Sin Ming Drive)",
      "Woodlands Memorial (Woodlands)",
      "Others",
    ],
  },
};

const PRAYER_SERVICE_OPTIONS = [
  { id: "interment_prayers", label: "Interment Prayers" },
  { id: "7th_day",           label: "7th Day Prayers" },
  { id: "49_days",           label: "49th Day Prayers" },
  { id: "others",            label: "Others" },
];

const EMBALMING_OPTIONS = [
  { id: "embalming_required",   label: "Embalming Required" },
  { id: "no_embalming",         label: "No Embalming" },
  { id: "infectious_case",      label: "Infectious Case Handling" },
  { id: "others",               label: "Others" },
];

/* ────────────────────────────────────────────────────
   Helpers (used by the sidebar partial-state preview)
   ──────────────────────────────────────────────────── */
function familyTreeTotals(family) {
  const sumObj = (o) => Object.values(o || {}).reduce((a, b) => a + (Number(b) || 0), 0);
  const children = sumObj(family?.children);
  const siblings = sumObj(family?.siblings);
  const grandchildren = sumObj(family?.paternal) + sumObj(family?.maternal);
  return { children, siblings, grandchildren };
}

function serviceSummaryFilled(d) {
  if (!d) return false;
  return !!(d.deceasedName || d.dateOfDeath || d.religion ||
  d.cremationOrBurial || d.wakeVenue || d.dispositionDate);
}

/* ────────────────────────────────────────────────────
   <ServiceSummaryScreen> — main screen
   ──────────────────────────────────────────────────── */
function ServiceSummaryScreen({
  caseDetails, workspace,
  serviceData, setServiceData,
  contacts = [], onCreateContact,
  selectedPackage, selectedCasket,
  selectedAddOns, addOnTotal, addOnCount,
  notes, setNotes,
  onEditCase, onJumpTo,
  onContinue,
  confirmationStatus, onSendForConfirmation, onViewPdf, onResend, onEditArrangement,
  amendmentSnapshot, onEnterEditMode, onFinalizeAmendment, onDiscardAmendment, onSendToCustomer,
  onSimulateSign, onSendSignedForm,
  appliedCoupon = null, onApplyCoupon, onRemoveCoupon,
}) {
  const tabs = visibleTabs({ workspace, religion: serviceData.religion || caseDetails?.religion });
  const [activeTab, setActiveTab] = React.useState(tabs[0]?.id || "care");

  // Fall back when the active tab disappears (e.g. workspace switch).
  React.useEffect(() => {
    if (!tabs.find((t) => t.id === activeTab)) setActiveTab(tabs[0]?.id);
  }, [workspace, serviceData.religion]); // eslint-disable-line react-hooks/exhaustive-deps

  const scrollRef = React.useRef(null);
  const onTabChange = (id) => {
    setActiveTab(id);
    if (scrollRef.current) scrollRef.current.scrollTo({ top: 0, behavior: "smooth" });
  };

  const update = (patch) => setServiceData({ ...serviceData, ...patch });

  return (
    <div style={{ display: "flex", alignItems: "stretch", minHeight: "calc(100vh - 84px)" }}>
      <main
        ref={scrollRef}
        style={{ flex: 1, minWidth: 0, background: "#FAFAFA", overflowY: "auto", overflowX: "hidden", display: "flex", flexDirection: "column" }}>
        
        <div style={{
          position: "sticky", top: 0, zIndex: 5,
          background: "#FAFAFA",
          paddingTop: 24, paddingLeft: 40, paddingRight: 40
        }}>
          <div style={{ maxWidth: 1100, margin: "0 auto" }}>
            {/* Confirmation / amendment status banners */}
            {caseDetails?.needType === "pre_need" && (
              <div style={{
                display: "flex", alignItems: "center", gap: 10,
                padding: "12px 16px", borderRadius: 10, marginBottom: 16,
                background: "#EEF2FF", border: "1px solid #C7D2FE",
              }}>
                <SerIcons.Star size={16} color="#4338CA" />
                <div>
                  <span style={{ fontSize: 14, fontWeight: 600, color: "#4338CA", letterSpacing: "-0.15px" }}>
                    Pre-Need Arrangement
                  </span>
                  <span style={{ fontSize: 14, fontWeight: 400, color: "#4338CA", letterSpacing: "-0.15px", marginLeft: 8 }}>
                    — The planee is still living. Fields capture preferred arrangements for future use.
                  </span>
                </div>
              </div>
            )}
            {(confirmationStatus === "confirmed" || confirmationStatus === "confirmed_updated") && (
              <div style={{
                display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
                padding: "12px 16px", borderRadius: 10, marginBottom: 16,
                background: "#EAF2E3", border: "1px solid #C4D9B8",
              }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <SerIcons.CheckCircle size={18} color="#5B7D4F" />
                  <span style={{ fontSize: 14, fontWeight: 500, color: "#5B7D4F", letterSpacing: "-0.15px" }}>
                    {confirmationStatus === "confirmed_updated"
                      ? "Confirmed (Updated) — this arrangement has been re-confirmed."
                      : "Confirmed — this arrangement has been signed by the customer."}
                  </span>
                </div>
                {onEnterEditMode && (
                  <Button variant="outline" size="sm" icon={<SerIcons.Edit size={16} />} onClick={onEnterEditMode}
                    style={{ flexShrink: 0, borderColor: "#9CAE82", color: "#5B7D4F" }}>
                    Enter Edit Mode
                  </Button>
                )}
              </div>
            )}
            {confirmationStatus === "amendment_draft" && (
              <div style={{
                display: "flex", alignItems: "center", gap: 10,
                padding: "12px 16px", borderRadius: 10, marginBottom: 16,
                background: "#E8EDF5", border: "1px solid #B8C8E0",
              }}>
                <SerIcons.Edit size={16} color="#2D4E7D" />
                <span style={{ fontSize: 14, fontWeight: 500, color: "#2D4E7D", letterSpacing: "-0.15px" }}>
                  Amendment Draft — changes here will be included in the updated arrangement.
                </span>
              </div>
            )}
            {(confirmationStatus === "awaiting" || confirmationStatus === "amended_awaiting") && (
              <div style={{
                padding: "12px 16px", borderRadius: 10, marginBottom: 16,
                background: "#FDF4E3", border: "1px solid #E8C98A",
                display: "flex", alignItems: "center", gap: 10,
              }}>
                <SerIcons.Clock size={18} color="#9A6B1F" />
                <span style={{ fontSize: 14, fontWeight: 500, color: "#9A6B1F", letterSpacing: "-0.15px" }}>
                  Awaiting customer confirmation — the arrangement has been sent for signing.
                </span>
              </div>
            )}

            <header style={{ marginBottom: 18 }}>
              <h1 style={{ font: "500 24px/32px Inter", letterSpacing: "0.07px", color: "#1F3A60", margin: 0 }}>Service Summary</h1>
              <p style={{ fontSize: 14, color: "#6B7A8F", letterSpacing: "-0.15px", margin: "4px 0 0" }}>
                Capture care details, family information, and arrangements. Jump between sections at any time.
              </p>
            </header>
            <div
              className="ser-tab-scroll"
              style={{
                display: "flex", gap: 3, overflowX: "auto",
                background: "#EEF2F7", borderRadius: 10, padding: 4,
                scrollbarWidth: "none", msOverflowStyle: "none",
                alignSelf: "flex-start",
              }}>
              <style>{`.ser-tab-scroll::-webkit-scrollbar { display: none; }`}</style>
              {tabs.map((t) =>
              <ServiceTabBtn
                key={t.id} label={t.label}
                isActive={activeTab === t.id}
                onClick={() => onTabChange(t.id)} />
              )}
            </div>
          </div>
        </div>

        <div style={{ flex: 1, padding: "24px 40px 80px" }}>
          <div style={{ maxWidth: 1100, margin: "0 auto" }}>
            {activeTab === "care" &&
            <CareTab
              data={serviceData} workspace={workspace} update={update}
              contacts={contacts} onCreateContact={onCreateContact}
              needType={caseDetails?.needType || "as_need"} />

            }
            {activeTab === "tree" && <TreeTab data={serviceData} update={update} />}
            {activeTab === "funeral" && <FuneralTab data={serviceData} workspace={workspace} update={update} needType={caseDetails?.needType || "as_need"} />}
            {activeTab === "pastoral" && <PastoralTab data={serviceData} update={update} />}
          </div>
        </div>
      </main>

      <OrderSummarySidebar
        caseDetails={caseDetails} caseBrand={brandForReligion(caseDetails?.religion || "")}
        serviceData={serviceData}
        selectedPackage={selectedPackage} selectedCasket={selectedCasket}
        selectedAddOns={selectedAddOns}
        addOnTotal={addOnTotal} addOnCount={addOnCount}
        notes={notes} setNotes={setNotes}
        onEditCase={onEditCase} onJumpTo={onJumpTo}
        onContinue={onContinue}
        continueLabel="Continue to Package"
        activeStep="service"
        confirmationStatus={confirmationStatus}
        onSendForConfirmation={onSendForConfirmation}
        onViewPdf={onViewPdf}
        onResend={onResend}
        onEditArrangement={onEditArrangement}
        amendmentSnapshot={amendmentSnapshot}
        onEnterEditMode={onEnterEditMode}
        onFinalizeAmendment={onFinalizeAmendment}
        onDiscardAmendment={onDiscardAmendment}
        onSendToCustomer={onSendToCustomer}
        onSimulateSign={onSimulateSign}
        onSendSignedForm={onSendSignedForm}
        appliedCoupon={appliedCoupon}
        onApplyCoupon={onApplyCoupon}
        onRemoveCoupon={onRemoveCoupon}
      />

    </div>);

}

function ServiceTabBtn({ label, isActive, onClick }) {
  return (
    <button
      onClick={onClick}
      style={{
        all: "unset", cursor: "pointer",
        display: "inline-flex", alignItems: "center",
        padding: "8px 18px",
        borderRadius: 7,
        fontSize: 14, fontWeight: isActive ? 600 : 500,
        letterSpacing: "-0.15px",
        color: isActive ? "#1F3A60" : "#6B7A8F",
        background: isActive ? "#FFFFFF" : "transparent",
        boxShadow: isActive ? "0 1px 4px rgba(31,58,96,0.12), 0 0 0 1px rgba(31,58,96,0.06)" : "none",
        whiteSpace: "nowrap", flexShrink: 0,
        transition: "background 150ms ease, color 150ms ease, box-shadow 150ms ease",
      }}>
      {label}
    </button>
  );
}

/* ───────────────── Form primitives ─────────────────
   Adopts Variation B's "floating card + section icon" design:
   - White card, soft shadow (no border), 14px radius
   - Header: 32px navy-tinted icon chip + title + optional hint
   - Bottom border between header and fields
   - Side-by-side label/field rows (180px label column) — ServiceField handles this
   - Tight 7px row padding via the field row container
   - Optional "More details" toggle for non-essential fields
   ────────────────────────────────────────────────── */

const SECTION_CARD_SHADOW = "0 1px 2px rgba(15,23,42,0.04), 0 4px 12px rgba(15,23,42,0.06)";

function SectionIcon({ kind }) {
  // 18px navy-stroke icons matching the Variation B set.
  const base = { width: 18, height: 18 };
  const stroke = "#1F3A60";
  switch (kind) {
    case "profile":
      return (
        <svg {...base} viewBox="0 0 20 20" fill="none">
          <circle cx="10" cy="7" r="3.2" stroke={stroke} strokeWidth="1.5" />
          <path d="M3 17.5c1-3.4 3.7-5 7-5s6 1.6 7 5" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" />
        </svg>
      );
    case "life":
      return (
        <svg {...base} viewBox="0 0 20 20" fill="none">
          <circle cx="10" cy="10" r="7" stroke={stroke} strokeWidth="1.5" />
          <path d="M10 6v4l3 2" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" />
        </svg>
      );
    case "care":
      return (
        <svg {...base} viewBox="0 0 20 20" fill="none">
          <path d="M3 9c0-3 2-5 5-5 1.5 0 2.5.7 3 1.5C11.5 4.7 12.5 4 14 4c3 0 4 2 4 5 0 4.5-7 7.5-7.5 7.5S3 13.5 3 9z" stroke={stroke} strokeWidth="1.5" strokeLinejoin="round" />
        </svg>
      );
    case "contacts":
      return (
        <svg {...base} viewBox="0 0 20 20" fill="none">
          <circle cx="7" cy="8" r="2.5" stroke={stroke} strokeWidth="1.5" />
          <circle cx="14" cy="9" r="2" stroke={stroke} strokeWidth="1.5" />
          <path d="M2.5 16c.5-2.5 2.5-3.5 4.5-3.5s4 1 4.5 3.5M11.5 16c.4-2 1.8-3 3-3s2.4.8 2.8 3" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" />
        </svg>
      );
    case "family":
      return (
        <svg {...base} viewBox="0 0 20 20" fill="none">
          <circle cx="6" cy="6" r="2" stroke={stroke} strokeWidth="1.5" />
          <circle cx="14" cy="6" r="2" stroke={stroke} strokeWidth="1.5" />
          <circle cx="10" cy="14" r="2" stroke={stroke} strokeWidth="1.5" />
          <path d="M6 8v2M14 8v2M8 13l1-1M12 13l-1-1" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" />
        </svg>
      );
    case "venue":
      return (
        <svg {...base} viewBox="0 0 20 20" fill="none">
          <path d="M10 18s-6-5.5-6-10a6 6 0 1 1 12 0c0 4.5-6 10-6 10z" stroke={stroke} strokeWidth="1.5" strokeLinejoin="round" />
          <circle cx="10" cy="8" r="2" stroke={stroke} strokeWidth="1.5" />
        </svg>
      );
    case "schedule":
      return (
        <svg {...base} viewBox="0 0 20 20" fill="none">
          <rect x="3" y="4.5" width="14" height="13" rx="1.5" stroke={stroke} strokeWidth="1.5" />
          <path d="M3 8.5h14M6.5 2.5v3M13.5 2.5v3" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" />
        </svg>
      );
    case "resting":
      return (
        <svg {...base} viewBox="0 0 20 20" fill="none">
          <path d="M4 16h12M5 16V8l5-3 5 3v8M8 16v-5h4v5" stroke={stroke} strokeWidth="1.5" strokeLinejoin="round" />
        </svg>
      );
    case "prayer":
      return (
        <svg {...base} viewBox="0 0 20 20" fill="none">
          <path d="M10 2v16M5 7h10" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" />
        </svg>
      );
    case "mass":
      return (
        <svg {...base} viewBox="0 0 20 20" fill="none">
          <path d="M4 16h12M6 16V8h8v8M8 5h4M10 3v4" stroke={stroke} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
        </svg>
      );
    default:
      return (
        <svg {...base} viewBox="0 0 20 20" fill="none">
          <rect x="4" y="4" width="12" height="12" rx="2" stroke={stroke} strokeWidth="1.5" />
        </svg>
      );
  }
}

function FormSection({ title, hint, children, columns = 1, icon }) {
  return (
    <section style={{
      background: "#FFFFFF",
      borderRadius: 14,
      boxShadow: SECTION_CARD_SHADOW,
      padding: "20px 24px",
      marginBottom: 18,
    }}>
      {title && (
        <header style={{
          display: "flex", alignItems: "center", gap: 12,
          marginBottom: 10,
          paddingBottom: 14,
          borderBottom: "1px solid #F0F1F4",
        }}>
          {icon && (
            <span style={{
              width: 32, height: 32, borderRadius: 8,
              background: "#EEF2F7",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              flexShrink: 0,
            }}>
              <SectionIcon kind={icon} />
            </span>
          )}
          <div style={{ display: "flex", flexDirection: "column", gap: 1, flex: 1, minWidth: 0 }}>
            <h3 style={{
              font: "600 15px/20px var(--font-ui, Inter, system-ui, -apple-system, sans-serif)",
              letterSpacing: "-0.2px", color: "#1F3A60", margin: 0,
            }}>{title}</h3>
            {hint && (
              <span style={{
                fontSize: 12, color: "#9CA8B8", letterSpacing: "-0.1px",
              }}>{hint}</span>
            )}
          </div>
        </header>
      )}
      <div style={{
        display: "grid",
        gridTemplateColumns: columns === 1 ? "minmax(0, 1fr)" : `repeat(${columns}, minmax(0, 1fr))`,
        gap: columns === 1 ? 0 : 14,
      }}>
        {children}
      </div>
    </section>
  );
}

function ServiceField({ label, required, span, hint, children }) {
  return (
    <label style={{
      display: "grid", gridTemplateColumns: "180px 1fr", alignItems: "center",
      columnGap: 16, rowGap: 4,
      padding: "7px 0",
      gridColumn: span ? `span ${span}` : "auto"
    }}>
      <span style={{
        fontSize: 13, fontWeight: required ? 500 : 400,
        color: required ? "#1F3A60" : "#6B7A8F",
        letterSpacing: "-0.15px",
        display: "inline-flex", alignItems: "center", gap: 2
      }}>
        {label}
        {required && <span style={{ color: "#8F4A45", marginLeft: 2 }}>*</span>}
      </span>
      <div style={{ minWidth: 0 }}>{children}</div>
      {hint &&
      <React.Fragment>
          <span />
          <span style={{ fontSize: 12, color: "#9CA8B8", letterSpacing: "-0.1px" }}>{hint}</span>
        </React.Fragment>
      }
    </label>);

}

function ServiceInput({ value, onChange, placeholder, type = "text", style: extraStyle }) {
  const [focused, setFocused] = React.useState(false);
  return (
    <input
      type={type}
      value={value || ""}
      onChange={onChange}
      placeholder={placeholder}
      onFocus={() => setFocused(true)}
      onBlur={() => setFocused(false)}
      style={{
        width: "100%", minWidth: 0, boxSizing: "border-box",
        height: 44, padding: "0 12px",
        fontFamily: "inherit", fontSize: 14, color: "#1F3A60",
        background: "#FFFFFF",
        border: `1px solid ${focused ? "#1F3A60" : "#E5E7EB"}`,
        boxShadow: focused ? "0 0 0 3px rgba(31,58,96,0.10)" : "none",
        borderRadius: 8, outline: "none",
        letterSpacing: "-0.15px",
        transition: "border-color 120ms, box-shadow 120ms",
        WebkitAppearance: "none",
        ...extraStyle
      }} />);


}

function DateTimeField({ label, value, onChange, required, span }) {
  const date = value ? value.split("T")[0] : "";
  const time = value ? (value.split("T")[1] || "") : "";
  const handleDate = (d) => onChange(d ? (time ? `${d}T${time}` : d) : "");
  const handleTime = (t) => onChange(date ? `${date}T${t}` : "");
  return (
    <ServiceField label={label} required={required} span={span}>
      <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
        <ServiceInput type="date" value={date} onChange={(e) => handleDate(e.target.value)} style={{ flex: "1 1 160px" }} />
        <ServiceInput type="time" value={time} onChange={(e) => handleTime(e.target.value)} style={{ flex: "1 1 120px" }} />
      </div>
    </ServiceField>
  );
}

function ServiceSelect({ value, onChange, options, groups, placeholder = "Select..." }) {
  const [open, setOpen] = React.useState(false);

  // Escape key to close
  React.useEffect(() => {
    if (!open) return;
    const onKey = (e) => { if (e.key === "Escape") setOpen(false); };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [open]);

  const opts = groups
    ? groups.flatMap((g) => g.items.map((item) => ({ value: item, label: item })))
    : (options || []).map((o) => typeof o === "string" ? { value: o, label: o } : o);
  const selected = opts.find((o) => o.value === value);

  const handleSelect = (v) => {
    onChange && onChange({ target: { value: v } });
    setOpen(false);
  };

  const optBtn = (key, label, isSel, onSelect) => (
    <button
      key={key}
      type="button"
      role="option"
      aria-selected={isSel}
      onPointerDown={(e) => { e.preventDefault(); onSelect(); }}
      style={{
        all: "unset", cursor: "pointer",
        width: "100%", boxSizing: "border-box",
        padding: "9px 12px", borderRadius: 6,
        fontSize: 14, color: "#1F3A60",
        background: isSel ? "#F0F4F8" : "transparent",
        letterSpacing: "-0.15px",
        display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8,
        transition: "background 100ms ease",
        touchAction: "manipulation",
      }}
      onMouseEnter={(e) => { if (!isSel) e.currentTarget.style.background = "#FAFBFC"; }}
      onMouseLeave={(e) => { if (!isSel) e.currentTarget.style.background = "transparent"; }}
    >
      <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
        {label}
      </span>
      {isSel && <SerIcons.Check size={14} color="#1F3A60" />}
    </button>
  );

  return (
    /* When open, elevate the container above the backdrop so the trigger
       button remains tappable. The backdrop sits at z:1000; this container
       at z:1001 ensures both the trigger and the dropdown list are on top. */
    <div style={{ position: "relative", width: "100%", zIndex: open ? 1001 : undefined }}>

      {/* Backdrop — covers the viewport, closes dropdown on any tap/click outside */}
      {open && (
        <div
          onPointerDown={() => setOpen(false)}
          style={{ position: "fixed", inset: 0, zIndex: 1000 }}
        />
      )}

      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="listbox"
        aria-expanded={open}
        style={{
          all: "unset",
          width: "100%", boxSizing: "border-box",
          height: 44, padding: "0 36px 0 12px",
          fontSize: 14,
          color: selected ? "#1F3A60" : "rgba(45,55,72,0.5)",
          background: "#FFFFFF",
          border: `1px solid ${open ? "#1F3A60" : "#E5E7EB"}`,
          boxShadow: open ? "0 0 0 3px rgba(31,58,96,0.10)" : "none",
          borderRadius: 8,
          display: "flex", alignItems: "center",
          letterSpacing: "-0.15px",
          cursor: "pointer",
          position: "relative",
          transition: "border-color 120ms, box-shadow 120ms",
          touchAction: "manipulation",
        }}
      >
        <span style={{
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", flex: 1,
        }}>
          {selected ? selected.label : placeholder}
        </span>
        <span style={{
          position: "absolute", right: 12, top: "50%",
          transform: `translateY(-50%) ${open ? "rotate(180deg)" : ""}`,
          color: "#6B7A8F", display: "flex",
          transition: "transform 140ms ease",
        }}>
          <svg width="14" height="14" viewBox="0 0 20 20" fill="none">
            <path d="M5 8l5 5 5-5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
          </svg>
        </span>
      </button>

      {open && (
        <div role="listbox" style={{
          position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0,
          background: "#FFFFFF",
          border: "1px solid #E5E7EB", borderRadius: 10,
          boxShadow: "0 12px 32px rgba(15,23,42,0.12)",
          padding: 6,
          zIndex: 30,
          maxHeight: 280, overflowY: "auto",
        }}>
          {opts.length === 0 ? (
            <div style={{
              padding: "10px 12px", fontSize: 13, color: "#9CA8B8",
              letterSpacing: "-0.1px",
            }}>No options</div>
          ) : groups ? groups.map(({ group, items }) => (
            <React.Fragment key={group || "__top"}>
              {group && (
                <div style={{
                  padding: "8px 12px 4px",
                  fontSize: 11, fontWeight: 600, color: "#9CA8B8",
                  letterSpacing: "0.4px", textTransform: "uppercase",
                  userSelect: "none",
                }}>
                  {group}
                </div>
              )}
              {items.map((item) => optBtn(item, item, item === value, () => handleSelect(item)))}
            </React.Fragment>
          )) : opts.map((opt) => optBtn(opt.value, opt.label, opt.value === value, () => handleSelect(opt.value)))}
        </div>
      )}
    </div>
  );
}

function ServiceTextarea({ value, onChange, placeholder, rows = 3 }) {
  return (
    <textarea
      value={value || ""}
      onChange={onChange}
      placeholder={placeholder}
      rows={rows}
      style={{
        width: "100%", boxSizing: "border-box",
        padding: "10px 12px", fontFamily: "inherit",
        fontSize: 14, lineHeight: "20px", color: "#1F3A60",
        background: "#FFFFFF", border: "1px solid #E5E7EB",
        borderRadius: 8, outline: "none", resize: "vertical",
        letterSpacing: "-0.15px"
      }} />);


}

function ServiceCheckbox({ checked, onChange, label }) {
  return (
    <label style={{
      display: "inline-flex", alignItems: "center", gap: 10, cursor: "pointer",
      padding: "10px 12px", borderRadius: 8,
      border: "1px solid #E5E7EB", background: "#FFFFFF"
    }}>
      <span style={{
        width: 18, height: 18, borderRadius: 4,
        border: `1.5px solid ${checked ? "#1F3A60" : "#D1D5DB"}`,
        background: checked ? "#1F3A60" : "#FFFFFF",
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        transition: "background 140ms ease, border-color 140ms ease"
      }}>
        {checked && <SerIcons.Check size={12} color="#FFFFFF" />}
      </span>
      <input type="checkbox" checked={checked} onChange={onChange} style={{ display: "none" }} />
      <span style={{ fontSize: 14, color: "#1F3A60", letterSpacing: "-0.15px" }}>{label}</span>
    </label>);

}

/* Numeric stepper for family-tree counts. Default 0, no negatives.
   The centre display is now an editable input: FDs can tap to type a
   value directly (shows numeric keypad on tablet) or use the buttons.
   Draft state decouples typing from the committed integer so the input
   stays responsive while a multi-digit number is being entered. */
function NumberStepper({ value = 0, onChange, min = 0, max = 99 }) {
  const set = (next) => onChange(Math.max(min, Math.min(max, next)));
  const [draft, setDraft] = React.useState(String(value));
  const focused = React.useRef(false);
  React.useEffect(() => {
    if (!focused.current) setDraft(String(value));
  }, [value]);
  const commit = () => {
    const parsed = parseInt(draft, 10);
    const safe = isNaN(parsed) ? min : Math.max(min, Math.min(max, parsed));
    set(safe);
    setDraft(String(safe));
  };
  return (
    <div style={{
      display: "inline-flex", alignItems: "center",
      border: "1px solid #E5E7EB", borderRadius: 8, background: "#FFFFFF",
      height: 40, overflow: "hidden"
    }}>
      <StepBtn onClick={() => set(value - 1)} disabled={value <= min}><SerIcons.Minus size={14} /></StepBtn>
      <input
        type="text"
        inputMode="numeric"
        pattern="[0-9]*"
        value={draft}
        onChange={(e) => {
          const raw = e.target.value.replace(/[^\d]/g, "");
          setDraft(raw);
          const parsed = parseInt(raw, 10);
          if (!isNaN(parsed)) set(Math.max(min, Math.min(max, parsed)));
        }}
        onFocus={() => { focused.current = true; }}
        onBlur={() => { focused.current = false; commit(); }}
        style={{
          width: 44, border: "none", outline: "none",
          textAlign: "center", background: "transparent",
          fontSize: 15, fontWeight: 500, color: "#1F3A60",
          fontFeatureSettings: "'tnum'", letterSpacing: "-0.15px",
          fontFamily: "inherit", padding: 0,
          WebkitAppearance: "none", MozAppearance: "textfield",
        }}
      />
      <StepBtn onClick={() => set(value + 1)} disabled={value >= max}><SerIcons.Plus size={16} /></StepBtn>
    </div>);

}

function StepBtn({ onClick, disabled, children }) {
  return (
    <button
      onClick={onClick} disabled={disabled}
      style={{
        all: "unset", cursor: disabled ? "not-allowed" : "pointer",
        width: 36, height: 38, display: "inline-flex",
        alignItems: "center", justifyContent: "center",
        color: disabled ? "#D1D5DB" : "#574F40",
        transition: "color 120ms ease"
      }}>
      {children}</button>);

}

/* ─────────────────────────────────────────────────────
   ContactPicker — Many2one to res.partner. Mirrors the
   pattern from Start Arrangement: search existing
   contacts or quick-create a new one.
   ───────────────────────────────────────────────────── */
function ContactPicker({ value, onChange, contacts = [], onCreate, placeholder = "Select contact…" }) {
  const [open, setOpen] = React.useState(false);
  const [q, setQ] = React.useState("");
  const [creating, setCreating] = React.useState(false);
  const [newName, setNewName] = React.useState("");
  const [newPhone, setNewPhone] = React.useState("");
  const [newEmail, setNewEmail] = React.useState("");
  const ref = React.useRef(null);
  const dropStyle = useSmartPosition(open, ref, { maxHeight: 360 });

  React.useEffect(() => {
    if (!open) return;
    const onDocClick = (e) => {if (ref.current && !ref.current.contains(e.target)) {setOpen(false);setCreating(false);}};
    const onEsc = (e) => {if (e.key === "Escape") {setOpen(false);setCreating(false);}};
    document.addEventListener("mousedown", onDocClick);
    document.addEventListener("keydown", onEsc);
    return () => {
      document.removeEventListener("mousedown", onDocClick);
      document.removeEventListener("keydown", onEsc);
    };
  }, [open]);

  const selected = contacts.find((c) => c.id === value);
  const matches = q ?
  contacts.filter((c) => `${c.name} ${c.phone || ""} ${c.mobile || ""}`.toLowerCase().includes(q.toLowerCase())) :
  contacts.slice(0, 8);

  const canCreate = newName.trim() && newPhone.includes(" ");
  const doCreate = async () => {
    if (!canCreate || !onCreate) return;
    const created = await onCreate({
      name: newName.trim(),
      mobile: newPhone.trim(),
      phone: newPhone.trim(),
      email: newEmail.trim() || undefined,
      type: "individual",
      category: "family",
      tags: []
    });
    if (created && created.id) onChange(created.id);
    setCreating(false);setNewName("");setNewPhone("");setNewEmail("");setOpen(false);
  };

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        style={{
          all: "unset", cursor: "pointer", width: "100%", boxSizing: "border-box",
          height: 44, padding: "0 12px",
          display: "inline-flex", alignItems: "center", justifyContent: "space-between",
          background: "#FFFFFF",
          border: `1px solid ${open ? "#1F3A60" : "#E5E7EB"}`,
          borderRadius: 8,
          fontSize: 14, color: selected ? "#1F3A60" : "rgba(45,55,72,0.5)",
          letterSpacing: "-0.15px"
        }}>
        
        <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          {selected ? selected.name : placeholder}
        </span>
        <SerIcons.ChevronDown size={14} color="#6B7A8F" />
      </button>

      {open && dropStyle &&
      <div style={{
        ...dropStyle,
        background: "#FFFFFF", border: "1px solid #E5E7EB",
        borderRadius: 10, padding: 6,
        boxShadow: "0 12px 32px -8px rgba(15,23,42,0.18)",
      }}>
          {!creating &&
        <React.Fragment>
              <div style={{ padding: 4 }}>
                <Input
              icon={<SerIcons.Search size={16} />}
              value={q} onChange={(e) => setQ(e.target.value)}
              placeholder="Search contacts…" />
            
              </div>
              {matches.length === 0 ?
          <div style={{ padding: "16px 12px", fontSize: 13, color: "#6B7A8F", textAlign: "center" }}>
                  No matching contacts
                </div> :

          matches.map((c) =>
          <button
            key={c.id}
            onClick={() => {onChange(c.id);setOpen(false);}}
            style={{
              all: "unset", cursor: "pointer", display: "flex",
              alignItems: "center", gap: 10, padding: "10px 12px",
              width: "100%", boxSizing: "border-box", borderRadius: 6,
              background: value === c.id ? "#EFE7D4" : "transparent"
            }}
            onMouseEnter={(e) => {if (value !== c.id) e.currentTarget.style.background = "#F3F4F6";}}
            onMouseLeave={(e) => {if (value !== c.id) e.currentTarget.style.background = "transparent";}}>
            
                    <div style={{
              width: 32, height: 32, borderRadius: "50%",
              background: "rgba(31,58,96,0.08)", color: "#1F3A60",
              display: "inline-flex", alignItems: "center", justifyContent: "center",
              fontSize: 12, fontWeight: 500, flexShrink: 0
            }}>
                      {(c.name || "?").split(/\s+/).slice(0, 2).map((w) => w[0]).join("").toUpperCase()}
                    </div>
                    <div style={{ display: "flex", flexDirection: "column", minWidth: 0 }}>
                      <span style={{
                fontSize: 14, fontWeight: 500, color: "#1F3A60",
                overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"
              }}>{c.name}</span>
                      <span style={{ fontSize: 12, color: "#6B7A8F" }}>
                        {fmtPhone(c.mobile || c.phone) || ""}
                      </span>
                    </div>
                  </button>
          )
          }
              {onCreate &&
          <button
            onClick={() => setCreating(true)}
            style={{
              all: "unset", cursor: "pointer",
              display: "flex", alignItems: "center", gap: 8,
              padding: "10px 12px", borderTop: "1px solid #F0F1F4",
              marginTop: 4, width: "100%", boxSizing: "border-box",
              fontSize: 13, color: "#1F3A60", fontWeight: 500
            }}>
            
                  <SerIcons.Plus size={16} />Create New Contact
                </button>
          }
            </React.Fragment>
        }

          {creating &&
        <div style={{ padding: 8, display: "flex", flexDirection: "column", gap: 10 }}>
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "0 4px" }}>
                <span style={{ fontSize: 13, fontWeight: 500, color: "#1F3A60" }}>New contact</span>
                <button onClick={() => {setCreating(false);setNewName("");setNewPhone("");setNewEmail("");}} style={{ all: "unset", cursor: "pointer", color: "#6B7A8F", fontSize: 12 }}>Cancel</button>
              </div>
              <ServiceInput value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="Name *" />
              <PhoneInput value={newPhone} onChange={(e) => setNewPhone(e.target.value)} />
              <ServiceInput type="email" value={newEmail} onChange={(e) => setNewEmail(e.target.value)} placeholder="Email" />
              <Button variant="primary-navy" size="md" onClick={doCreate} disabled={!canCreate} style={{ width: "100%" }}>
                Save & Select
              </Button>
            </div>
        }
        </div>
      }
    </div>);

}

/* ───────────────── Care Information tab ─────────────────
   Sections (per Odoo Care Information layout):
     • Deceased Profile        — left column
     • Life Information        — right column
     • Preparation & Care      — left
     • Case Contacts           — right
     • Family Record           — Fountains only
   ────────────────────────────────────────────────────────── */
function CareTab({ data, workspace, update, contacts, onCreateContact, needType }) {
  const isPreNeed = needType === "pre_need";
  const religionOptions = RELIGIONS_BY_WORKSPACE[workspace] || RELIGIONS_BY_WORKSPACE.serenity;

  // Auto-fill primaryContactEmail when primary contact is selected/changed,
  // but only if the FD hasn't already typed something in the field.
  React.useEffect(() => {
    if (!data.primaryContactId) return;
    const c = contacts.find((x) => x.id === data.primaryContactId);
    if (c && c.email && !data.primaryContactEmail) {
      update({ primaryContactEmail: c.email });
    }
  }, [data.primaryContactId]); // eslint-disable-line react-hooks/exhaustive-deps

  // Same for secondary contact.
  React.useEffect(() => {
    if (!data.secondaryContactId) return;
    const c = contacts.find((x) => x.id === data.secondaryContactId);
    if (c && c.email && !data.secondaryContactEmail) {
      update({ secondaryContactEmail: c.email });
    }
  }, [data.secondaryContactId]); // eslint-disable-line react-hooks/exhaustive-deps

  // Auto-calculate age. For As-Need: uses dateOfDeath as the reference point
  // so historical ages remain accurate. For Pre-Need: falls back to today's
  // date when no dateOfDeath is recorded (person still living). Manual edits
  // are preserved when one of the two dates is missing.
  React.useEffect(() => {
    const refDateStr = data.dateOfDeath || (isPreNeed ? new Date().toISOString().slice(0, 10) : "");
    if (!data.dateOfBirth || !refDateStr) return;
    const dob = new Date(data.dateOfBirth);
    const dod = new Date(refDateStr);
    if (isNaN(dob.getTime()) || isNaN(dod.getTime())) return;
    let age = dod.getFullYear() - dob.getFullYear();
    const m = dod.getMonth() - dob.getMonth();
    if (m < 0 || m === 0 && dod.getDate() < dob.getDate()) age -= 1;
    if (age < 0) age = 0;
    if (String(age) !== String(data.age)) update({ age: String(age) });
  }, [data.dateOfBirth, data.dateOfDeath]); // eslint-disable-line react-hooks/exhaustive-deps

  return (
    <React.Fragment>
      {/* Stacked sections — horizontal labels demand more width per field. */}
      <FormSection icon="profile" title={isPreNeed ? "Planee Profile" : "Deceased Profile"}>
          <ServiceField label="Salutation">
            <ServiceSelect
            value={data.salutations}
            onChange={(e) => update({ salutations: e.target.value })}
            options={SALUTATION_OPTIONS}
            placeholder="Select salutation" />

          </ServiceField>
          <ServiceField label={isPreNeed ? "Full Name" : "Deceased Name"} required>
            <ServiceInput value={data.deceasedName} onChange={(e) => update({ deceasedName: e.target.value })} placeholder={isPreNeed ? "Enter planee's full name" : "Enter full name"} />
          </ServiceField>
          <ServiceField label="Gender">
            <ServiceSelect
            value={data.gender}
            onChange={(e) => update({ gender: e.target.value })}
            options={GENDER_OPTIONS}
            placeholder="Select gender" />
          
          </ServiceField>
          {workspace === "fountains" &&
        <ServiceField label="Marital Status">
              <ServiceSelect
            value={data.maritalStatus}
            onChange={(e) => update({ maritalStatus: e.target.value })}
            options={MARITAL_OPTIONS}
            placeholder="Select marital status" />
          
            </ServiceField>
        }
          <ServiceField label="Religion" required>
            <ServiceSelect
            value={data.religion}
            onChange={(e) => update({ religion: e.target.value })}
            options={religionOptions}
            placeholder="Select religion" />
          
          </ServiceField>
          {workspace === "fountains" &&
        <ServiceField label="Dialect">
              <ServiceSelect
            value={data.dialect}
            onChange={(e) => update({ dialect: e.target.value })}
            options={DIALECT_OPTIONS}
            placeholder="Select dialect" />
          
            </ServiceField>
        }
        </FormSection>

        <FormSection icon="life" title="Life Information">
          {!isPreNeed && (
            <ServiceField label="Date of Death" required>
              <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
                <ServiceInput type="date" value={data.dateOfDeath} onChange={(e) => update({ dateOfDeath: e.target.value })} style={{ flex: "1 1 160px" }} />
                <span style={{ fontSize: 13, color: "#6B7A8F", whiteSpace: "nowrap", flexShrink: 0 }}>Time of Death</span>
                <ServiceInput type="time" value={data.timeOfDeath} onChange={(e) => update({ timeOfDeath: e.target.value })} style={{ flex: "1 1 120px" }} />
              </div>
            </ServiceField>
          )}
          <ServiceField label="Date of Birth" required={isPreNeed}>
            <ServiceInput type="date" value={data.dateOfBirth} onChange={(e) => update({ dateOfBirth: e.target.value })} />
          </ServiceField>
          <ServiceField label="Age" hint={
            data.dateOfBirth && data.dateOfDeath ? "Calculated automatically" :
            data.dateOfBirth && isPreNeed ? "Calculated from today's date" :
            null
          }>
            <ServiceInput type="number" value={data.age} onChange={(e) => update({ age: e.target.value })} placeholder="—" />
          </ServiceField>
        </FormSection>

      {/* Preparation & Care — only for At-Need cases (person already deceased) */}
      {!isPreNeed && (
        <FormSection icon="care" title="Preparation & Care">
          <ServiceField label="Transfer Location">
            <ServiceSelect
              value={data.transferLocationType}
              onChange={(e) => update({ transferLocationType: e.target.value, transferLocationHospital: "", transferLocationHospice: "", transferLocationRemarks: "" })}
              options={TRANSFER_LOCATION_TYPES}
              placeholder="Select transfer type" />
          </ServiceField>
          {data.transferLocationType === "Hospital" && (
          <div style={{ display: "flex", flexDirection: "column" }}>
            <ServiceField label="Hospital">
              <ServiceSelect
                value={data.transferLocationHospital}
                onChange={(e) => update({ transferLocationHospital: e.target.value, transferLocationRemarks: "" })}
                options={HOSPITAL_OPTIONS}
                placeholder="Select hospital" />
            </ServiceField>
            <div style={{
              display: "grid",
              gridTemplateRows: data.transferLocationHospital === "Others" ? "1fr" : "0fr",
              opacity: data.transferLocationHospital === "Others" ? 1 : 0,
              transition: "grid-template-rows 220ms cubic-bezier(0.4,0,0.2,1), opacity 180ms ease",
              overflow: "hidden",
            }}>
              <div style={{ minHeight: 0 }}>
                <ServiceField label="Specify Hospital">
                  <ServiceInput
                    value={data.transferLocationRemarks}
                    onChange={(e) => update({ transferLocationRemarks: e.target.value })}
                    placeholder="Enter hospital name" />
                </ServiceField>
              </div>
            </div>
          </div>
          )}
          {data.transferLocationType === "Hospice" && (
          <div style={{ display: "flex", flexDirection: "column" }}>
            <ServiceField label="Hospice">
              <ServiceSelect
                value={data.transferLocationHospice}
                onChange={(e) => update({ transferLocationHospice: e.target.value, transferLocationRemarks: "" })}
                options={HOSPICE_OPTIONS}
                placeholder="Select hospice" />
            </ServiceField>
            <div style={{
              display: "grid",
              gridTemplateRows: data.transferLocationHospice === "Others" ? "1fr" : "0fr",
              opacity: data.transferLocationHospice === "Others" ? 1 : 0,
              transition: "grid-template-rows 220ms cubic-bezier(0.4,0,0.2,1), opacity 180ms ease",
              overflow: "hidden",
            }}>
              <div style={{ minHeight: 0 }}>
                <ServiceField label="Specify Hospice">
                  <ServiceInput
                    value={data.transferLocationRemarks}
                    onChange={(e) => update({ transferLocationRemarks: e.target.value })}
                    placeholder="Enter hospice name" />
                </ServiceField>
              </div>
            </div>
          </div>
          )}
          {data.transferLocationType === "Nursing Home" && (
          <ServiceField label="Specify Nursing Home">
            <ServiceInput
              value={data.transferLocationRemarks}
              onChange={(e) => update({ transferLocationRemarks: e.target.value })}
              placeholder="Enter nursing home name" />
          </ServiceField>
          )}
          {data.transferLocationType === "Home" && (
          <ServiceField label="Home Address">
            <ServiceInput
              value={data.transferLocationRemarks}
              onChange={(e) => update({ transferLocationRemarks: e.target.value })}
              placeholder="Block, street, unit number" />
          </ServiceField>
          )}
          {data.transferLocationType === "Coroner" && (
          <ServiceField label="Location">
            <ServiceInput
              value={data.transferLocationRemarks}
              onChange={(e) => update({ transferLocationRemarks: e.target.value })}
              placeholder="e.g. Health Sciences Authority (HSA)" />
          </ServiceField>
          )}
          {data.transferLocationType === "Other" && (
          <ServiceField label="Specify Location">
            <ServiceInput
              value={data.transferLocationRemarks}
              onChange={(e) => update({ transferLocationRemarks: e.target.value })}
              placeholder="Describe transfer location" />
          </ServiceField>
          )}
          <ServiceField label="Embalming Options">
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {EMBALMING_OPTIONS.map((opt) => {
                const selected = Array.isArray(data.embalmingOptions)
                  ? data.embalmingOptions.includes(opt.id)
                  : false;
                return (
                  <button
                    key={opt.id}
                    type="button"
                    onClick={() => {
                      const current = Array.isArray(data.embalmingOptions) ? data.embalmingOptions : [];
                      const next = selected ? current.filter(x => x !== opt.id) : [...current, opt.id];
                      update({ embalmingOptions: next });
                    }}
                    style={{
                      all: "unset", cursor: "pointer",
                      padding: "8px 16px", borderRadius: 8,
                      border: `1px solid ${selected ? "#574F40" : "#E5E7EB"}`,
                      background: selected ? "#EFE7D4" : "#FFFFFF",
                      fontSize: 13, fontWeight: 500,
                      color: selected ? "#1F3A60" : "#6B7A8F",
                      letterSpacing: "-0.1px",
                      display: "inline-flex", alignItems: "center", gap: 7,
                      transition: "border-color 140ms ease, background 140ms ease, color 140ms ease",
                      fontFamily: "inherit",
                    }}
                  >
                    {selected && <SerIcons.Check size={12} color="#1F3A60" />}
                    {opt.label}
                  </button>
                );
              })}
            </div>
          </ServiceField>
          <ServiceField label="Embalming Remarks">
            <ServiceTextarea
            value={data.embalmingRemarks}
            onChange={(e) => update({ embalmingRemarks: e.target.value })}
            placeholder="Special considerations, preferences, or notes from the family…"
            rows={4} />

          </ServiceField>
        </FormSection>
      )}

        <FormSection icon="contacts" title="Case Contacts" hint="Primary and secondary family contacts for this case.">
          <ServiceField label="Primary Contact Relationship">
            <ServiceSelect
            value={data.primaryRelationship}
            onChange={(e) => update({ primaryRelationship: e.target.value })}
            options={RELATIONSHIP_OPTIONS}
            placeholder="Select relationship" />

          </ServiceField>
          <ServiceField label="Primary Family Contact">
            <ContactPicker
            value={data.primaryContactId}
            onChange={(id) => update({ primaryContactId: id })}
            contacts={contacts}
            onCreate={onCreateContact}
            placeholder="Select or create contact" />

          </ServiceField>
          <ServiceField label="Primary Contact Email">
            <ServiceInput
              type="email"
              value={data.primaryContactEmail || ""}
              onChange={(e) => update({ primaryContactEmail: e.target.value })}
              placeholder="name@example.com" />
          </ServiceField>
          <ServiceField label="Secondary Contact Relationship">
            <ServiceSelect
            value={data.secondaryRelationship}
            onChange={(e) => update({ secondaryRelationship: e.target.value })}
            options={RELATIONSHIP_OPTIONS}
            placeholder="Select relationship" />
          
          </ServiceField>
          <ServiceField label="Secondary Family Contact">
            <ContactPicker
            value={data.secondaryContactId}
            onChange={(id) => update({ secondaryContactId: id })}
            contacts={contacts}
            onCreate={onCreateContact}
            placeholder="Select or create contact" />

          </ServiceField>
          <ServiceField label="Secondary Contact Email">
            <ServiceInput
              type="email"
              value={data.secondaryContactEmail || ""}
              onChange={(e) => update({ secondaryContactEmail: e.target.value })}
              placeholder="name@example.com" />
          </ServiceField>
        </FormSection>

      {/* Family Record — Fountains only */}
      {workspace === "fountains" &&
      <FormSection icon="family" title="Family Record" hint="Surviving immediate family.">
          <ServiceField label="Surviving Spouse">
            <ServiceSelect
            value={data.survivingSpouse}
            onChange={(e) => update({ survivingSpouse: e.target.value })}
            options={["Yes", "No"]}
            placeholder="Yes / No" />
          
          </ServiceField>
          <ServiceField label="Surviving Parents">
            <ServiceSelect
            value={data.survivingParents}
            onChange={(e) => update({ survivingParents: e.target.value })}
            options={["Yes", "No"]}
            placeholder="Yes / No" />
          
          </ServiceField>
        </FormSection>
      }
    </React.Fragment>);

}

/* ───────────────── Family Tree tab (Fountains) ───────────────── */
function TreeTab({ data, update }) {
  const setGroup = (group, key, n) =>
  update({ family: { ...data.family, [group]: { ...data.family[group], [key]: n } } });

  return (
    <React.Fragment>
      <FamilyCountGroup
        title="Children" rows={data.family.children}
        fields={[
        ["son", "Son"],
        ["daughter", "Daughter"],
        ["sonInLaw", "Son-in-Law"],
        ["daughterInLaw", "Daughter-in-Law"]]
        }
        onChange={(k, n) => setGroup("children", k, n)} />
      
      <FamilyCountGroup
        title="Siblings" rows={data.family.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"]]
        }
        onChange={(k, n) => setGroup("siblings", k, n)} />
      
      <FamilyCountGroup
        title="Paternal Grandchildren" rows={data.family.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"]]
        }
        onChange={(k, n) => setGroup("paternal", k, n)} />
      
      <FamilyCountGroup
        title="Maternal Grandchildren" rows={data.family.maternal}
        fields={[
        ["grandson", "Grandson"],
        ["granddaughter", "Grand-Daughter"],
        ["granddaughterInLaw", "Grand-Daughter-in-Law"],
        ["grandsonInLaw", "Grandson-in-Law"],
        ["greatGrandson", "Great Grandson"]]
        }
        onChange={(k, n) => setGroup("maternal", k, n)} />
      
    </React.Fragment>);

}

function FamilyCountGroup({ title, rows, fields, onChange }) {
  return (
    <FormSection icon="family" title={title}>
      {fields.map(([key, label]) =>
      <div key={key} style={{
        display: "flex", justifyContent: "space-between", alignItems: "center",
        padding: "4px 0", gap: 12
      }}>
          <span style={{ fontSize: 14, color: "#1F3A60", letterSpacing: "-0.15px" }}>{label}</span>
          <NumberStepper value={rows[key] || 0} onChange={(n) => onChange(key, n)} />
        </div>
      )}
    </FormSection>);

}

/* ───────────────── Funeral Arrangement tab ─────────────────
   Two-column Odoo-aligned layout:
     • Wake Details (left)        — wake venue / duration / visiting hours
     • Final Resting Information (right) — cremation/burial date, locations,
                                     final resting, prayer service, remarks
   ──────────────────────────────────────────────────────────── */
function FuneralTab({ data, workspace, update, needType }) {
  const isPreNeed = needType === "pre_need";
  const isFountains = workspace === "fountains";
  const isCremation = data.cremationOrBurial === "cremation";
  const isBurial = data.cremationOrBurial === "burial";
  const isOthers = data.cremationOrBurial === "others";

  const cremationOptions = CREMATION_LOCATIONS[workspace] || CREMATION_LOCATIONS.serenity;
  const burialOptions    = BURIAL_LOCATIONS[workspace]    || BURIAL_LOCATIONS.serenity;

  /* Cascading Final Resting Location options based on arrangement + workspace */
  const restingLocationConfig = RESTING_LOCATIONS[data.restingArrangement];
  const restingLocationRaw = restingLocationConfig
    ? (restingLocationConfig.both || restingLocationConfig[workspace] || restingLocationConfig.serenity || [])
    : [];
  const restingLocationOptions = [
    ...restingLocationRaw.filter(o => o !== "Others").sort((a, b) => a.localeCompare(b)),
    ...(restingLocationRaw.includes("Others") ? ["Others"] : []),
  ];

  /* Wake-date cross-computation helpers.
       Dates are stored as ISO YYYY-MM-DD; duration is an integer day count.
     Rule set:
       • Change Wake Start Date  → recompute End Date from current duration
       • Change Wake End Date    → recompute Duration from End − Start
       • Change Wake Duration    → recompute End Date from Start + duration
     All three fields stay live and editable; the FD never sees a "locked" field. */
  const parseISO = (iso) => {
    if (!iso) return null;
    const d = new Date(iso + "T00:00:00");
    return isNaN(d.getTime()) ? null : d;
  };
  // Format as local YYYY-MM-DD (NOT toISOString — that converts to UTC and
  // can shift the date by one day in any timezone east of UTC).
  const toISO = (d) => {
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, "0");
    const dd = String(d.getDate()).padStart(2, "0");
    return `${y}-${m}-${dd}`;
  };
  const daysBetween = (a, b) => Math.round((b.getTime() - a.getTime()) / 86400000) + 1;
  const addDays = (d, n) => {const c = new Date(d);c.setDate(c.getDate() + n);return c;};

  const onStartDateChange = (iso) => {
    const start = parseISO(iso);
    const dur = parseInt(data.wakeDuration, 10);
    const patch = { wakeStartDate: iso };
    if (start && dur > 0) {
      patch.wakeEndDate = toISO(addDays(start, dur - 1));
    }
    update(patch);
  };

  const onEndDateChange = (iso) => {
    const start = parseISO(data.wakeStartDate);
    const end = parseISO(iso);
    const patch = { wakeEndDate: iso };
    if (start && end && end >= start) {
      patch.wakeDuration = String(daysBetween(start, end));
    }
    update(patch);
  };

  const onDurationChange = (value) => {
    const dur = parseInt(value, 10);
    const start = parseISO(data.wakeStartDate);
    const patch = { wakeDuration: value };
    if (start && dur > 0) {
      patch.wakeEndDate = toISO(addDays(start, dur - 1));
    }
    update(patch);
  };

  return (
    <div style={{ display: "flex", flexDirection: "column" }}>
      {isPreNeed && (
        <div style={{
          display: "flex", alignItems: "flex-start", gap: 10,
          padding: "12px 16px", borderRadius: 10, marginBottom: 18,
          background: "#EEF2FF", border: "1px solid #C7D2FE",
        }}>
          <SerIcons.Star size={16} color="#4338CA" style={{ flexShrink: 0, marginTop: 1 }} />
          <span style={{ fontSize: 13, color: "#4338CA", letterSpacing: "-0.1px", lineHeight: "20px" }}>
            <strong>Pre-Need</strong> — The following fields capture the planee's <em>preferred</em> arrangements. Actual details will be confirmed and may be updated at the time of need.
          </span>
        </div>
      )}
      <FormSection icon="venue" title={isPreNeed ? "Preferred Wake Arrangement" : "Wake Details"}>
        <ServiceField label={isPreNeed ? "Preferred Wake Venue" : "Wake Venue"}>
          <ServiceSelect
            value={data.wakeVenueType}
            onChange={(e) => update({ wakeVenueType: e.target.value, wakeVenueParlour: "", wakeVenueChurch: "", wakeVenueRemarks: "" })}
            options={isFountains ? WAKE_VENUE_TYPES_FOUNTAINS : WAKE_VENUE_TYPES}
            placeholder="Select Wake Venue" />
        </ServiceField>
        {data.wakeVenueType === "Parlour" && (
        <div style={{ display: "flex", flexDirection: "column" }}>
          <ServiceField label="Parlour">
            <ServiceSelect
              value={data.wakeVenueParlour}
              onChange={(e) => update({ wakeVenueParlour: e.target.value, wakeVenueRemarks: "" })}
              options={isFountains ? PARLOUR_OPTIONS.fountains : PARLOUR_OPTIONS.serenity}
              placeholder="Select Parlour" />
          </ServiceField>
          <div style={{
            display: "grid",
            gridTemplateRows: data.wakeVenueParlour === "Others" ? "1fr" : "0fr",
            opacity: data.wakeVenueParlour === "Others" ? 1 : 0,
            transition: "grid-template-rows 220ms cubic-bezier(0.4,0,0.2,1), opacity 180ms ease",
            overflow: "hidden",
          }}>
            <div style={{ minHeight: 0 }}>
              <ServiceField label="Specify Parlour">
                <ServiceInput
                  value={data.wakeVenueRemarks}
                  onChange={(e) => update({ wakeVenueRemarks: e.target.value })}
                  placeholder="Enter parlour name" />
              </ServiceField>
            </div>
          </div>
        </div>
        )}
        {data.wakeVenueType === "Church" && (
        <div style={{ display: "flex", flexDirection: "column" }}>
          <ServiceField label="Church">
            <ServiceSelect
              value={data.wakeVenueChurch}
              onChange={(e) => update({ wakeVenueChurch: e.target.value, wakeVenueRemarks: "" })}
              options={CHURCH_OPTIONS}
              placeholder="Select Church" />
          </ServiceField>
          <div style={{
            display: "grid",
            gridTemplateRows: data.wakeVenueChurch === "Others" ? "1fr" : "0fr",
            opacity: data.wakeVenueChurch === "Others" ? 1 : 0,
            transition: "grid-template-rows 220ms cubic-bezier(0.4,0,0.2,1), opacity 180ms ease",
            overflow: "hidden",
          }}>
            <div style={{ minHeight: 0 }}>
              <ServiceField label="Specify Church">
                <ServiceInput
                  value={data.wakeVenueRemarks}
                  onChange={(e) => update({ wakeVenueRemarks: e.target.value })}
                  placeholder="Enter church name" />
              </ServiceField>
            </div>
          </div>
        </div>
        )}
        {data.wakeVenueType === "HDB" && (
        <ServiceField label="Location">
          <ServiceInput
            value={data.wakeVenueRemarks}
            onChange={(e) => update({ wakeVenueRemarks: e.target.value })}
            placeholder="Block, street, unit number" />
        </ServiceField>
        )}
        {data.wakeVenueType === "Others" && (
        <ServiceField label="Specify Wake Venue">
          <ServiceInput
            value={data.wakeVenueRemarks}
            onChange={(e) => update({ wakeVenueRemarks: e.target.value })}
            placeholder="Enter wake venue name" />
        </ServiceField>
        )}
        <ServiceField label="Wake Schedule" required hint="Start date + duration → end date computed.">
          <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
            <div style={{ flex: "1 1 160px", minWidth: 140 }}>
              <ServiceInput type="date" value={data.wakeStartDate} onChange={(e) => onStartDateChange(e.target.value)} />
            </div>
            <span style={{ color: "#9CA8B8", fontSize: 13 }}>for</span>
            <div style={{ width: 110, flexShrink: 0, position: "relative" }}>
              <ServiceInput type="number" value={data.wakeDuration} onChange={(e) => onDurationChange(e.target.value)} placeholder="—" style={{ paddingRight: 42 }} />
              <span style={{
                position: "absolute", right: 12, top: "50%", transform: "translateY(-50%)",
                fontSize: 12, color: "#9CA8B8", letterSpacing: "-0.05px", pointerEvents: "none",
              }}>days</span>
            </div>
            <span style={{ color: "#9CA8B8", fontSize: 13 }}>→</span>
            <div style={{
              flex: "1 1 160px", minWidth: 140,
              height: 44, padding: "0 14px",
              fontSize: 14, color: "#1F3A60",
              background: "#F4F6F9",
              border: "1px solid #E5E9F0",
              borderRadius: 8,
              display: "flex", alignItems: "center",
              letterSpacing: "-0.15px",
            }}>
              {data.wakeEndDate ? (() => {
                // Parse as local (T00:00:00) so toLocaleDateString never shifts
                // a day in any timezone east of UTC.
                const ed = parseISO(data.wakeEndDate);
                return ed ? ed.toLocaleDateString("en-SG", { day: "2-digit", month: "short", year: "numeric" }) : "—";
              })() : "—"}
            </div>
          </div>
        </ServiceField>
        <ServiceField label="Visiting Hours">
          <ServiceInput value={data.visitingHours} onChange={(e) => update({ visitingHours: e.target.value })} placeholder="e.g. 10:00 AM – 10:00 PM" />
        </ServiceField>
      </FormSection>

      <FormSection
        icon="resting"
        title={isPreNeed ? "Preferred Final Resting" : "Final Resting Information"}
        hint={isPreNeed ? "Capture the planee's preferences — these may be updated at time of need." : "At least one of Cremation or Burial is required."}>
        <ServiceField label={isPreNeed ? "Preferred Disposition" : "Cremation or Burial"} required={!isPreNeed}>
          <div style={{ display: "flex", gap: 10 }}>
            {[
            { id: "cremation", label: "Cremation" },
            { id: "burial", label: "Burial" },
            { id: "others", label: "Others" }].
            map((opt) => {
              const selected = data.cremationOrBurial === opt.id;
              return (
                <button
                  key={opt.id}
                  onClick={() => {
                    const patch = { cremationOrBurial: opt.id };
                    if (opt.id !== "cremation") {
                      patch.cremationLocation = "";
                      patch.restingArrangement = "";
                      patch.finalRestingLocation = "";
                      patch.finalRestingLocationOthers = "";
                      patch.finalRestingDate = "";
                    }
                    if (opt.id !== "burial") {
                      patch.burialLocation = "";
                    }
                    update(patch);
                  }}
                  style={{
                    all: "unset", cursor: "pointer", flex: 1,
                    padding: "12px 14px", borderRadius: 8,
                    border: `1px solid ${selected ? "#574F40" : "#E5E7EB"}`,
                    background: selected ? "#EFE7D4" : "#FFFFFF",
                    fontSize: 14, fontWeight: 500, color: "#1F3A60",
                    letterSpacing: "-0.15px",
                    display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 8,
                    transition: "border-color 140ms ease, background 140ms ease"
                  }}>
                  
                  {selected && <SerIcons.Check size={14} color="#1F3A60" />}
                  {opt.label}
                </button>);

            })}
          </div>
        </ServiceField>

        <ServiceField label={isPreNeed ? "Preferred Funeral Date" : "Funeral Date"}>
          <ServiceInput type="date" value={data.dispositionDate} onChange={(e) => update({ dispositionDate: e.target.value })} />
        </ServiceField>

        {isCremation &&
        <ServiceField label="Cremation Location">
            <ServiceSelect
            value={data.cremationLocation}
            onChange={(e) => update({ cremationLocation: e.target.value })}
            options={cremationOptions}
            placeholder="Select Cremation Location" />
          
          </ServiceField>
        }
        {isBurial &&
        <ServiceField label="Burial Location">
            <ServiceSelect
            value={data.burialLocation}
            onChange={(e) => update({ burialLocation: e.target.value })}
            options={burialOptions}
            placeholder="Select burial location" />
          
          </ServiceField>
        }

        {isCremation && (
        <ServiceField label="Ashes Arrangement">
          <ServiceSelect
            value={data.restingArrangement}
            onChange={(e) => update({ restingArrangement: e.target.value, finalRestingLocation: "", finalRestingLocationOthers: "" })}
            options={RESTING_ARRANGEMENTS}
            placeholder="Select arrangement" />
        </ServiceField>
        )}
        {isCremation && restingLocationOptions.length > 0 && (
        <ServiceField label="Final Resting Location">
          <ServiceSelect
            value={data.finalRestingLocation}
            onChange={(e) => update({ finalRestingLocation: e.target.value, finalRestingLocationOthers: "" })}
            options={restingLocationOptions}
            placeholder="Select Final Resting Location" />
        </ServiceField>
        )}
        {isCremation && (data.restingArrangement === "Others" || data.finalRestingLocation === "Others") && (
        <ServiceField label={data.restingArrangement === "Others" ? "Specify Ashes Arrangement" : "Specify Final Resting Location"}>
          <ServiceInput
            value={data.finalRestingLocationOthers}
            onChange={(e) => update({ finalRestingLocationOthers: e.target.value })}
            placeholder={data.restingArrangement === "Others" ? "Describe ashes arrangement" : "Enter location name"} />
        </ServiceField>
        )}
        {isCremation && (
        <DateTimeField label="Final Resting Date / Time"
          value={data.finalRestingDate}
          onChange={(v) => update({ finalRestingDate: v })} />
        )}
        {workspace === "fountains" &&
        <React.Fragment>
            <ServiceField label="Ancestral Tablet Location">
              <ServiceInput value={data.ancestorTabletLocation} onChange={(e) => update({ ancestorTabletLocation: e.target.value })} placeholder="Ancestral Tablet" />
            </ServiceField>
            <ServiceField label="Anling / Jiling Remarks">
              <ServiceInput value={data.jilingAnlingRemarks} onChange={(e) => update({ jilingAnlingRemarks: e.target.value })} placeholder="Anling / Jiling notes" />
            </ServiceField>
            <ServiceField label="Prayer Service">
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {PRAYER_SERVICE_OPTIONS.filter(opt => !(isBurial && opt.id === "interment_prayers")).map((opt) => {
                  const selected = Array.isArray(data.prayerService)
                    ? data.prayerService.includes(opt.id)
                    : false;
                  return (
                    <button
                      key={opt.id}
                      type="button"
                      onClick={() => {
                        const current = Array.isArray(data.prayerService) ? data.prayerService : [];
                        const next = selected ? current.filter(x => x !== opt.id) : [...current, opt.id];
                        const patch = { prayerService: next };
                        if (opt.id === "others" && selected) patch.prayerServiceOthers = "";
                        update(patch);
                      }}
                      style={{
                        all: "unset", cursor: "pointer",
                        padding: "8px 16px", borderRadius: 8,
                        border: `1px solid ${selected ? "#574F40" : "#E5E7EB"}`,
                        background: selected ? "#EFE7D4" : "#FFFFFF",
                        fontSize: 13, fontWeight: 500,
                        color: selected ? "#1F3A60" : "#6B7A8F",
                        letterSpacing: "-0.1px",
                        display: "inline-flex", alignItems: "center", gap: 7,
                        transition: "border-color 140ms ease, background 140ms ease, color 140ms ease",
                        fontFamily: "inherit",
                      }}
                    >
                      {selected && <SerIcons.Check size={12} color="#1F3A60" />}
                      {opt.label}
                    </button>
                  );
                })}
              </div>
            </ServiceField>
            {Array.isArray(data.prayerService) && data.prayerService.includes("others") && (
            <ServiceField label="Specify Prayer Service">
              <ServiceInput
                value={data.prayerServiceOthers || ""}
                onChange={(e) => update({ prayerServiceOthers: e.target.value })}
                placeholder="Enter prayer service type" />
            </ServiceField>
            )}
          </React.Fragment>
        }

        <ServiceField label="Additional Information">
          <ServiceTextarea
            value={data.dispositionRemarks}
            onChange={(e) => update({ dispositionRemarks: e.target.value })}
            placeholder="Additional notes for the family or operations team…"
            rows={3} />
          
        </ServiceField>
      </FormSection>
    </div>);

}

/* ───────────────── Pastoral Care tab ─────────────────
   Visibility (set at the SERVICE_TABS level):
     workspace = Serenity AND religion ∈ { Christian, Catholic }

   Within the tab, fields show conditionally by religion:
     Christian → Church, Pastor, Memorial Service Date/Time
     Catholic  → Parish, Nightly Prayers, Church Mass + details
   ───────────────────────────────────────────────────── */
function PastoralTab({ data, update }) {
  const religion = (data.religion || "").toLowerCase();
  const isChristian = religion === "christian";
  const isCatholic = religion === "catholic";

  return (
    <React.Fragment>
      <FormSection icon="prayer" title="Church & Clergy" hint={
      isChristian ? "Christian — Pastor and church details." :
      isCatholic ? "Catholic — Parish Church details." :
      "Available for Christian or Catholic cases."
      }>
        {isChristian &&
        <React.Fragment>
            <ServiceField label="Church">
              <ServiceInput value={data.church} onChange={(e) => update({ church: e.target.value })} placeholder="Name of church" />
            </ServiceField>
            <ServiceField label="Pastor">
              <ServiceInput value={data.pastor} onChange={(e) => update({ pastor: e.target.value })} placeholder="Name and contact" />
            </ServiceField>
          </React.Fragment>
        }
        {isCatholic &&
        <ServiceField label="Parish Church" span={2}>
            <ServiceInput value={data.parish} onChange={(e) => update({ parish: e.target.value })} placeholder="Parish name" />
          </ServiceField>
        }
      </FormSection>

      <FormSection icon="schedule" title="Liturgical Schedule">
        {isChristian &&
          <ServiceField label="Memorial Service Date / Time">
            <ServiceTextarea
              value={data.memorialServiceDateTime}
              onChange={(e) => update({ memorialServiceDateTime: e.target.value })}
              placeholder="Date, time, venue, or any additional notes for the memorial service…"
              rows={3} />
          </ServiceField>
        }
        {isCatholic &&
          <DateTimeField label="Nightly Prayers Date / Time"
            value={data.nightlyPrayersDateTime}
            onChange={(v) => update({ nightlyPrayersDateTime: v })} />
        }
      </FormSection>

      {isCatholic &&
      <FormSection icon="mass" title="Mass Details">
          <ServiceField label="Church Mass Required" span={2}>
            <ServiceCheckbox
            checked={!!data.churchMass}
            onChange={(e) => update({ churchMass: e.target.checked })}
            label="Yes, a church mass is required" />
          
          </ServiceField>
          <ServiceField label="Mass Location" span={2}>
            <ServiceInput
            value={data.churchMassDetails}
            onChange={(e) => update({ churchMassDetails: e.target.value })}
            placeholder="e.g. Church of St Mary · 20 May · 11:00 AM" />
          
          </ServiceField>
          <DateTimeField label="Mass Date / Time" span={2}
            value={data.massDateTime}
            onChange={(v) => update({ massDateTime: v })} />
        </FormSection>
      }
    </React.Fragment>);

}

Object.assign(window, {
  ServiceSummaryScreen, SERVICE_DATA_BLANK,
  familyTreeTotals, serviceSummaryFilled,
  visibleTabs, SERVICE_TABS,
  SALUTATION_OPTIONS, GENDER_OPTIONS, MARITAL_OPTIONS, DIALECT_OPTIONS,
  RELATIONSHIP_OPTIONS, CREMATION_LOCATIONS, BURIAL_LOCATIONS, RESTING_ARRANGEMENTS, RESTING_LOCATIONS, PRAYER_SERVICE_OPTIONS, EMBALMING_OPTIONS,
  ContactPicker
});