/* SER-OS — Case card (My Cases & Case Archive) */

function fmtWakeSchedule(c) {
  if (!c.wakeDate) return "—";
  const dur = c.wakeDuration
    ? ` (${c.wakeDuration} Day${c.wakeDuration === 1 ? "" : "s"})`
    : "";
  if (!c.wakeEndDate || c.wakeDate === c.wakeEndDate) {
    return `${c.wakeDate}${dur}`;
  }
  return `${c.wakeDate} – ${c.wakeEndDate}${dur}`;
}

function CaseCard({ caseData, mode = "active", onContinue, onView, onEdit, onArchive, onRestore, onOpenContact, onEnterEditMode }) {
  const c = caseData;
  const updatedDisplay = c.updatedAt ? relativeTime(c.updatedAt) : (c.updated || "—");
  const contactClickable = !!(onOpenContact && c.contactId);
  // Inside the Case Archive, the surrounding page already implies
  // "archived" — so we surface ONLY "Cancelled" status pills. Non-cancelled
  // archived cases render with no pill at all (calmer, less CRM-like).
  const showStatusPill = (mode === "active" && c.pillStatus != null) || (mode === "archived" && c.status === "Cancelled");
  // Confirmed-flow cases: confirmed, confirmed_updated, awaiting, amended_awaiting
  // These use the Read-Only Summary path instead of Continue Case.
  const isConfirmedFlowCase = ["confirmed", "confirmed_updated", "awaiting", "amended_awaiting"].includes(c.workflowStatus);

  return (
    <article style={{
      background: "#FFFFFF", border: "1px solid var(--border-subtle)", borderRadius: 12,
      padding: 24, display: "flex", flexDirection: "column", gap: 18,
      opacity: mode === "archived" ? 0.96 : 1,
    }}>
      <header style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          <h2 style={{ font: "500 22px/30px var(--font-ui, Inter)", letterSpacing: "-0.439px", color: "var(--fg-primary)", margin: 0 }}>
            {c.deceased}
          </h2>
          <div style={{ display: "flex", alignItems: "center", gap: 16, color: "var(--fg-secondary)", fontSize: 13 }}>
            {contactClickable ? (
              <button
                onClick={(e) => { e.stopPropagation(); onOpenContact(c.contactId); }}
                style={{
                  all: "unset", cursor: "pointer",
                  display: "inline-flex", alignItems: "center", gap: 6,
                  color: "var(--fg-primary)",
                  borderBottom: "1px dashed transparent",
                  transition: "border-color 120ms ease",
                }}
                onMouseEnter={(e) => e.currentTarget.style.borderBottomColor = "var(--brand-navy)"}
                onMouseLeave={(e) => e.currentTarget.style.borderBottomColor = "transparent"}
                aria-label={`View contact details for ${c.contact}`}
              >
                <SerIcons.User size={14} />{c.contact}
              </button>
            ) : (
              <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
                <SerIcons.User size={14} />{c.contact}
              </span>
            )}
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
              <SerIcons.Phone size={13} />{c.phone}
            </span>
          </div>
        </div>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
          {(c.needType === "pre_need") ? (
            <span style={{
              display: "inline-flex", alignItems: "center", gap: 5,
              padding: "3px 9px", borderRadius: 20,
              background: "var(--surface-chip)", border: "1px solid var(--brand-tan-soft)",
              fontSize: 11, fontWeight: 600, color: "var(--brand-navy)",
              letterSpacing: "0.02em", whiteSpace: "nowrap",
            }}>
              <SerIcons.Star size={10} color="var(--brand-navy)" />
              PRE-NEED
            </span>
          ) : (
            <span style={{
              display: "inline-flex", alignItems: "center", gap: 5,
              padding: "3px 9px", borderRadius: 20,
              background: "var(--slate-75, #f1f5f9)", border: "1px solid var(--slate-150, #e2e8f0)",
              fontSize: 11, fontWeight: 600, color: "var(--fg-secondary)",
              letterSpacing: "0.02em", whiteSpace: "nowrap",
            }}>
              AT-NEED
            </span>
          )}
          {showStatusPill && <StatusPill status={c.pillStatus || c.status} />}
        </div>
      </header>

      <div style={{
        display: "grid", gridTemplateColumns: "1fr 1fr", rowGap: 16, columnGap: 24,
        padding: "16px 0", borderTop: "1px solid var(--slate-150)", borderBottom: "1px solid var(--slate-150)",
      }}>
        <FieldRow label="Case Number" value={c.caseNumber} />
        <FieldRow label="Religion" value={c.religion} />
        <FieldRow label="Last Updated" value={updatedDisplay} icon={<SerIcons.Clock size={18} color="var(--fg-secondary)" />} />
        <FieldRow label="Assigned FDs" value={Array.isArray(c.fd) ? c.fd.join(", ") : (c.fd || "—")} />
        <FieldRow label="Wake Schedule" value={fmtWakeSchedule(c)} />
        <FieldRow label="Funeral Date" value={c.funeralDate || "—"} />
      </div>

      <div>
        <div style={{ fontSize: 13, color: "var(--fg-secondary)", marginBottom: 10 }}>Arrangement Summary</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          <SummaryRow label="Package:"             value={c.package}     muted={c.package === "Not selected"} />
          <SummaryRow label="Add-ons:"            value={c.addons || "0 items"} muted={!c.addons || c.addons === "0 items"} />
          <SummaryRow label="Funeral Arrangement:" value={c.serviceType} muted={c.serviceType === "Not decided"} />
        </div>
      </div>

      {mode === "active" ? (
        isConfirmedFlowCase ? (
          /* ── Confirmed / Awaiting: View Summary + Edit Mode + Cancel ── */
          <div style={{ display: "flex", gap: 10, alignItems: "center", marginTop: "auto" }}>
            <Button
              variant="outline" size="md" style={{ flex: 1, height: 48 }}
              icon={<SerIcons.Eye size={18} />}
              onClick={onView}
            >
              View Details
            </Button>
            <IconButton
              onClick={onEnterEditMode}
              title="Enter Edit Mode"
              style={{ width: 48, height: 48, color: "var(--fg-secondary)", background: "var(--surface-chip)" }}
            >
              <SerIcons.Edit size={18} />
            </IconButton>
            <OverflowMenu
              items={[
                { label: "Cancel Case", icon: <SerIcons.Close size={14} />, onClick: onArchive, danger: true },
              ]}
              trigger={
                <button style={{
                  all: "unset", cursor: "pointer",
                  width: 48, height: 48, borderRadius: 8, background: "var(--surface-chip)",
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  color: "var(--fg-primary)",
                }}>
                  <SerIcons.More size={18} />
                </button>
              }
            />
          </div>
        ) : (
          /* ── Draft / Active: Continue Case + Cancel ── */
          <div style={{ display: "flex", gap: 10, alignItems: "center", marginTop: "auto" }}>
            <Button variant="primary-navy" size="md" style={{ flex: 1, height: 48 }}
              iconRight={<SerIcons.Arrow size={18} />}
              onClick={onContinue}
            >
              Continue Case
            </Button>
            <OverflowMenu
              items={[
                { label: "Cancel Case", icon: <SerIcons.Close size={14} />, onClick: onArchive, danger: true },
              ]}
              trigger={
                <button style={{
                  all: "unset", cursor: "pointer",
                  width: 48, height: 48, borderRadius: 8, background: "var(--surface-chip)",
                  display: "inline-flex", alignItems: "center", justifyContent: "center",
                  color: "var(--fg-primary)",
                }}>
                  <SerIcons.More size={18} />
                </button>
              }
            />
          </div>
        )
      ) : (
        <div style={{ display: "flex", gap: 10, alignItems: "center", marginTop: "auto" }}>
          <Button variant="primary-navy" size="md" style={{ flex: 1, height: 48 }}
            icon={<SerIcons.RotateCcw size={18} />}
            onClick={onRestore}
          >
            Restore Case
          </Button>
          <IconButton onClick={onView} style={{ width: 48, height: 48, background: "var(--surface-chip)" }}><SerIcons.Eye size={20} /></IconButton>
        </div>
      )}
    </article>
  );
}

function FieldRow({ label, value, sub, icon }) {
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
      <span style={{ fontSize: 12, color: "var(--fg-secondary)" }}>{label}</span>
      <span style={{ fontSize: 14, fontWeight: 500, color: "var(--fg-primary)", display: "inline-flex", alignItems: "center", gap: 6 }}>
        {icon}{value}
      </span>
      {sub && <span style={{ fontSize: 12, color: "var(--fg-secondary)" }}>{sub}</span>}
    </div>
  );
}

function SummaryRow({ label, value, muted }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14 }}>
      <span style={{ color: "var(--fg-secondary)" }}>{label}</span>
      <span style={{ color: muted ? "var(--fg-tertiary)" : "var(--fg-primary)", fontWeight: muted ? 400 : 500 }}>{value}</span>
    </div>
  );
}

/* Minimal popover menu used for the ⋯ overflow button.
   Self-contained so it can be reused in CaseListView too. */
function OverflowMenu({ items = [], align = "right", trigger }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const dropStyle = useSmartPosition(open, ref, { maxHeight: 400, minWidth: 180, align });

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

  return (
    <div ref={ref} style={{ position: "relative" }}>
      {trigger ? (
        React.cloneElement(trigger, { onClick: (e) => { e.stopPropagation(); setOpen((o) => !o); } })
      ) : (
        <IconButton
          onClick={(e) => { e.stopPropagation(); setOpen((o) => !o); }}
          style={{ width: 48, height: 48 }}
          aria-haspopup="menu"
          aria-expanded={open}
        >
          <SerIcons.More size={18} />
        </IconButton>
      )}
      {open && dropStyle && (
        <div
          role="menu"
          style={{
            ...dropStyle,
            background: "var(--surface-card, #fff)",
            border: "1px solid var(--border-subtle)",
            borderRadius: "var(--radius-lg, 12px)",
            boxShadow: "var(--shadow-overlay, 0 8px 24px rgba(15,23,42,0.12))",
            padding: 6,
            display: "flex", flexDirection: "column",
          }}
        >
          {items.map((it, i) => (
            <OverflowMenuItem
              key={i}
              icon={it.icon}
              danger={it.danger}
              onClick={() => { setOpen(false); it.onClick && it.onClick(); }}
            >
              {it.label}
            </OverflowMenuItem>
          ))}
        </div>
      )}
    </div>
  );
}

function OverflowMenuItem({ children, icon, danger, onClick }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      role="menuitem"
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        all: "unset",
        cursor: "pointer",
        display: "flex", alignItems: "center", gap: 10,
        width: "100%", boxSizing: "border-box",
        padding: "10px 12px",
        borderRadius: "var(--radius-md, 8px)",
        fontSize: 14, fontWeight: 500,
        letterSpacing: "-0.15px",
        color: danger ? "var(--status-danger)" : "var(--fg-primary)",
        background: hover ? "var(--slate-75)" : "transparent",
        transition: "background 100ms ease",
      }}
    >
      {icon}<span>{children}</span>
    </button>
  );
}

Object.assign(window, { CaseCard, OverflowMenu, OverflowMenuItem });
