/* SER-OS — Shared Order Summary sidebar used across all consultation screens */

function OrderSummarySidebar({
  caseDetails, caseBrand,
  serviceData,
  selectedPackage, selectedCasket,
  addOnTotal = 0, addOnCount = 0, selectedAddOns = [],
  notes, setNotes,
  onEditCase, onJumpTo,
  onContinue, continueLabel = "Continue", continueDisabled,
  activeStep, // "service" | "package" | "casket" | "addons"
  confirmationStatus = "draft",
  // "draft" | "awaiting" | "confirmed" | "amendment_draft" |
  // "amended_awaiting" | "confirmed_updated"
  onSendForConfirmation, onViewPdf, onResend, onEditArrangement,
  // Amendment workflow
  amendmentSnapshot,
  onEnterEditMode, onFinalizeAmendment, onDiscardAmendment, onSendToCustomer,
  // Simulate + delivery (prototype + confirmed state)
  onSimulateSign, onSendSignedForm,
  // Coupon code system
  appliedCoupon = null, onApplyCoupon, onRemoveCoupon,
}) {
  /* Collapsed state — self-managed and persisted to localStorage so the
     same state survives navigation between screens (the sidebar mounts
     fresh inside each consultation screen, so component state alone
     would reset on every screen change). */
  const STORAGE_KEY = "ser-os-sidebar-collapsed";
  const [collapsed, setCollapsedState] = React.useState(() => {
    try { return localStorage.getItem(STORAGE_KEY) === "1"; } catch { return false; }
  });
  const setCollapsed = (next) => {
    setCollapsedState(next);
    try { localStorage.setItem(STORAGE_KEY, next ? "1" : "0"); } catch {}
  };

  /* ── Coupon modal state ───────────────────────────────────────── */
  const [showCouponModal, setShowCouponModal] = React.useState(false);
  const [couponInput, setCouponInput]         = React.useState("");
  const [couponError, setCouponError]         = React.useState(null);

  /* ── Notes section meatball menu ─────────────────────────────── */
  const [notesMenuOpen, setNotesMenuOpen] = React.useState(false);
  const notesMenuRef = React.useRef(null);
  const isEditable = confirmationStatus === "draft" || confirmationStatus === "amendment_draft";

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

  if (collapsed) {
    return (
      <aside onClick={() => setCollapsed(false)} style={{
        width: 48, background: "#FFFFFF", borderLeft: "1px solid #E5E7EB",
        display: "flex", flexDirection: "column", alignItems: "center",
        paddingTop: 20, gap: 10, cursor: "pointer", flexShrink: 0,
        maxHeight: "calc(100vh - 84px)", position: "sticky", top: 84,
      }} title="Expand Case Summary">
        <SerIcons.ChevronLeft size={20} color="#6B7A8F" />
        <div style={{ writingMode: "vertical-rl", transform: "rotate(180deg)", fontSize: 12, color: "#6B7A8F", letterSpacing: "0.04em" }}>
          Case Summary
        </div>
      </aside>);

  }

  const pkgPrice = selectedPackage ? selectedPackage.price : 0;
  const casketPrice = selectedCasket ? selectedCasket.included ? 0 : selectedCasket.upgrade : 0;
  const total = pkgPrice + casketPrice + (addOnTotal || 0);

  return (
    <aside style={{
      width: 384, flexShrink: 0, background: "#FFFFFF",
      borderLeft: "1px solid #E5E7EB",
      display: "flex", flexDirection: "column",
      alignSelf: "stretch",
      maxHeight: "calc(100vh - 84px)", position: "sticky", top: 84,
      overflow: "hidden",
    }}>
    {/* ── Scrollable content ─────────────────────────────── */}
    <div style={{ flex: 1, overflowY: "auto", padding: "24px 24px 12px", display: "flex", flexDirection: "column", gap: 18 }}>
      {/* Header */}
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
        <div>
          <h2 style={{ font: "500 20px/28px Inter", letterSpacing: "-0.449px", color: "#1F3A60", margin: 0 }}>
            Case Summary
          </h2>
          <span style={{ fontSize: 13, color: "#6B7A8F", letterSpacing: "-0.15px", fontFeatureSettings: "'tnum'" }}>
            {caseDetails.quotationId}
          </span>
        </div>
        <button
          onClick={() => setCollapsed(true)}
          aria-label="Collapse Case Summary"
          title="Collapse Case Summary"
          style={{
            background: "transparent", border: "none", padding: 4, cursor: "pointer", color: "#9CA8B8",
          }}
        ><SerIcons.ChevronRight size={20} /></button>
      </div>

      {/* Case Details — header outside box, Edit pill next to title.
          Data sits in a bordered card to match Order Summary's line-item visual. */}
      <section>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
          <h3 style={{ font: "500 16px/22px Inter", letterSpacing: "-0.313px", color: "#1F3A60", margin: 0 }}>Case Details</h3>
          <EditPill onClick={onEditCase} />
        </div>
        <div style={{
          padding: 12, borderRadius: 10,
          background: "#FFFFFF", border: "1px solid #E5E7EB",
          display: "flex", flexDirection: "column", gap: 8,
          fontSize: 13, color: "#1F3A60", letterSpacing: "-0.15px",
        }}>
          <SidebarKV label="Contact" value={caseDetails.contact} />
          {caseDetails.phone && <SidebarKV label="Phone" value={fmtPhone(caseDetails.phone)} />}
          <SidebarKV label="Need Type" value={caseDetails.needType === "pre_need" ? "Pre-Need" : "At-Need"} />
          {/* Deceased Name + Religion intentionally live in the Service
              Summary section below — they're not duplicated here. */}
        </div>
      </section>

      <div style={{ height: 1, background: "#E5E7EB" }} />

      {/* Service Summary — non-product service capture (Odoo-aligned).
          Clickable card with Edit pill that jumps to the Service Summary tab.
          Shows partial state when fields are filled. */}
      <ServiceSummarySidebarSection
        serviceData={serviceData}
        workspace={caseBrand === "fountains" ? "fountains" : "serenity"}
        active={activeStep === "service"}
        onJump={() => onJumpTo && onJumpTo("service")}
      />

      <div style={{ height: 1, background: "#E5E7EB" }} />

      {/* Line items */}
      <section>
        <h3 style={{ font: "500 16px/22px Inter", letterSpacing: "-0.313px", color: "#1F3A60", margin: "0 0 10px" }}>Order Summary</h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          <LineItem
            label={selectedPackage ? selectedPackage.name : "Package"}
            meta={selectedPackage ? "Base Package" : "No item"}
            tag={selectedPackage && selectedPackage.venueLabel}
            price={selectedPackage ? formatPrice(selectedPackage.price) : "$0"}
            empty={!selectedPackage}
            active={activeStep === "package"}
            onJump={() => onJumpTo && onJumpTo("package")} />
          
          <LineItem
            label={selectedCasket ? `${selectedCasket.name} (${selectedCasket.finish})` : "Casket"}
            meta={selectedCasket ? "Casket" : "No item"}
            price={
            selectedCasket ?
            selectedCasket.included ? "Included" : `+${formatPrice(selectedCasket.upgrade)}` :
            "$0"
            }
            empty={!selectedCasket}
            active={activeStep === "casket"}
            onJump={() => onJumpTo && onJumpTo("casket")} />
          
          <LineItem
            label="Floral Arrangement"
            meta="No item" price="$0" empty />
          
          <LineItem
            label="Burial Option"
            meta="No item" price="$0" empty />
          
          <LineItem
            label="Add-on Items"
            meta={addOnCount > 0 ? `${addOnCount} item${addOnCount > 1 ? "s" : ""}` : "No item"}
            price={addOnCount > 0 ? `+${formatPrice(addOnTotal)}` : "$0"}
            empty={addOnCount === 0}
            active={activeStep === "addons"}
            onJump={() => onJumpTo && onJumpTo("addons")}
            extra={addOnCount > 0 ? <AddonBreakdown items={selectedAddOns} /> : null}
          />
          
        </div>
      </section>

      {/* Internal Note + Coupon */}
      <section>
          {/* Header row: icon, title, meatball menu (editable states only) */}
          <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
            <SerIcons.Notes size={18} color="#6B7A8F" />
            <h3 style={{ font: "500 16px/22px Inter", letterSpacing: "-0.313px", color: "#1F3A60", margin: 0, flex: 1 }}>Internal Note</h3>
            {isEditable && (
              <div ref={notesMenuRef} style={{ position: "relative" }}>
                <button
                  onClick={() => setNotesMenuOpen(!notesMenuOpen)}
                  title="More options"
                  style={{
                    background: "transparent", border: "none", cursor: "pointer",
                    color: "#9CA8B8", padding: "2px 6px", borderRadius: 4,
                    fontSize: 18, lineHeight: "1", display: "flex", alignItems: "center",
                    letterSpacing: "0.08em",
                  }}
                >···</button>
                {notesMenuOpen && (
                  <div style={{
                    position: "absolute", right: 0, top: "calc(100% + 4px)", zIndex: 30,
                    background: "#FFFFFF", border: "1px solid #E5E7EB",
                    borderRadius: 8, boxShadow: "0 4px 16px rgba(0,0,0,0.10)",
                    minWidth: 190, overflow: "hidden",
                  }}>
                    <button
                      onClick={() => {
                        setNotesMenuOpen(false);
                        setCouponInput("");
                        setCouponError(null);
                        setShowCouponModal(true);
                      }}
                      style={{
                        width: "100%", textAlign: "left",
                        padding: "10px 14px", background: "transparent",
                        border: "none", cursor: "pointer",
                        fontFamily: "inherit", fontSize: 13, color: "#1F3A60",
                        display: "flex", alignItems: "center", gap: 8,
                      }}
                    >
                      <SerIcons.Tag size={16} color="#6B7A8F" />
                      Apply Coupon Code
                    </button>
                    {(appliedCoupon || []).length > 0 && (
                      <button
                        onClick={() => { setNotesMenuOpen(false); onRemoveCoupon && onRemoveCoupon(); }}
                        style={{
                          width: "100%", textAlign: "left",
                          padding: "10px 14px", background: "transparent",
                          border: "none", borderTop: "1px solid #F0F1F4", cursor: "pointer",
                          fontFamily: "inherit", fontSize: 13, color: "#A35854",
                          display: "flex", alignItems: "center", gap: 8,
                        }}
                      >
                        <SerIcons.Close size={16} color="#A35854" />
                        Remove All Coupons
                      </button>
                    )}
                  </div>
                )}
              </div>
            )}
          </div>
          <Textarea placeholder="Add internal notes (FD use only)…" rows={3} value={notes || ""} readOnly={!setNotes} onChange={setNotes ? (e) => setNotes(e.target.value) : undefined} />
          {/* Coupon chips — one per applied coupon, stacked */}
          {(appliedCoupon || []).length > 0 && (
            <div style={{ marginTop: 8, display: "flex", flexDirection: "column", gap: 5 }}>
              {(appliedCoupon || []).map((c) => (
                <div key={c.code} style={{
                  display: "flex", alignItems: "center", gap: 6,
                  padding: "6px 10px", borderRadius: 6,
                  background: c.type === "discount" ? "#FDF4E3" : "#EAF2E3",
                  border: `1px solid ${c.type === "discount" ? "#F5D9A0" : "#C4D9B8"}`,
                }}>
                  <SerIcons.Tag size={13} color={c.type === "discount" ? "#9A6B1F" : "#5B7D4F"} />
                  <span style={{
                    flex: 1, fontSize: 12, fontWeight: 500, letterSpacing: "-0.1px",
                    color: c.type === "discount" ? "#9A6B1F" : "#5B7D4F",
                  }}>
                    {c.code}
                    {c.type === "discount" && ` — $${c.amount} off subtotal`}
                    {c.type === "freeitem"  && ` — ${c.label}`}
                  </span>
                  {isEditable && (
                    <button
                      onClick={() => onRemoveCoupon && onRemoveCoupon(c.code)}
                      title={`Remove ${c.code}`}
                      style={{ background: "transparent", border: "none", cursor: "pointer", padding: 0, display: "flex" }}
                    >
                      <SerIcons.Close size={13} color={c.type === "discount" ? "#9A6B1F" : "#5B7D4F"} />
                    </button>
                  )}
                </div>
              ))}
            </div>
          )}
        </section>

      {/* Arrangement stage indicator — always visible, calm and non-dominant.
          Colour-coded against the Serenity status palette: neutral navy-grey
          for Draft, warm amber for Awaiting states, muted green for Confirmed.
          Amendment Draft uses a soft blue-navy tint.
          sublabel provides secondary context without cluttering the label. */}
      {(() => {
        const stageCfg = {
          draft:             { bg: "#F0F4F8", dot: "#9CA8B8", fg: "#1F3A60",  label: "Working Arrangement",              sublabel: null,                                      badge: null },
          awaiting:          { bg: "#FDF4E3", dot: "#C28A45", fg: "#9A6B1F",  label: "Awaiting Customer Signature",     sublabel: "Customer reviewing and signing via Odoo", badge: "Odoo" },
          confirmed:         { bg: "#EAF2E3", dot: "#9CAE82", fg: "#5B7D4F",  label: "Confirmed",                       sublabel: "Signed and confirmed via Odoo",           badge: null },
          amendment_draft:   { bg: "#E8EDF5", dot: "#6D8EC5", fg: "#2D4E7D",  label: "Amendment Draft",                 sublabel: "Editing a confirmed arrangement",          badge: null },
          amended_awaiting:  { bg: "#FDF4E3", dot: "#C28A45", fg: "#9A6B1F",  label: "Amendment Awaiting Signature",    sublabel: "Awaiting customer re-signing via Odoo",   badge: "Odoo" },
          confirmed_updated: { bg: "#EAF2E3", dot: "#9CAE82", fg: "#5B7D4F",  label: "Confirmed",                       sublabel: "Updated arrangement confirmed via Odoo",  badge: null },
        };
        const cfg = stageCfg[confirmationStatus] || stageCfg.draft;
        if (confirmationStatus === "draft" || !confirmationStatus) return null;
        return (
          <div style={{
            display: "flex", alignItems: "flex-start", gap: 10,
            padding: "10px 12px", borderRadius: 8, background: cfg.bg,
          }}>
            {/* Status dot — top-aligned so it sits beside the label, not sublabel */}
            <span style={{ width: 7, height: 7, borderRadius: "50%", flexShrink: 0, background: cfg.dot, marginTop: 4 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 6 }}>
                <span style={{ fontSize: 12, fontWeight: 600, letterSpacing: "-0.1px", color: cfg.fg }}>
                  {cfg.label}
                </span>
                {cfg.badge && (
                  <span style={{
                    fontSize: 10, fontWeight: 500, letterSpacing: "0.04em",
                    color: "#9CA8B8", background: "#FFFFFF",
                    padding: "2px 6px", borderRadius: 4,
                    border: "1px solid #E5E7EB", flexShrink: 0,
                    textTransform: "uppercase",
                  }}>{cfg.badge}</span>
                )}
              </div>
              {cfg.sublabel && (
                <div style={{ fontSize: 11, color: cfg.fg, opacity: 0.75, marginTop: 2, letterSpacing: "-0.1px" }}>
                  {cfg.sublabel}
                </div>
              )}
            </div>
          </div>
        );
      })()}

    </div>{/* end scrollable content */}

      {/* ── Sticky bottom: compact pricing + actions ───────── */}
      <div style={{
        borderTop: "1px solid #E5E7EB", background: "#FFFFFF",
        padding: "12px 20px 16px",
        display: "flex", flexDirection: "column", gap: 10,
        flexShrink: 0,
      }}>
        {/* Compact pricing — coupon-aware, pre-GST methodology, stacked coupons */}
        {(() => {
          const fmt = (n) => "$" + n.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
          const coupons = appliedCoupon || [];
          const discountCoupons = coupons.filter((c) => c.type === "discount");
          const totalCouponAmt  = discountCoupons.reduce((sum, c) => sum + (c.amount || 0), 0);
          const subtotal = total;
          const adjustedSubtotal = Math.max(0, subtotal - totalCouponAmt);
          const gst = adjustedSubtotal * 0.09;
          const finalTotal = adjustedSubtotal * 1.09;
          return (
            <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <span style={{ fontSize: 12, color: "#9CA8B8" }}>Subtotal (before GST)</span>
                <span style={{ fontSize: 12, color: "#9CA8B8", fontFeatureSettings: "'tnum'" }}>{fmt(subtotal)}</span>
              </div>
              {discountCoupons.map((c) => (
                <div key={c.code} style={{ display: "flex", justifyContent: "space-between" }}>
                  <span style={{ fontSize: 12, color: "#9A6B1F" }}>Coupon ({c.code})</span>
                  <span style={{ fontSize: 12, color: "#9A6B1F", fontFeatureSettings: "'tnum'" }}>−{fmt(c.amount || 0)}</span>
                </div>
              ))}
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <span style={{ fontSize: 12, color: "#9CA8B8" }}>GST (9%)</span>
                <span style={{ fontSize: 12, color: "#9CA8B8", fontFeatureSettings: "'tnum'" }}>{fmt(gst)}</span>
              </div>
              <div style={{ height: 1, background: "#F0F1F4", margin: "4px 0" }} />
              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                <span style={{ fontSize: 13, fontWeight: 500, color: "#1F3A60" }}>Total Payable</span>
                <span style={{ fontSize: 20, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.3px", fontFeatureSettings: "'tnum'" }}>
                  {fmt(finalTotal)}
                </span>
              </div>
            </div>
          );
        })()}

        {/* Amendment Draft: price delta + Finalise / Discard */}
        {confirmationStatus === "amendment_draft" ? (
          <React.Fragment>
            {amendmentSnapshot && (() => {
              const origSubtotal = amendmentSnapshot.confirmedTotal;
              const newSubtotal  = total;
              const subtotalDelta = newSubtotal - origSubtotal;
              const gstDelta      = subtotalDelta * 0.09;
              const totalDelta    = subtotalDelta * 1.09;
              const fmtAbs  = (n) => "$" + Math.abs(n).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
              const fmtSgn  = (n) => (n === 0 ? "No change" : (n > 0 ? "+" : "−") + fmtAbs(n));
              const deltaColor = subtotalDelta === 0 ? "#6B7A8F" : subtotalDelta > 0 ? "#9A6B1F" : "#5B7D4F";
              return (
                <div style={{
                  padding: "10px 12px", borderRadius: 8,
                  background: "#F0F4F8", display: "flex", flexDirection: "column", gap: 5, fontSize: 12,
                }}>
                  <div style={{ display: "flex", justifyContent: "space-between", color: "#6B7A8F" }}>
                    <span>Original subtotal</span>
                    <span style={{ fontWeight: 500, color: "#1F3A60", fontFeatureSettings: "'tnum'" }}>
                      {formatPrice(origSubtotal)}
                    </span>
                  </div>
                  <div style={{ display: "flex", justifyContent: "space-between", color: "#6B7A8F" }}>
                    <span>Revised subtotal</span>
                    <span style={{ fontWeight: 500, color: "#1F3A60", fontFeatureSettings: "'tnum'" }}>
                      {formatPrice(newSubtotal)}
                    </span>
                  </div>
                  {subtotalDelta !== 0 && (
                    <div style={{ display: "flex", justifyContent: "space-between", color: "#9CA8B8" }}>
                      <span>GST impact (9%)</span>
                      <span style={{ fontFeatureSettings: "'tnum'" }}>{fmtSgn(gstDelta)}</span>
                    </div>
                  )}
                  <div style={{ height: 1, background: "#DDE4EE", margin: "2px 0" }} />
                  <div style={{
                    display: "flex", justifyContent: "space-between",
                    color: deltaColor, fontWeight: 600, fontSize: 13,
                  }}>
                    <span>Total payable change</span>
                    <span style={{ fontFeatureSettings: "'tnum'" }}>{fmtSgn(totalDelta)}</span>
                  </div>
                </div>
              );
            })()}
            <Button
              variant="primary-navy" size="md"
              style={{ width: "100%" }}
              onClick={onFinalizeAmendment}>
              Review &amp; Confirm Amendment
            </Button>
            <Button
              variant="outline" size="md"
              style={{ width: "100%" }}
              onClick={onDiscardAmendment}>
              Discard Changes
            </Button>
          </React.Fragment>

        ) : confirmationStatus === "awaiting" || confirmationStatus === "amended_awaiting" ? (
          /* ── Awaiting / Amended-Awaiting — workflow actions replace navigation ── */
          <React.Fragment>
            {/* Primary: view the pending PDF in Odoo */}
            <Button
              variant="primary-navy" size="md"
              style={{ width: "100%" }}
              icon={<SerIcons.Document size={18} />}
              onClick={onViewPdf}>
              View Service Summary Form
            </Button>

            {/* Prototype-only simulate button — clearly distinguished from real actions */}
            {onSimulateSign && (
              <div style={{
                padding: "10px 12px", borderRadius: 8,
                border: "1px dashed #D1D5DB", background: "#FAFAFA",
                display: "flex", flexDirection: "column", gap: 8,
              }}>
                <p style={{ margin: 0, fontSize: 11, color: "#9CA8B8", letterSpacing: "-0.1px", fontWeight: 500, textTransform: "uppercase", letterSpacing: "0.04em" }}>
                  Prototype only
                </p>
                <Button
                  variant="dashed" size="sm"
                  style={{ width: "100%", fontSize: 13 }}
                  onClick={onSimulateSign}>
                  ⚙ Simulate: Customer Signs in Odoo
                </Button>
              </div>
            )}

            {/* Secondary controls */}
            <div style={{ display: "flex", gap: 8 }}>
              <Button variant="outline" size="sm" style={{ flex: 1 }} onClick={onResend}>
                Resend
              </Button>
              <Button variant="ghost" size="sm" style={{ flex: 1 }} onClick={onEditArrangement}>
                Edit Arrangement
              </Button>
            </div>
            <p style={{ margin: 0, fontSize: 12, color: "#9CA8B8", textAlign: "center", letterSpacing: "-0.15px", lineHeight: "17px" }}>
              The customer receives the proposal through Odoo and signs digitally. The FD App updates automatically once confirmed.
            </p>
          </React.Fragment>

        ) : confirmationStatus === "confirmed" ? (
          /* ── Confirmed — view signed doc, notify customer, enter edit mode ── */
          <React.Fragment>
            <Button
              variant="primary-navy" size="md"
              style={{ width: "100%" }}
              icon={<SerIcons.Document size={18} />}
              onClick={onViewPdf}>
              View Signed Service Summary Form
            </Button>
            {onSendSignedForm && (
              <Button
                variant="outline" size="md"
                style={{ width: "100%" }}
                icon={<SerIcons.Mail size={18} />}
                onClick={onSendSignedForm}>
                Send Signed Form to Customer
              </Button>
            )}
            <Button
              variant="ghost" size="md"
              style={{ width: "100%" }}
              icon={<SerIcons.Edit size={18} />}
              onClick={onEnterEditMode}>
              Enter Edit Mode
            </Button>
            <p style={{ margin: 0, fontSize: 12, color: "#5B7D4F", textAlign: "center", letterSpacing: "-0.15px", lineHeight: "17px" }}>
              Signed Service Summary Form available — confirmed by customer in Odoo.
            </p>
          </React.Fragment>

        ) : confirmationStatus === "confirmed_updated" ? (
          /* ── Confirmed (Updated) — view updated signed PDF, notify, or edit ── */
          <React.Fragment>
            <Button
              variant="primary-navy" size="md"
              style={{ width: "100%" }}
              icon={<SerIcons.Document size={18} />}
              onClick={onViewPdf}>
              View Updated Signed Form
            </Button>
            {onSendSignedForm && (
              <Button
                variant="outline" size="md"
                style={{ width: "100%" }}
                icon={<SerIcons.Mail size={18} />}
                onClick={onSendSignedForm}>
                Send Updated Form to Customer
              </Button>
            )}
            <Button
              variant="ghost" size="md"
              style={{ width: "100%" }}
              icon={<SerIcons.Edit size={18} />}
              onClick={onEnterEditMode}>
              Enter Edit Mode
            </Button>
            <p style={{ margin: 0, fontSize: 12, color: "#5B7D4F", textAlign: "center", letterSpacing: "-0.15px", lineHeight: "17px" }}>
              Amendment confirmed — all changes are locked in Odoo.
            </p>
          </React.Fragment>

        ) : (
          /* ── Draft: unified Send + Back CTAs for all consultation steps.
             Section navigation is handled by sidebar Edit pills (onJumpTo). ── */
          <React.Fragment>
            <Button
              variant="primary-navy" size="md"
              style={{ width: "100%" }}
              onClick={onSendForConfirmation}>
              Send for Confirmation
            </Button>
            <Button
              variant="outline" size="md"
              style={{ width: "100%" }}
              onClick={onContinue}>
              Back to My Cases
            </Button>
          </React.Fragment>
        )}
      </div>{/* end sticky bottom */}

      {/* ── Coupon Code Modal ─────────────────────────────────────── */}
      <Modal
        open={showCouponModal}
        onClose={() => { setShowCouponModal(false); setCouponInput(""); setCouponError(null); }}
        title="Apply Coupon Code"
        icon={<span style={{ color: "#9A6B1F", display: "flex" }}><SerIcons.Tag size={20} /></span>}
        secondary={{ label: "Done", onClick: () => { setShowCouponModal(false); setCouponInput(""); setCouponError(null); } }}
        primary={{
          label: "Add Code",
          disabled: !couponInput.trim(),
          onClick: () => {
            const code = couponInput.trim().toUpperCase();
            const alreadyApplied = (appliedCoupon || []).some((c) => c.code === code);
            if (alreadyApplied) {
              setCouponError("This code has already been applied.");
              return;
            }
            const coupon = COUPON_CODES[code];
            if (!coupon) {
              setCouponError("Invalid coupon code. Please check and try again.");
              return;
            }
            onApplyCoupon && onApplyCoupon(code, coupon);
            setCouponInput("");
            setCouponError(null);
            // Stay open so FD can add more codes
          },
        }}
      >
        <p style={{ fontSize: 14, color: "#574F40", margin: 0, letterSpacing: "-0.15px", lineHeight: "22px" }}>
          Enter one or more coupon codes. Codes stack — discounts and complimentary items are applied together per Odoo logic.
        </p>

        {/* Applied codes list */}
        {(appliedCoupon || []).length > 0 && (
          <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: "#9CA8B8", textTransform: "uppercase", letterSpacing: "0.08em" }}>
              Applied Codes
            </div>
            {(appliedCoupon || []).map((c) => (
              <div key={c.code} style={{
                display: "flex", alignItems: "center", gap: 8,
                padding: "8px 12px", borderRadius: 7,
                background: c.type === "discount" ? "#FDF4E3" : "#EAF2E3",
                border: `1px solid ${c.type === "discount" ? "#F5D9A0" : "#C4D9B8"}`,
              }}>
                <SerIcons.Tag size={13} color={c.type === "discount" ? "#9A6B1F" : "#5B7D4F"} />
                <span style={{ flex: 1, fontSize: 13, fontWeight: 500, color: c.type === "discount" ? "#9A6B1F" : "#5B7D4F" }}>
                  <strong>{c.code}</strong>
                  {c.type === "discount" && ` — $${c.amount} off subtotal`}
                  {c.type === "freeitem"  && ` — ${c.label}`}
                </span>
                <button
                  onClick={() => { onRemoveCoupon && onRemoveCoupon(c.code); setCouponError(null); }}
                  title={`Remove ${c.code}`}
                  style={{ all: "unset", cursor: "pointer", display: "flex", color: c.type === "discount" ? "#9A6B1F" : "#5B7D4F" }}
                >
                  <SerIcons.Close size={14} />
                </button>
              </div>
            ))}
          </div>
        )}

        {/* Input row */}
        <Input
          value={couponInput}
          onChange={(e) => { setCouponInput(e.target.value.toUpperCase()); setCouponError(null); }}
          onKeyDown={(e) => {
            if (e.key === "Enter" && couponInput.trim()) {
              const code = couponInput.trim().toUpperCase();
              const alreadyApplied = (appliedCoupon || []).some((c) => c.code === code);
              if (alreadyApplied) { setCouponError("This code has already been applied."); return; }
              const coupon = COUPON_CODES[code];
              if (!coupon) { setCouponError("Invalid coupon code. Please check and try again."); return; }
              onApplyCoupon && onApplyCoupon(code, coupon);
              setCouponInput(""); setCouponError(null);
            }
          }}
          placeholder="e.g. DISC100 or COMP-FLORAL"
        />
        {couponError && (
          <div style={{
            padding: "8px 12px", borderRadius: 6,
            background: "#FCE7E5", border: "1px solid #F0C4C1",
            fontSize: 13, color: "#A35854", letterSpacing: "-0.1px",
          }}>
            {couponError}
          </div>
        )}

        {/* Sample codes — clearly labelled as prototype */}
        <div style={{
          padding: "10px 12px", borderRadius: 6,
          background: "#F9F8F5", border: "1px solid #E5E7EB",
          fontSize: 12, color: "#6B7A8F", lineHeight: "20px", letterSpacing: "-0.05px",
        }}>
          <div style={{
            display: "inline-flex", alignItems: "center", gap: 5,
            padding: "2px 7px", borderRadius: 4, marginBottom: 6,
            background: "#EEF2FB", border: "1px solid #C8D8EE",
            fontSize: 10, fontWeight: 700, color: "#4A6E9A",
            textTransform: "uppercase", letterSpacing: "0.1em",
          }}>
            Prototype sample codes only
          </div>
          <br />
          <strong style={{ color: "#1F3A60", fontWeight: 600 }}>Discount codes:</strong>{" "}
          DISC50 · DISC100 · DISC150 · DISC200 · DISC250 · DISC300<br />
          <strong style={{ color: "#1F3A60", fontWeight: 600 }}>Free item codes:</strong>{" "}
          COMP-FLORAL · COMP-CANDLE · COMP-FRAME
        </div>
      </Modal>

    </aside>);

}

function LineItem({ label, meta, tag, price, empty, active, onJump, extra }) {
  return (
    <div style={{
      padding: 12, borderRadius: 8,
      background: active ? "#F4F0EA" : empty ? "transparent" : "#FFFFFF",
      border: empty && !active ? "1px solid #F0F1F4" : active ? "1px solid #574F40" : "1px solid #E5E7EB",
      display: "flex", flexDirection: "column", gap: 4
    }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 10 }}>
        <span style={{
          fontSize: 14, fontWeight: 500, color: empty ? "#6B7A8F" : "#1F3A60", letterSpacing: "-0.15px",
          flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"
        }}>{label}</span>
        <span style={{
          fontSize: 14, fontWeight: 500, letterSpacing: "-0.15px",
          color: empty ? "#9CA8B8" : "#1F3A60", fontFeatureSettings: "'tnum'",
          flexShrink: 0
        }}>{price}</span>
      </div>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, minHeight: 22 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, flex: 1, minWidth: 0 }}>
          <span style={{ fontSize: 12, color: "#6B7A8F", whiteSpace: "nowrap", flexShrink: 0 }}>{meta}</span>
          {tag && <Tag variant="cream">{tag}</Tag>}
        </div>
        {onJump && <span style={{ flexShrink: 0 }}><EditPill onClick={onJump} /></span>}
      </div>
      {extra}
    </div>);

}

/* ─────────────────────────────────────────────────────────────
   AddonBreakdown — itemised list inside the Add-on Items
   line item. Shows each selected add-on with quantity and
   line subtotal so the FD can read off the per-item cost
   without leaving the screen.
   ───────────────────────────────────────────────────────────── */
function AddonBreakdown({ items }) {
  if (!items || items.length === 0) return null;
  const chargeableItems = items.filter(
    (it) => it.itemType !== "section" && it.itemType !== "note"
  );
  if (chargeableItems.length === 0) return null;
  const subtotal = (it) => {
    if (it.chargeType === "complimentary") return 0;
    return it.unitPrice * it.quantity * (it.rentalDays || 1);
  };
  return (
    <div style={{
      marginTop: 6, paddingTop: 8,
      borderTop: "1px dashed #E5E7EB",
      display: "flex", flexDirection: "column", gap: 4,
    }}>
      {chargeableItems.map((it) => {
        const isComp    = it.chargeType === "complimentary";
        const isRentable = !!(it.rentable || it.chargeType === "per day");
        const needsDuration = isRentable && !it.rentalDays;
        return (
          <div key={it._uid || it.id} style={{
            display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 8,
            fontSize: 12, letterSpacing: "-0.1px",
          }}>
            <span style={{
              color: "#1F3A60",
              overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
              flex: 1, minWidth: 0,
            }}>
              {it.name}
              <span style={{ color: "#6B7A8F" }}> × {it.quantity}</span>
              {it.rentalDays && (
                <span style={{ color: "#9CA8B8" }}> · {it.rentalDays} day{it.rentalDays > 1 ? "s" : ""}</span>
              )}
              {needsDuration && (
                <span style={{ color: "#B45309" }}> · Duration not set</span>
              )}
            </span>
            <span style={{
              color: isComp ? "#5B7D4F" : "#1F3A60", fontWeight: 500,
              fontFeatureSettings: "'tnum'", flexShrink: 0,
            }}>
              {isComp ? "Included" : formatPrice(subtotal(it))}
            </span>
          </div>
        );
      })}
    </div>
  );
}

function PriceRow({ label, value }) {
  return (
    <div style={{
      display: "flex", justifyContent: "space-between", alignItems: "baseline",
      fontSize: 14, color: "#574F40", letterSpacing: "-0.15px",
      fontFeatureSettings: "'tnum'"
    }}>
      <span style={{ fontWeight: 500 }}>{label}</span>
      <span>{value}</span>
    </div>);

}

/* ────────────────────────────────────────────────────
   <ServiceSummarySidebarSection> — sits between Case
   Details and Order Summary in the sidebar. Reflects
   whatever's filled in on the Service Summary screen.
   ──────────────────────────────────────────────────── */
function ServiceSummarySidebarSection({ serviceData, workspace, active, onJump }) {
  const filled = serviceSummaryFilled(serviceData);
  const totals = workspace === "fountains" && serviceData
    ? familyTreeTotals(serviceData.family) : null;
  const familyHasCounts = totals && (totals.children + totals.siblings + totals.grandchildren > 0);

  const MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  const fmtD = (iso) => {
    if (!iso) return null;
    const d = String(iso).split("T")[0].split("-");
    if (d.length < 3) return iso;
    return `${parseInt(d[2], 10)} ${MONTHS[parseInt(d[1], 10) - 1]} ${d[0]}`;
  };

  // Wake venue — "Type – Specific Location" combined display
  const wakeVenueName = (() => {
    const type = serviceData?.wakeVenueType;
    if (!type && !serviceData?.wakeVenue) return null;
    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;
  })();

  // Transfer location — "Type – Location" combined display
  const transferName = (() => {
    const t = serviceData?.transferLocationType;
    if (!t) return null;
    if (t === "Hospital") {
      const h = serviceData.transferLocationHospital;
      if (!h) return "Hospital";
      const loc = h === "Others" ? (serviceData.transferLocationRemarks || null) : h;
      return loc ? `Hospital – ${loc}` : "Hospital";
    }
    if (t === "Hospice") {
      const h = serviceData.transferLocationHospice;
      if (!h) return "Hospice";
      const loc = h === "Others" ? (serviceData.transferLocationRemarks || null) : h;
      return loc ? `Hospice – ${loc}` : "Hospice";
    }
    // Home, Nursing Home, Coroner, Other — remarks holds the address/detail
    const remarks = serviceData.transferLocationRemarks;
    return remarks ? `${t} – ${remarks}` : t;
  })();

  const embalmingOpts = Array.isArray(serviceData?.embalmingOptions) ? serviceData.embalmingOptions : [];
  const embalmingSummary = (() => {
    if (embalmingOpts.length === 0) return null;
    if (embalmingOpts.length >= 3) return `${embalmingOpts.length} options selected`;
    const labels = embalmingOpts.map(id => {
      const found = (window.EMBALMING_OPTIONS || []).find(o => o.id === id);
      return found ? found.label.replace(" Required", "").replace(" Case Handling", "") : id;
    });
    return labels.join(", ");
  })();

  const isCremation = serviceData?.cremationOrBurial === "cremation";
  const religion = serviceData?.religion ? titleCase(serviceData.religion) : null;
  const arrangementLabel = serviceData?.cremationOrBurial
    ? serviceData.cremationOrBurial.charAt(0).toUpperCase() + serviceData.cremationOrBurial.slice(1)
    : null;
  const identityMeta = [religion, arrangementLabel].filter(Boolean).join("  ·  ");

  const wakeDate = fmtD(serviceData?.wakeStartDate);
  const wakeDurNum = parseInt(serviceData?.wakeDuration, 10);
  const wakeDurText = wakeDurNum > 0 ? `${wakeDurNum} ${wakeDurNum === 1 ? "Day" : "Days"}` : null;
  const wakeMeta = [wakeDate, wakeDurText].filter(Boolean).join("  ·  ");

  const funeralDate = fmtD(serviceData?.dispositionDate);

  const finalRestingLoc = (() => {
    if (!isCremation) return null;
    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);
  })();
  const finalRestingDate = isCremation ? fmtD(serviceData?.finalRestingDate) : null;

  // Shared style tokens (plain objects, not components — avoids defining components in render)
  const ss = {
    microlabel: {
      fontSize: 11, fontWeight: 600, color: "#6B7A8F",
      letterSpacing: "-0.05px", marginBottom: 4,
    },
    primary:    { fontSize: 13, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.15px", lineHeight: "19px" },
    meta:       { fontSize: 12, color: "#9CA8B8", marginTop: 2, letterSpacing: "-0.05px" },
    sep:        { height: 1, background: "#F4F5F8", margin: "12px 0" },
  };

  // Build groups list (null entries filtered out before render)
  const groups = [

    serviceData?.deceasedName ? { key: "id", node:
      <div>
        <div style={{ fontSize: 14, fontWeight: 600, color: "#1F3A60", letterSpacing: "-0.2px", lineHeight: "20px" }}>
          {serviceData.deceasedName}
        </div>
        {identityMeta && <div style={ss.meta}>{identityMeta}</div>}
      </div>
    } : null,

    (wakeVenueName || wakeMeta) ? { key: "wake", node:
      <div>
        <div style={ss.microlabel}>Wake</div>
        {wakeVenueName && <div style={ss.primary}>{wakeVenueName}</div>}
        {wakeMeta && <div style={ss.meta}>{wakeMeta}</div>}
      </div>
    } : null,

    funeralDate ? { key: "funeral", node:
      <div>
        <div style={ss.microlabel}>Funeral</div>
        <div style={ss.primary}>{funeralDate}</div>
      </div>
    } : null,

    transferName ? { key: "transfer", node:
      <div>
        <div style={ss.microlabel}>Transfer Location</div>
        <div style={ss.primary}>{transferName}</div>
      </div>
    } : null,

    embalmingSummary ? { key: "embalming", node:
      <div>
        <div style={ss.microlabel}>Embalming</div>
        <div style={ss.primary}>{embalmingSummary}</div>
      </div>
    } : null,

    (finalRestingLoc || finalRestingDate) ? { key: "resting", node:
      <div>
        <div style={ss.microlabel}>Final resting</div>
        {finalRestingLoc && <div style={ss.primary}>{finalRestingLoc}</div>}
        {finalRestingDate && <div style={ss.meta}>{finalRestingDate}</div>}
      </div>
    } : null,

    familyHasCounts ? { key: "family", node:
      <div style={{ display: "flex", flexDirection: "column", gap: 3 }}>
        <div style={ss.microlabel}>Family tree</div>
        {totals.children      > 0 && <SidebarKV label="Children"      value={totals.children} />}
        {totals.siblings      > 0 && <SidebarKV label="Siblings"      value={totals.siblings} />}
        {totals.grandchildren > 0 && <SidebarKV label="Grandchildren" value={totals.grandchildren} />}
      </div>
    } : null,

  ].filter(Boolean);

  return (
    <section>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
        <h3 style={{ font: "500 16px/22px Inter", letterSpacing: "-0.313px", color: "#1F3A60", margin: 0 }}>
          Service Summary
        </h3>
        {onJump && <EditPill onClick={onJump} />}
      </div>
      <div style={{
        padding: 14, borderRadius: 10,
        background: active ? "#F4F0EA" : "#FFFFFF",
        border: `1px solid ${active ? "#574F40" : "#E5E7EB"}`,
        transition: "background 140ms ease, border-color 140ms ease",
      }}>
        {filled && groups.length > 0 ? (
          <div>
            {groups.map((g, i) => (
              <React.Fragment key={g.key}>
                {i > 0 && <div style={ss.sep} />}
                {g.node}
              </React.Fragment>
            ))}
          </div>
        ) : (
          <span style={{ fontSize: 13, color: "#9CA8B8", letterSpacing: "-0.15px" }}>
            No service details added yet
          </span>
        )}
      </div>
    </section>
  );
}

function SidebarKV({ label, value }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", gap: 8, alignItems: "baseline" }}>
      <span style={{ color: "#6B7A8F", fontSize: 13 }}>{label}</span>
      <span style={{
        color: "#1F3A60", fontWeight: 500, textAlign: "right",
        fontSize: 13, letterSpacing: "-0.15px",
        overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
        maxWidth: "60%",
      }}>{value}</span>
    </div>
  );
}

Object.assign(window, { OrderSummarySidebar, LineItem, ServiceSummarySidebarSection, AddonBreakdown });