/* SER-OS — Screens */

/* =========================================================
   Shared filter state used by both My Cases & Case Archive.
   Preserved across Card/List view toggles by storing it one
   level up in the screen component.
   ========================================================= */


function applyCaseFilters(cases, { q, tab, datePreset, customFrom, customTo, statuses }) {
  const { from, to } = rangeForPreset(datePreset, customFrom, customTo);
  const allowedStatuses = statuses; // undefined = any
  return cases.filter((c) => {
    if (allowedStatuses && !allowedStatuses.includes(c.status)) return false;
    // Use tabCategory (which reflects workflow state) for tab filtering
    if (tab && tab !== "All" && (c.tabCategory || c.status) !== tab) return false;
    if (q) {
      const hay = `${c.deceased} ${c.contact} ${c.phone} ${c.caseNumber}`.toLowerCase();
      if (!hay.includes(q.toLowerCase())) return false;
    }
    if (c.updatedAt) {
      const t = new Date(c.updatedAt).getTime();
      if (from !== null && t < from) return false;
      if (to !== null && t >= to) return false;
    }
    return true;
  });
}

/* ── Status filter tab (reused in My Cases) ───────────────────────
   Matches the original pill-tab style from the design system:
   active = navy fill + white text; inactive = white + border.
   ────────────────────────────────────────────────────────────────── */
function FilterTab({ label, count, isActive, onClick }) {
  return (
    <button
      onClick={onClick}
      style={{
        all: "unset", cursor: "pointer",
        display: "inline-flex", alignItems: "center", gap: 8,
        padding: "10px 20px", borderRadius: 10,
        background: isActive ? "#1F3A60" : "#FFFFFF",
        color: isActive ? "#FFFFFF" : "#1F3A60",
        border: `1px solid ${isActive ? "#1F3A60" : "#E5E7EB"}`,
        fontSize: 14, fontWeight: 500, letterSpacing: "-0.15px",
        transition: "background 120ms ease, color 120ms ease, border-color 120ms ease",
        whiteSpace: "nowrap",
      }}
    >
      {label}
      <span style={{
        fontSize: 12, fontWeight: 600,
        background: isActive ? "rgba(255,255,255,0.18)" : "#F0F4F8",
        color: isActive ? "#FFFFFF" : "#6B7A8F",
        padding: "1px 7px", borderRadius: 6,
        letterSpacing: "-0.05px",
        minWidth: 22, textAlign: "center",
      }}>{count}</span>
    </button>
  );
}

/* =========================================================
   1. MY CASES — active workspace
   ========================================================= */
function MyCasesScreen({ cases, onOpenCase, onCreateNew, onArchiveCase, onGoToArchive, onOpenContact, archivedCount, onEnterEditMode }) {
  const [statusFilter, setStatusFilter] = React.useState("All");
  // "All" | "Draft" | "Awaiting" | "Confirmed"
  const [view, setView] = React.useState("card");
  const [q, setQ] = React.useState("");
  const [datePreset, setDatePreset] = React.useState("all");
  const [customFrom, setCustomFrom] = React.useState("");
  const [customTo, setCustomTo] = React.useState("");

  // My Cases: all non-archived, non-cancelled cases
  const activeOnly = React.useMemo(
    () => cases.filter((c) => !c.archived && (c.tabCategory || "Draft") !== "Cancelled"),
    [cases]
  );

  // Counts per status bucket for the tab labels
  const bucketCounts = React.useMemo(() => ({
    Draft:     activeOnly.filter((c) => (c.tabCategory || "Draft") === "Draft").length,
    Awaiting:  activeOnly.filter((c) => (c.tabCategory || "Draft") === "Awaiting").length,
    Confirmed: activeOnly.filter((c) => (c.tabCategory || "Draft") === "Confirmed").length,
  }), [activeOnly]);

  // Pre-filter by status tab, then apply text/date search
  const filtered = React.useMemo(() => {
    const statusFiltered = statusFilter === "All"
      ? activeOnly
      : activeOnly.filter((c) => (c.tabCategory || "Draft") === statusFilter);
    return applyCaseFilters(statusFiltered, { q, tab: "All", datePreset, customFrom, customTo });
  }, [activeOnly, statusFilter, q, datePreset, customFrom, customTo]);

  const anyFilterActive = datePreset !== "all" || q.trim().length > 0 || statusFilter !== "All";

  return (
    <div style={{ padding: "32px 48px 64px", display: "flex", flexDirection: "column", gap: 24, maxWidth: 1440, margin: "0 auto", width: "100%", boxSizing: "border-box" }}>
      <header style={{ display: "flex", flexDirection: "column", gap: 4 }}>
        <h1 style={{ font: "500 28px/36px Inter", letterSpacing: "-0.5px", color: "#1F3A60", margin: 0 }}>My Cases</h1>
        <p style={{ fontSize: 14, color: "#6B7A8F", letterSpacing: "-0.15px", margin: 0 }}>
          Draft, awaiting signature, and confirmed arrangements.
        </p>
      </header>

      {/* ── Status filter tabs ─────────────────────────────────────── */}
      <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
        <FilterTab label="All"                count={activeOnly.length}      isActive={statusFilter === "All"}       onClick={() => setStatusFilter("All")} />
        <FilterTab label="Draft"              count={bucketCounts.Draft}     isActive={statusFilter === "Draft"}     onClick={() => setStatusFilter("Draft")} />
        <FilterTab label="Awaiting Signature" count={bucketCounts.Awaiting}  isActive={statusFilter === "Awaiting"}  onClick={() => setStatusFilter("Awaiting")} />
        <FilterTab label="Confirmed"          count={bucketCounts.Confirmed} isActive={statusFilter === "Confirmed"} onClick={() => setStatusFilter("Confirmed")} />
        {archivedCount > 0 && (
          <button
            onClick={onGoToArchive}
            style={{
              all: "unset", cursor: "pointer",
              display: "inline-flex", alignItems: "center", gap: 8,
              padding: "10px 20px", borderRadius: 10,
              background: "#FFFFFF", color: "#1F3A60",
              border: "1px solid #E5E7EB",
              fontSize: 14, fontWeight: 500, letterSpacing: "-0.15px",
              transition: "background 120ms ease",
              whiteSpace: "nowrap",
              marginLeft: "auto",
            }}>
            <SerIcons.Archive size={14} color="#6B7A8F" />
            View Case Archive
          </button>
        )}
      </div>

      {/* ── Search + date + view toggles ──────────────────────────── */}
      <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
        <Input
          icon={<SerIcons.Search size={18} />}
          placeholder="Search by deceased name, contact, phone, or case number..."
          value={q}
          onChange={(e) => setQ(e.target.value)}
          style={{ flex: "1 1 320px", minWidth: 240 }} />

        <DateFilter
          preset={datePreset} onPresetChange={setDatePreset}
          customFrom={customFrom} onCustomFromChange={setCustomFrom}
          customTo={customTo} onCustomToChange={setCustomTo} />

        <div style={{ display: "inline-flex", border: "1px solid #E5E7EB", borderRadius: 8, overflow: "hidden", height: 48 }}>
          <ViewToggle isActive={view === "card"} onClick={() => setView("card")} icon={<SerIcons.Grid size={18} />} label="Card" />
          <ViewToggle isActive={view === "list"} onClick={() => setView("list")} icon={<SerIcons.List size={18} />} label="List" />
        </div>
        <Button variant="primary-navy" size="lg" icon={<SerIcons.Plus size={18} />} onClick={onCreateNew} style={{ height: 48 }}>
          Create New Case
        </Button>
      </div>

      {filtered.length === 0 ?
      <CasesEmptyState
        variant={anyFilterActive ? "filtered" : "empty-active"}
        onCreateNew={onCreateNew}
        onClearFilters={() => { setQ(""); setStatusFilter("All"); setDatePreset("all"); setCustomFrom(""); setCustomTo(""); }} /> :

      view === "card" ?
      <div style={{ display: "grid", gridTemplateColumns: "repeat(2, minmax(0, 1fr))", gap: 20 }}>
        {filtered.map((c) =>
          <CaseCard
            key={c.caseNumber}
            caseData={c}
            mode="active"
            onContinue={() => onOpenCase(c)}
            onView={() => onOpenCase(c)}
            onEdit={() => onOpenCase(c)}
            onArchive={() => onArchiveCase(c)}
            onOpenContact={onOpenContact}
            onEnterEditMode={onEnterEditMode ? () => onEnterEditMode(c) : undefined} />
        )}
      </div> :

      <CaseListView
        cases={filtered} mode="active"
        onOpenCase={onOpenCase}
        onArchiveCase={onArchiveCase}
        onOpenContact={onOpenContact}
        onEnterEditMode={onEnterEditMode} />
      }
    </div>
  );
}

/* =========================================================
   1b. CASE ARCHIVE — calm secondary workspace
   Holds Cancelled cases plus any Draft/Active case the FD
   manually archived. Accessed from the My Cases header, not
   the top navigation, to keep it operationally secondary.
   ========================================================= */
function CaseArchiveScreen({ cases, onOpenCase, onRestoreCase, onOpenContact, onBackToCases }) {
  const [view, setView] = React.useState("card");
  const [q, setQ] = React.useState("");
  const [datePreset, setDatePreset] = React.useState("all");
  const [customFrom, setCustomFrom] = React.useState("");
  const [customTo, setCustomTo] = React.useState("");
  const [sort, setSort] = React.useState("recent"); // recent | oldest | name

  const archivedOnly = React.useMemo(() => cases.filter((c) => c.archived), [cases]);

  let filtered = applyCaseFilters(archivedOnly, {
    q, tab: "All", datePreset, customFrom, customTo,
  });

  filtered = [...filtered].sort((a, b) => {
    if (sort === "name") return (a.deceased || "").localeCompare(b.deceased || "");
    const at = new Date(a.updatedAt || 0).getTime();
    const bt = new Date(b.updatedAt || 0).getTime();
    return sort === "oldest" ? at - bt : bt - at;
  });

  const anyFilterActive = datePreset !== "all" || q.trim().length > 0;

  return (
    <div style={{ padding: "32px 48px 64px", display: "flex", flexDirection: "column", gap: 24, maxWidth: 1440, margin: "0 auto", width: "100%", boxSizing: "border-box" }}>
      <header style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end", gap: 16, flexWrap: "wrap" }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
          <button
            onClick={onBackToCases}
            style={{
              all: "unset", cursor: "pointer",
              display: "inline-flex", alignItems: "center", gap: 6,
              color: "#6B7A8F", fontSize: 13, letterSpacing: "-0.15px",
              marginBottom: 4,
            }}>
            <SerIcons.ChevronLeft size={14} color="#6B7A8F" />Back to My Cases
          </button>
          <h1 style={{ font: "500 28px/36px Inter", letterSpacing: "-0.5px", color: "#1F3A60", margin: 0 }}>Case Archive</h1>
          <p style={{ fontSize: 14, color: "#6B7A8F", letterSpacing: "-0.15px", margin: 0 }}>
            Cancelled and inactive cases. Restore any case to return it to your active workspace.
          </p>
        </div>
      </header>

      <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
        <Input
          icon={<SerIcons.Search size={18} />}
          placeholder="Search archive..."
          value={q}
          onChange={(e) => setQ(e.target.value)}
          style={{ flex: "1 1 320px", minWidth: 240 }} />

        <DateFilter
          preset={datePreset} onPresetChange={setDatePreset}
          customFrom={customFrom} onCustomFromChange={setCustomFrom}
          customTo={customTo} onCustomToChange={setCustomTo} />

        <SortSelect value={sort} onChange={setSort} />
        <div style={{ display: "inline-flex", border: "1px solid #E5E7EB", borderRadius: 8, overflow: "hidden", height: 48 }}>
          <ViewToggle isActive={view === "card"} onClick={() => setView("card")} icon={<SerIcons.Grid size={18} />} label="Card" />
          <ViewToggle isActive={view === "list"} onClick={() => setView("list")} icon={<SerIcons.List size={18} />} label="List" />
        </div>
      </div>

      {filtered.length === 0 ? (
        <CasesEmptyState
          variant={anyFilterActive ? "filtered" : "empty-archive"}
          onClearFilters={() => { setQ(""); setDatePreset("all"); setCustomFrom(""); setCustomTo(""); }}
        />
      ) : view === "card" ? (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(2, minmax(0, 1fr))", gap: 20 }}>
          {filtered.map((c) =>
            <CaseCard
              key={c.caseNumber}
              caseData={c}
              mode="archived"
              onView={() => onOpenCase(c)}
              onRestore={() => onRestoreCase(c)}
              onOpenContact={onOpenContact} />
          )}
        </div>
      ) : (
        <CaseListView cases={filtered} mode="archived" onOpenCase={onOpenCase} onRestoreCase={onRestoreCase} onOpenContact={onOpenContact} />
      )}
    </div>
  );
}

/* ---- Date range filter button + popover ---- */
function DateFilter({ preset, onPresetChange, customFrom, onCustomFromChange, customTo, onCustomToChange }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);

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

  const presets = [
  { id: "all", label: "All Time" },
  { id: "today", label: "Today" },
  { id: "7d", label: "Last 7 Days" },
  { id: "30d", label: "Last 30 Days" },
  { id: "month", label: "This Month" },
  { id: "custom", label: "Custom Range" }];


  const active = preset !== "all";
  const label = labelForPreset(preset, customFrom, customTo);

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button
        type="button"
        onClick={() => setOpen((o) => !o)}
        aria-haspopup="dialog"
        aria-expanded={open}
        style={{
          all: "unset",
          height: 48, padding: "0 14px",
          display: "inline-flex", alignItems: "center", gap: 10,
          background: "#FFFFFF",
          border: `1px solid ${active ? "#574F40" : "#E5E7EB"}`,
          borderRadius: 8,
          fontSize: 14, fontWeight: 500, color: "#1F3A60",
          letterSpacing: "-0.15px",
          cursor: "pointer",
          boxSizing: "border-box"
        }}>
        
        <SerIcons.Calendar size={16} color={active ? "#1F3A60" : "#6B7A8F"} />
        <span style={{ color: active ? "#1F3A60" : "#574F40" }}>{label}</span>
        <SerIcons.ChevronDown size={14} color="#6B7A8F" />
      </button>

      {open &&
      <div
        role="dialog"
        style={{
          position: "absolute",
          top: "calc(100% + 8px)",
          left: 0,
          width: 280,
          background: "#FFFFFF",
          border: "1px solid #E5E7EB",
          borderRadius: 12,
          boxShadow: "var(--shadow-overlay, 0 12px 32px rgba(15,23,42,0.12))",
          padding: 8,
          display: "flex", flexDirection: "column", gap: 2,
          zIndex: 30
        }}>
        
          {presets.map((p) =>
        <DateFilterItem
          key={p.id}
          label={p.label}
          selected={preset === p.id}
          onClick={() => {
            onPresetChange(p.id);
            if (p.id !== "custom") setOpen(false);
          }} />

        )}
          {preset === "custom" &&
        <div style={{
          borderTop: "1px solid #F0F1F4",
          marginTop: 6, paddingTop: 12, paddingLeft: 8, paddingRight: 8,
          display: "flex", flexDirection: "column", gap: 10
        }}>
              <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                <span style={{ fontSize: 12, color: "#6B7A8F", fontWeight: 500 }}>From</span>
                <input type="date" value={customFrom} onChange={(e) => onCustomFromChange(e.target.value)} style={dateInputStyle} />
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                <span style={{ fontSize: 12, color: "#6B7A8F", fontWeight: 500 }}>To</span>
                <input type="date" value={customTo} onChange={(e) => onCustomToChange(e.target.value)} style={dateInputStyle} />
              </div>
              <div style={{ display: "flex", justifyContent: "space-between", paddingTop: 4 }}>
                <button
              onClick={() => {onCustomFromChange("");onCustomToChange("");}}
              style={{ all: "unset", cursor: "pointer", fontSize: 13, color: "#6B7A8F", padding: "4px 0" }}>
              
                  Clear
                </button>
                <button
              onClick={() => setOpen(false)}
              style={{
                all: "unset", cursor: "pointer",
                fontSize: 13, fontWeight: 500, color: "#FFFFFF",
                background: "#574F40",
                padding: "6px 14px", borderRadius: 6
              }}>
              
                  Apply
                </button>
              </div>
            </div>
        }
        </div>
      }
    </div>);

}

const dateInputStyle = {
  width: "100%", boxSizing: "border-box",
  height: 38, padding: "0 12px",
  fontFamily: "inherit", fontSize: 13, color: "#1F3A60",
  background: "#FFFFFF", border: "1px solid #E5E7EB",
  borderRadius: 6, outline: "none"
};

function DateFilterItem({ label, selected, onClick }) {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        all: "unset", cursor: "pointer",
        padding: "10px 12px", borderRadius: 6,
        fontSize: 14, fontWeight: 500, letterSpacing: "-0.15px",
        color: selected ? "#1F3A60" : "#1F3A60",
        background: selected ? "#EAE2CE" : hover ? "#F3F4F6" : "transparent",
        display: "flex", justifyContent: "space-between", alignItems: "center"
      }}>
      
      <span>{label}</span>
      {selected && <SerIcons.Check size={14} color="#1F3A60" />}
    </button>);

}

function SortSelect({ value, onChange }) {
  return (
    <select
      value={value}
      onChange={(e) => onChange(e.target.value)}
      style={{
        height: 48, padding: "0 36px 0 14px",
        fontFamily: "inherit", fontSize: 14, fontWeight: 500, color: "#1F3A60",
        background: "#FFFFFF",
        border: "1px solid #E5E7EB", borderRadius: 8, outline: "none",
        appearance: "none", letterSpacing: "-0.15px", cursor: "pointer",
        backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 20 20' fill='none'><path d='M5 8l5 5 5-5' stroke='%23718096' stroke-width='1.5' stroke-linecap='round'/></svg>\")",
        backgroundRepeat: "no-repeat", backgroundPosition: "right 12px center"
      }}>
      
      <option value="recent">Sort: Most recent</option>
      <option value="oldest">Sort: Oldest first</option>
      <option value="name">Sort: Name A–Z</option>
    </select>);

}

/* ---- Empty states ---- */
function CasesEmptyState({ variant, onCreateNew, onClearFilters }) {
  const copy = {
    "empty-active": {
      title: "No active cases",
      body: "When you start a new arrangement it will appear here.",
      cta: onCreateNew && { label: "Create New Case", onClick: onCreateNew, icon: <SerIcons.Plus size={18} /> }
    },
    "empty-archive": {
      title: "No archived cases",
      body:  "Cancelled cases will appear here.",
    },
    "filtered": {
      title: "No cases match your filters",
      body: "Try clearing the date range or search to see more cases.",
      cta: onClearFilters && { label: "Clear Filters", onClick: onClearFilters, icon: <SerIcons.Close size={16} /> }
    }
  }[variant] || {};

  return (
    <div style={{
      padding: "72px 32px", textAlign: "center",
      border: "1px dashed #E5E7EB", borderRadius: 12,
      background: "#FFFFFF",
      display: "flex", flexDirection: "column", alignItems: "center", gap: 12
    }}>
      <h3 style={{ font: "500 18px/26px Inter", color: "#1F3A60", margin: 0, letterSpacing: "-0.3px" }}>{copy.title}</h3>
      <p style={{ fontSize: 14, color: "#6B7A8F", margin: 0, letterSpacing: "-0.15px", maxWidth: 380 }}>{copy.body}</p>
      {copy.cta &&
      <div style={{ marginTop: 8 }}>
          <Button variant="primary-navy" size="md" icon={copy.cta.icon} onClick={copy.cta.onClick}>
            {copy.cta.label}
          </Button>
        </div>
      }
    </div>);

}

function ViewToggle({ isActive, onClick, icon, label }) {
  return (
    <button onClick={onClick} style={{
      height: "100%", padding: "0 16px",
      background: isActive ? "#1F3A60" : "#FFFFFF",
      color: isActive ? "#FFFFFF" : "#1F3A60",
      border: "none", fontFamily: "inherit", fontSize: 14, fontWeight: 500,
      display: "inline-flex", alignItems: "center", gap: 6, cursor: "pointer"
    }}>
      {icon}{label}
    </button>);

}


function CaseListView({ cases, mode = "active", onOpenCase, onArchiveCase, onRestoreCase, onOpenContact, onEnterEditMode }) {
  return (
    <div style={{ background: "#FFFFFF", border: "1px solid #E5E7EB", borderRadius: 12, overflow: "hidden" }}>
      <div style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 0.8fr 1.2fr 150px", padding: "14px 20px", borderBottom: "1px solid #E5E7EB", background: "#FAFAFA", fontSize: 12, color: "#6B7A8F", fontWeight: 500, textTransform: "uppercase", letterSpacing: "0.04em" }}>
        <span>Deceased</span><span>Case No.</span><span>Religion</span><span>Status</span><span>Last Updated</span><span></span>
      </div>
      {cases.map((c, i) => {
        const contactClickable = !!(onOpenContact && c.contactId);
        return (
          <div key={c.caseNumber} style={{ display: "grid", gridTemplateColumns: "1.6fr 1fr 1fr 0.8fr 1.2fr 150px", padding: "16px 20px", borderBottom: i === cases.length - 1 ? "none" : "1px solid #F0F1F4", alignItems: "center", fontSize: 14, color: "#1F3A60" }}>
          <div style={{ display: "flex", flexDirection: "column" }}>
            <span style={{ fontWeight: 500 }}>{c.deceased}</span>
            {contactClickable ?
              <button
                onClick={(e) => {e.stopPropagation();onOpenContact(c.contactId);}}
                style={{
                  all: "unset", cursor: "pointer",
                  fontSize: 12, color: "#1F3A60",
                  alignSelf: "flex-start",
                  borderBottom: "1px dashed transparent"
                }}
                onMouseEnter={(e) => e.currentTarget.style.borderBottomColor = "#1F3A60"}
                onMouseLeave={(e) => e.currentTarget.style.borderBottomColor = "transparent"}>
                
                {c.contact}
              </button> :

              <span style={{ fontSize: 12, color: "#6B7A8F" }}>{c.contact}</span>
              }
          </div>
          <span style={{ fontFeatureSettings: "'tnum'", color: "#574F40" }}>{c.caseNumber}</span>
          <span style={{ color: "#574F40" }}>{c.religion}</span>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
            {(mode === "active" || c.status === "Cancelled") && <StatusPill status={c.pillStatus || c.status} />}
            {c.needType === "pre_need" && (
              <span style={{
                display: "inline-flex", alignItems: "center", gap: 4,
                padding: "2px 7px", borderRadius: 20,
                background: "#EEF2FF", border: "1px solid #C7D2FE",
                fontSize: 10, fontWeight: 600, color: "#4338CA",
                letterSpacing: "0.03em", whiteSpace: "nowrap",
              }}>
                <SerIcons.Star size={9} color="#4338CA" />
                PRE-NEED
              </span>
            )}
          </span>
          <span style={{ color: "#6B7A8F" }}>{c.updatedAt ? relativeTime(c.updatedAt) : c.updated || "—"}</span>
          <div style={{ display: "inline-flex", justifySelf: "end", alignItems: "center", gap: 6 }}>
            {mode === "active" ? (() => {
              const isConfirmedFlowRow = ["confirmed", "confirmed_updated", "awaiting", "amended_awaiting"].includes(c.workflowStatus);
              return (
                <React.Fragment>
                  <Button variant="secondary" size="sm" onClick={() => onOpenCase(c)}>
                    {isConfirmedFlowRow ? "View" : "Open"}
                  </Button>
                  {isConfirmedFlowRow && onEnterEditMode && (
                    <button
                      onClick={() => onEnterEditMode(c)}
                      title="Enter Edit Mode"
                      style={{
                        all: "unset", cursor: "pointer",
                        width: 32, height: 32, borderRadius: 6,
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                        color: "#574F40", border: "1px solid #E5E7EB",
                      }}
                    >
                      <SerIcons.Edit size={16} />
                    </button>
                  )}
                  <OverflowMenu
                    align="right"
                    items={[
                      { label: "Cancel Case", icon: <SerIcons.Close size={16} />, onClick: () => onArchiveCase && onArchiveCase(c), danger: true }
                    ]}
                    trigger={
                      <button style={{
                        all: "unset", cursor: "pointer",
                        width: 32, height: 32, borderRadius: 6,
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                        color: "#574F40"
                      }}>
                        <SerIcons.More size={18} />
                      </button>
                    }
                  />
                </React.Fragment>
              );
            })() :
              <Button variant="secondary" size="sm" icon={<SerIcons.RotateCcw size={16} />} onClick={() => onRestoreCase && onRestoreCase(c)}>
                Restore
              </Button>
            }
          </div>
        </div>);

      })}
    </div>);

}

/* =========================================================
   2. START NEW ARRANGEMENT
   ========================================================= */
function StartArrangementScreen({ contacts, onStarted, workspace = "serenity", workspaceTick = 0, preselectedContact = null, onConsumePreselect }) {
  const [q, setQ] = React.useState("");
  const [selectedContact, setSelectedContact] = React.useState(null);
  const [creatingNew, setCreatingNew] = React.useState(false);
  const [newName, setNewName] = React.useState("");
  const [newPhone, setNewPhone] = React.useState("");
  const [newEmail, setNewEmail] = React.useState("");
  const [deceasedName, setDeceasedName] = React.useState("");
  const [religion, setReligion] = React.useState("");
  const [needType, setNeedType] = React.useState("as_need");
  const [relationship, setRelationship] = React.useState("");

  // When workspace switches, religion may no longer be valid -> clear it.
  // Keep all other fields (contact, deceased name, etc).
  React.useEffect(() => {setReligion("");}, [workspaceTick]);

  // Apply a preselected contact (e.g. when launched from My Contacts via "Start Case")
  React.useEffect(() => {
    if (preselectedContact) {
      const phone = preselectedContact.mobile || preselectedContact.phone || "";
      setSelectedContact({
        name: preselectedContact.name,
        phone,
        email: preselectedContact.email || "",
        mobile: preselectedContact.mobile
      });
      setCreatingNew(false);
      // Prefill the search box so the user can see the matched contact row
      // surfaced with a selection ring — visually confirms which contact is bound.
      setQ(preselectedContact.name);
      // Note: intentionally NOT pre-filling relationship from the contact.
      // The contact's stored `relationship` describes their tie to a PAST
      // deceased (e.g. "Daughter of late Tan Ah Kow") and may not match the
      // new case's deceased. The FD picks the relationship fresh.
      onConsumePreselect && onConsumePreselect();
    }
  }, [preselectedContact]); // eslint-disable-line react-hooks/exhaustive-deps

  const religionOptions = RELIGIONS_BY_WORKSPACE[workspace] || RELIGIONS_BY_WORKSPACE.serenity;

  const matches = q ?
  contacts.filter((c) => `${c.name} ${c.phone || ""} ${c.mobile || ""} ${c.email || ""}`.toLowerCase().includes(q.toLowerCase())) :
  [];

  const canStart = (selectedContact || (creatingNew && newName.trim() && newPhone.trim())) &&
  deceasedName.trim() && religion && relationship;

  const handleStart = () => {
    if (!canStart) return;
    const contactName = selectedContact ? selectedContact.name : newName.trim();
    const contactPhone = selectedContact ? selectedContact.mobile || selectedContact.phone || "" : newPhone.trim();
    const contactEmail = selectedContact ? selectedContact.email || "" : newEmail.trim();
    const contactId    = selectedContact ? selectedContact.id || null : null;
    const isNewContact = creatingNew && !selectedContact;
    const qid = "QT-" + String(Date.now()).slice(-6);
    onStarted({
      quotationId: qid,
      contact:      contactName,
      phone:        contactPhone,
      email:        contactEmail,
      contactId,
      isNewContact, // true when FD created a brand-new contact on this screen
      deceased:     deceasedName,
      religion,
      needType,
      relationship,
    });
  };

  return (
    <div style={{ padding: "64px 48px", display: "flex", flexDirection: "column", alignItems: "center", gap: 32, maxWidth: 720, margin: "0 auto", width: "100%", boxSizing: "border-box" }}>
      <header style={{ textAlign: "center", display: "flex", flexDirection: "column", gap: 8 }}>
        <h1 style={{ font: "500 32px/40px Inter", letterSpacing: "-0.6px", color: "#1F3A60", margin: 0 }}>Start New Arrangement</h1>
        <p style={{ fontSize: 15, color: "#6B7A8F", letterSpacing: "-0.15px", margin: 0 }}>
          Search for an existing contact or create a new one
        </p>
      </header>

      <section style={{ width: "100%", background: "#FFFFFF", border: "1px solid #E5E7EB", borderRadius: 12, padding: 20, display: "flex", flexDirection: "column", gap: 12 }}>
        {selectedContact ? (
          /* Confirmed selection — replaces the search + matches list.
             Tap "Change" to clear and pick again or create new. */
          <React.Fragment>
            <div style={{ fontSize: 12, color: "#6B7A8F", fontWeight: 500, textTransform: "uppercase", letterSpacing: "0.06em" }}>
              Selected Contact
            </div>
            <div style={{
              display: "flex", alignItems: "center", gap: 12,
              padding: 14, borderRadius: 8,
              background: "#EFE7D4", border: "1px solid #574F40",
            }}>
              <div style={{
                width: 40, height: 40, borderRadius: "50%",
                background: "#1F3A60", color: "#FFFFFF",
                display: "flex", alignItems: "center", justifyContent: "center",
              }}>
                <SerIcons.Check size={18} />
              </div>
              <div style={{ display: "flex", flexDirection: "column", flex: 1, minWidth: 0 }}>
                <span style={{ fontSize: 15, fontWeight: 500, color: "#1F3A60" }}>{selectedContact.name}</span>
                <span style={{ fontSize: 13, color: "#6B7A8F", display: "inline-flex", alignItems: "center", gap: 6 }}>
                  <SerIcons.Phone size={12} />{selectedContact.mobile || selectedContact.phone || ""}
                </span>
              </div>
              <button
                onClick={() => { setSelectedContact(null); setQ(""); }}
                style={{
                  all: "unset", cursor: "pointer",
                  fontSize: 13, fontWeight: 500, color: "#1F3A60",
                  display: "inline-flex", alignItems: "center", gap: 4,
                  padding: "8px 12px", borderRadius: 6,
                  border: "1px solid #E5E7EB", background: "#FFFFFF",
                }}
              >
                <SerIcons.Edit size={12} />Change
              </button>
            </div>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <Input
              icon={<SerIcons.Search size={18} />}
              placeholder="Search by name or phone number..."
              value={q}
              onChange={(e) => { setQ(e.target.value); setSelectedContact(null); setCreatingNew(false); }} />

            {matches.map((c) =>
              <button key={c.name} onClick={() => { setSelectedContact(c); setCreatingNew(false); }} style={{
                all: "unset", cursor: "pointer", display: "flex", alignItems: "center", gap: 12,
                padding: 14, borderRadius: 8,
                background: "transparent",
                border: "1px solid #F0F1F4",
              }}>
                <div style={{ width: 36, height: 36, borderRadius: "50%", background: "rgba(87,79,64,0.10)", color: "#574F40", display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <SerIcons.User size={20} />
                </div>
                <div style={{ display: "flex", flexDirection: "column" }}>
                  <span style={{ fontSize: 15, fontWeight: 500, color: "#1F3A60" }}>{c.name}</span>
                  <span style={{ fontSize: 13, color: "#6B7A8F", display: "inline-flex", alignItems: "center", gap: 6 }}>
                    <SerIcons.Phone size={12} />{c.mobile || c.phone || ""}
                  </span>
                </div>
              </button>
            )}
            <Button variant="dashed" size="md" icon={<SerIcons.Plus size={18} />} onClick={() => { setCreatingNew(true); setSelectedContact(null); }} style={{ width: "100%" }}>
              Create New Contact
            </Button>
          </React.Fragment>
        )}
      </section>

      {creatingNew && !selectedContact &&
      <section style={{ width: "100%", background: "#FFFFFF", border: "1px solid #E5E7EB", borderRadius: 12, padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <h2 style={{ font: "500 20px/28px Inter", letterSpacing: "-0.449px", color: "#1F3A60", margin: 0 }}>New Contact Details</h2>
            <button onClick={() => {setCreatingNew(false);setNewName("");setNewPhone("");setNewEmail("");}} style={{
            background: "transparent", border: "none", padding: 0, cursor: "pointer",
            fontFamily: "inherit", fontSize: 13, color: "#6B7A8F"
          }}>Cancel</button>
          </div>
          <FormField label="Contact Name *">
            <Input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="Enter contact name" />
          </FormField>
          <FormField label="Phone Number *">
            <PhoneInput value={newPhone} onChange={(e) => setNewPhone(e.target.value)} />
          </FormField>
          <FormField label="Email">
            <Input type="email" value={newEmail} onChange={(e) => setNewEmail(e.target.value)} placeholder="name@example.com" />
          </FormField>
        </section>
      }

      {(selectedContact || creatingNew) &&
      <section style={{ width: "100%", background: "#FFFFFF", border: "1px solid #E5E7EB", borderRadius: 12, padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
          <h2 style={{ font: "500 20px/28px Inter", letterSpacing: "-0.449px", color: "#1F3A60", margin: 0 }}>Case Type</h2>
          <FormField label="Need Type *">
            <select value={needType} onChange={(e) => setNeedType(e.target.value)} style={{
              width: "100%", boxSizing: "border-box", height: 48, padding: "0 14px",
              fontFamily: "inherit", fontSize: 14, color: "#1F3A60",
              background: "#FFFFFF", border: "1px solid #E5E7EB", borderRadius: 8, outline: "none",
              appearance: "none", letterSpacing: "-0.15px",
              backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 20 20' fill='none'><path d='M5 8l5 5 5-5' stroke='%23718096' stroke-width='1.5' stroke-linecap='round'/></svg>\")",
              backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center",
            }}>
              <option value="as_need">At-Need</option>
              <option value="pre_need">Pre-Need</option>
            </select>
          </FormField>
          <FormField label="Relationship to Deceased *">
            <select value={relationship} onChange={(e) => setRelationship(e.target.value)} style={{
              width: "100%", boxSizing: "border-box", height: 48, padding: "0 14px",
              fontFamily: "inherit", fontSize: 14, color: relationship ? "#1F3A60" : "rgba(45,55,72,0.5)",
              background: "#FFFFFF", border: "1px solid #E5E7EB", borderRadius: 8, outline: "none",
              appearance: "none", letterSpacing: "-0.15px",
              backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 20 20' fill='none'><path d='M5 8l5 5 5-5' stroke='%23718096' stroke-width='1.5' stroke-linecap='round'/></svg>\")",
              backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center",
            }}>
              <option value="">Select relationship…</option>
              {(window.RELATIONSHIP_OPTIONS || []).map((r) => <option key={r} value={r}>{r}</option>)}
            </select>
          </FormField>
        </section>
      }

      {(selectedContact || creatingNew) &&
      <section style={{ width: "100%", background: "#FFFFFF", border: "1px solid #E5E7EB", borderRadius: 12, padding: 24, display: "flex", flexDirection: "column", gap: 18 }}>
          <h2 style={{ font: "500 20px/28px Inter", letterSpacing: "-0.449px", color: "#1F3A60", margin: 0 }}>{needType === "pre_need" ? "Planee Information" : "Deceased Information"}</h2>
          <FormField label={needType === "pre_need" ? "Planee Name *" : "Deceased Name *"}>
            <Input value={deceasedName} onChange={(e) => setDeceasedName(e.target.value)} placeholder={needType === "pre_need" ? "Enter planee's full name" : "Enter deceased name"} />
          </FormField>
          <FormField label="Religion *">
            <select value={religion} onChange={(e) => setReligion(e.target.value)} style={{
            width: "100%", boxSizing: "border-box", height: 48, padding: "0 14px",
            fontFamily: "inherit", fontSize: 14, color: religion ? "#1F3A60" : "rgba(45,55,72,0.5)",
            background: "#FFFFFF", border: "1px solid #E5E7EB", borderRadius: 8, outline: "none",
            appearance: "none", letterSpacing: "-0.15px",
            backgroundImage: "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 20 20' fill='none'><path d='M5 8l5 5 5-5' stroke='%23718096' stroke-width='1.5' stroke-linecap='round'/></svg>\")",
            backgroundRepeat: "no-repeat", backgroundPosition: "right 14px center"
          }}>
              <option value="">Select religion…</option>
              {religionOptions.map((r) => <option key={r}>{r}</option>)}
            </select>
          </FormField>
        </section>
      }

      <Button variant="primary-navy" size="lg" disabled={!canStart} iconRight={<SerIcons.Arrow size={18} />} onClick={handleStart} style={{ width: "100%" }}>
        Start Arrangement
      </Button>
    </div>);

}

function FormField({ label, children }) {
  // Required is encoded in the label as a trailing " *". Detect it so we
  // can dim non-required field labels for a calmer hierarchy.
  const cleanLabel = String(label || "").replace(/\s*\*\s*$/, "");
  const required = /\*\s*$/.test(label || "");
  return (
    <label style={{
      display: "grid", gridTemplateColumns: "180px 1fr",
      alignItems: "center", columnGap: 16,
    }}>
      <span style={{
        fontSize: 14, fontWeight: required ? 500 : 400,
        color: required ? "#1F3A60" : "#6B7A8F",
        letterSpacing: "-0.15px",
      }}>
        {cleanLabel}
        {required && <span style={{ color: "#8F4A45", marginLeft: 2 }}>*</span>}
      </span>
      <div style={{ minWidth: 0 }}>{children}</div>
    </label>);

}

/* =========================================================
   3. SELECT CASKET — main consultation screen
   ========================================================= */
function CasketSelectionScreen({ caskets, selectedId, onSelect, caseDetails, onContinue }) {
  const selected = caskets.find((c) => c.id === selectedId);

  const lineItems = [
  {
    label: "Serenity Package (HDB)",
    meta: "Base Package",
    tag: "HDB Void Deck",
    price: "$6,277"
  },
  selected ? {
    label: selected.name,
    meta: "Casket",
    price: selected.price
  } : {
    label: "Casket",
    meta: "No item",
    price: "$0",
    empty: true
  },
  { label: "Floral Arrangement", meta: "No item", price: "$0", empty: true },
  { label: "Burial Option", meta: "No item", price: "$0", empty: true },
  { label: "Add-on Items", meta: "No item", price: "$0", empty: true }];


  // crude $ math for demo
  const parseAmt = (s) => Number(String(s).replace(/[^0-9.-]/g, "")) || 0;
  const total = lineItems.reduce((sum, it) => sum + parseAmt(it.price), 0);
  const totalStr = "$" + total.toLocaleString("en-SG");

  return (
    <div style={{ display: "flex", alignItems: "stretch", minHeight: "calc(100vh - 84px)" }}>
      <main style={{ flex: 1, padding: "32px 40px 64px", display: "flex", flexDirection: "column", gap: 24, background: "#FAFAFA" }}>
        <header style={{ display: "flex", flexDirection: "column", gap: 4 }}>
          <h1 style={{ font: "500 24px/32px Inter", letterSpacing: "0.07px", color: "#1F3A60", margin: 0 }}>Select Casket</h1>
          <p style={{ fontSize: 14, color: "#6B7A8F", letterSpacing: "-0.15px", margin: 0 }}>
            Choose a casket that reflects your preferences
          </p>
        </header>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, minmax(0, 1fr))", gap: 20 }}>
          {caskets.map((c) =>
          <CasketCard
            key={c.id}
            casket={c}
            selected={c.id === selectedId}
            onSelect={() => onSelect(c.id)} />

          )}
        </div>
      </main>

      <OrderSummary
        caseDetails={caseDetails}
        lineItems={lineItems}
        total={totalStr}
        onContinue={onContinue} />
      
    </div>);

}

Object.assign(window, { FilterTab, MyCasesScreen, CaseArchiveScreen, StartArrangementScreen, CasketSelectionScreen });