// Recursive MLS — Screen 5: Clients (CRM).
// Master list + detail. Lead scoring (Follow Up Boss), household/relationship
// model with AI crossover (Rechat), tags, saved-search alerts, market messages.
function ClientsCRM() {
  const C = window.RC_CRM;
  const [selId, setSelId] = useState("p1");
  const [filter, setFilter] = useState("All");
  const [sort, setSort] = useState("score");
  const [q, setQ] = useState("");
  const [tab, setTab] = useState("overview");

  let list = C.people.filter((p) => {
    if (filter === "Buyers" && !p.role.includes("Buyer")) return false;
    if (filter === "Sellers" && !p.role.includes("Seller")) return false;
    if (q && !p.name.toLowerCase().includes(q.toLowerCase())) return false;
    return true;
  });
  list = list.slice().sort((a, b) => sort === "score" ? b.score.total - a.score.total : a.name.localeCompare(b.name));
  const p = C.person(selId);
  const hh = C.household(p.hh);

  const LeadRing = ({ value, size = 38, band }) => {
    const r = (size - 6) / 2, circ = 2 * Math.PI * r, off = circ * (1 - value / 100);
    return (
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ flex: "none" }}>
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="#eeede7" strokeWidth="4" />
        <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={band.color} strokeWidth="4" strokeLinecap="round"
          strokeDasharray={circ} strokeDashoffset={off} transform={`rotate(-90 ${size / 2} ${size / 2})`} />
        <text x="50%" y="52%" dominantBaseline="middle" textAnchor="middle" fontFamily="'Space Mono', monospace" fontSize={size * 0.3} fontWeight="700" fill="#1d241f">{value}</text>
      </svg>
    );
  };
  const Stage = ({ s }) => { const sc = C.stageColor[s]; return <span style={{ fontSize: 11, fontWeight: 600, color: sc.c, background: sc.b, borderRadius: 999, padding: "3px 9px", whiteSpace: "nowrap" }}>{s}</span>; };

  return (
    <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
      {/* header */}
      <div style={{ flex: "none", padding: "18px 24px 0", display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 14, flexWrap: "wrap" }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 23, fontWeight: 600, letterSpacing: "-0.5px", color: "#1d241f" }}>Clients</h1>
          <p style={{ margin: "4px 0 0", fontSize: 13.5, color: "#8a8e88" }}>{C.people.length} people · {Object.keys(C.households).length} households · {C.people.filter((x) => x.stage === "Active").length} active</p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <button style={btnOutline}><Icon name="upload" size={15} color="#006747" /> Import</button>
          <button style={btnPrimary}><Icon name="user-plus" size={15} color="#fff" /> Add Client</button>
        </div>
      </div>

      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "minmax(360px, 0.9fr) 1.6fr", gap: 0, minHeight: 0, padding: "16px 24px 0" }}>
        {/* LIST */}
        <div style={{ display: "flex", flexDirection: "column", minHeight: 0, background: "#fff", borderRadius: "3px 0 0 3px", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)" }}>
          <div style={{ padding: "12px 14px", borderBottom: "1px solid #f1f0ea", display: "flex", flexDirection: "column", gap: 10 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#f4f3ef", borderRadius: 7, padding: "8px 11px" }}>
              <Icon name="search" size={15} color="#a8aca6" />
              <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search clients…" style={{ flex: 1, border: 0, background: "transparent", outline: 0, fontFamily: "inherit", fontSize: 13 }} />
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              {["All", "Buyers", "Sellers"].map((f) => (
                <button key={f} onClick={() => setFilter(f)} style={{ fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, cursor: "pointer", border: 0, borderRadius: 6, padding: "5px 11px",
                  background: filter === f ? "#eef4f1" : "transparent", color: filter === f ? "#006747" : "#8a8e88" }}>{f}</button>
              ))}
              <div style={{ flex: 1 }} />
              <button onClick={() => setSort(sort === "score" ? "name" : "score")} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "inherit", fontSize: 12, fontWeight: 600, color: "#6b706a", background: "transparent", border: 0, cursor: "pointer" }}>
                <Icon name="arrow-up-down" size={13} color="#a8aca6" /> {sort === "score" ? "Lead score" : "Name"}
              </button>
            </div>
          </div>
          <div style={{ flex: 1, overflowY: "auto" }}>
            {list.map((c) => {
              const on = c.id === selId;
              const partner = C.household(c.hh).members.length > 1;
              return (
                <div key={c.id} onClick={() => { setSelId(c.id); setTab("overview"); }} className="rc-row" style={{ display: "flex", gap: 11, alignItems: "center", padding: "12px 14px", cursor: "pointer", borderBottom: "1px solid #f6f5f0", background: on ? "#f3f6f4" : "transparent", borderLeft: on ? "2.5px solid #006747" : "2.5px solid transparent" }}>
                  <div style={{ width: 38, height: 38, borderRadius: "50%", background: "#e7e1d4", color: "#006747", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 13, flex: "none" }}>{c.initials}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                      <span style={{ fontSize: 14, fontWeight: 600, color: "#1d241f" }}>{c.name}</span>
                      {partner && <Icon name="link" size={12} color="#a8aca6" />}
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 4 }}>
                      <Stage s={c.stage} />
                      <span style={{ fontSize: 11.5, color: "#bcbfba" }}>{c.role}</span>
                    </div>
                    <div style={{ display: "flex", gap: 4, marginTop: 6, flexWrap: "wrap" }}>
                      {c.tags.slice(0, 2).map((t) => <span key={t} style={{ fontSize: 10.5, color: "#6b706a", background: "#f4f3ef", border: "1px solid #ececec", borderRadius: 4, padding: "1px 6px" }}>{t}</span>)}
                      {c.tags.length > 2 && <span style={{ fontSize: 10.5, color: "#a8aca6" }}>+{c.tags.length - 2}</span>}
                    </div>
                  </div>
                  <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 3, flex: "none" }}>
                    <LeadRing value={c.score.total} band={c.band} />
                    <span style={{ fontSize: 9.5, fontWeight: 600, color: c.band.color, textTransform: "uppercase", letterSpacing: ".4px" }}>{c.band.label}</span>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* DETAIL */}
        <div style={{ display: "flex", flexDirection: "column", minHeight: 0, background: "#fbfaf7", borderRadius: "0 3px 3px 0", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", borderLeft: "none" }}>
          {/* detail header */}
          <div style={{ flex: "none", padding: "18px 22px 0", borderBottom: "1px solid #f1f0ea", background: "#fff", borderRadius: "0 3px 0 0" }}>
            <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
              <div style={{ width: 52, height: 52, borderRadius: "50%", background: "#006747", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 18, flex: "none" }}>{p.initials}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                  <h2 style={{ margin: 0, fontSize: 19, fontWeight: 600, color: "#1d241f" }}>{p.name}</h2>
                  <Stage s={p.stage} />
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 14, marginTop: 5, fontSize: 12.5, color: "#8a8e88", flexWrap: "wrap" }}>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="mail" size={13} color="#a8aca6" /> {p.email}</span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="phone" size={13} color="#a8aca6" /> {p.phone}</span>
                  <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}><Icon name="users" size={13} color="#a8aca6" /> {hh.name}</span>
                </div>
              </div>
              <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 2, flex: "none" }}>
                <LeadRing value={p.score.total} band={p.band} size={50} />
                <span style={{ fontSize: 10, fontWeight: 600, color: p.band.color, textTransform: "uppercase", letterSpacing: ".5px" }}>{p.band.label} lead</span>
              </div>
              <div style={{ display: "flex", gap: 8, flex: "none" }}>
                <button style={{ ...btnOutline, padding: "8px 12px" }}><Icon name="mail" size={14} color="#006747" /> Email</button>
                <button style={{ ...btnPrimary, padding: "8px 12px" }}><Icon name="phone" size={14} color="#fff" /> Call</button>
              </div>
            </div>
            <div style={{ display: "flex", gap: 4, marginTop: 16 }}>
              {[["overview", "Overview"], ["searches", "Searches & alerts"], ["homes", "Saved homes"], ["household", "Household"], ["activity", "Activity"]].map(([id, lab]) => (
                <button key={id} onClick={() => setTab(id)} style={{ fontFamily: "inherit", fontSize: 13, fontWeight: 600, cursor: "pointer", border: 0, background: "transparent", padding: "9px 12px", color: tab === id ? "#006747" : "#8a8e88", borderBottom: tab === id ? "2px solid #006747" : "2px solid transparent", marginBottom: -1 }}>{lab}</button>
              ))}
            </div>
          </div>

          {/* detail body */}
          <div style={{ flex: 1, overflowY: "auto", padding: 20 }}>
            {tab === "overview" && <Overview p={p} C={C} />}
            {tab === "searches" && <Searches p={p} C={C} />}
            {tab === "homes" && <SavedHomes p={p} C={C} />}
            {tab === "household" && <Household p={p} hh={hh} C={C} onSel={(id) => { setSelId(id); setTab("overview"); }} />}
            {tab === "activity" && <Activity p={p} />}
          </div>
        </div>
      </div>
    </div>
  );
}

// ---- panel atoms ----
function CrmCard({ title, action, children, pad = 16 }) {
  return (
    <div style={{ background: "#fff", borderRadius: 3, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", marginBottom: 14 }}>
      {title && <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "12px 16px", borderBottom: "1px solid #f1f0ea" }}>
        <h3 style={{ margin: 0, fontSize: 13.5, fontWeight: 600, color: "#1d241f" }}>{title}</h3>{action}
      </div>}
      <div style={{ padding: pad }}>{children}</div>
    </div>
  );
}

function Overview({ p, C }) {
  const [tags, setTags] = useState(p.tags);
  const [adding, setAdding] = useState(false);
  const add = (t) => { if (!tags.includes(t)) setTags([...tags, t]); setAdding(false); };
  return (
    <div>
      {/* lead score breakdown */}
      <CrmCard title="Lead score" action={<span style={{ fontFamily: "'Space Mono', monospace", fontSize: 15, fontWeight: 700, color: p.band.color }}>{p.score.total}<span style={{ color: "#bcbfba", fontSize: 12 }}>/100</span></span>}>
        <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
          {p.score.parts.map((part) => (
            <div key={part.key}>
              <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 5 }}>
                <span style={{ fontSize: 12.5, color: "#4a504a", fontWeight: 500 }}>{part.key} <span style={{ color: "#bcbfba", fontWeight: 400 }}>· {part.detail}</span></span>
                <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 12, fontWeight: 700, color: "#6b706a" }}>+{part.val}</span>
              </div>
              <div style={{ height: 5, borderRadius: 3, background: "#eeede7", overflow: "hidden" }}>
                <div style={{ width: `${(part.val / 30) * 100}%`, height: "100%", background: p.band.color, opacity: 0.85 }} />
              </div>
            </div>
          ))}
        </div>
        <div style={{ fontSize: 11, color: "#a8aca6", marginTop: 12 }}>Updates automatically from views, recency, email opens, search activity, and saved homes.</div>
      </CrmCard>

      {/* tags */}
      <CrmCard title="Tags">
        <div style={{ display: "flex", flexWrap: "wrap", gap: 7, alignItems: "center" }}>
          {tags.map((t) => (
            <span key={t} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 500, color: "#006747", background: "#eef4f1", borderRadius: 999, padding: "5px 10px" }}>
              {t}<span onClick={() => setTags(tags.filter((x) => x !== t))} style={{ display: "inline-flex", cursor: "pointer", opacity: 0.6 }}><Icon name="x" size={12} color="#006747" /></span>
            </span>
          ))}
          <div style={{ position: "relative" }}>
            <button onClick={() => setAdding(!adding)} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "inherit", fontSize: 12, fontWeight: 600, color: "#8a8e88", background: "#fff", border: "1px dashed #c8c6bc", borderRadius: 999, padding: "5px 10px", cursor: "pointer" }}>
              <Icon name="plus" size={12} color="#8a8e88" /> Add tag
            </button>
            {adding && (
              <div style={{ position: "absolute", top: "calc(100% + 6px)", left: 0, width: 200, maxHeight: 200, overflowY: "auto", background: "#fff", borderRadius: 8, boxShadow: "0 8px 24px rgba(0,0,0,.16), inset 0 0 0 1px rgba(0,0,0,.06)", padding: 6, zIndex: 20 }}>
                {C.allTags.filter((t) => !tags.includes(t)).map((t) => (
                  <div key={t} onClick={() => add(t)} className="rc-nav-item" style={{ padding: "7px 9px", borderRadius: 6, cursor: "pointer", fontSize: 12.5, color: "#1d241f" }}>{t}</div>
                ))}
              </div>
            )}
          </div>
        </div>
      </CrmCard>

      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
        <CrmCard title="Snapshot">
          {[["Role", p.role], ["Stage", p.stage], ["Owner", p.owner], ["Saved homes", p.saved.length], ["Active searches", p.searches.length]].map(([k, v]) => (
            <div key={k} style={{ display: "flex", justifyContent: "space-between", padding: "6px 0", borderBottom: "1px solid #f6f5f0", fontSize: 12.5 }}>
              <span style={{ color: "#8a8e88" }}>{k}</span><span style={{ color: "#1d241f", fontWeight: 600 }}>{v}</span>
            </div>
          ))}
        </CrmCard>
        <CrmCard title="Market updates">
          <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 8 }}>
            <span style={{ width: 30, height: 30, borderRadius: "50%", background: "#faf0e8", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="mail" size={15} color="#c0612f" /></span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, color: "#1d241f" }}>{p.market.area}</div>
              <div style={{ fontSize: 11.5, color: "#8a8e88" }}>{p.market.scope} · {p.market.freq}</div>
            </div>
            <span style={{ fontSize: 11, fontWeight: 600, color: p.market.on ? "#1f8a5b" : "#a8aca6", background: p.market.on ? "#e8f4ee" : "#f0efe9", borderRadius: 999, padding: "2px 8px" }}>{p.market.on ? "On" : "Off"}</span>
          </div>
          <div style={{ fontSize: 11.5, color: "#a8aca6" }}>From Market Insights · auto-branded digest.</div>
        </CrmCard>
      </div>
    </div>
  );
}

function Searches({ p, C }) {
  const [searches, setSearches] = useState(p.searches);
  const setFreq = (i, f) => setSearches(searches.map((s, j) => j === i ? { ...s, freq: f } : s));
  return (
    <div>
      <CrmCard title="Saved search alerts" action={<button style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "inherit", fontSize: 12, fontWeight: 600, color: "#006747", background: "none", border: 0, cursor: "pointer" }}><Icon name="plus" size={13} color="#006747" /> New search</button>} pad={0}>
        {searches.length === 0 && <div style={{ padding: 16, fontSize: 13, color: "#a8aca6" }}>No saved searches yet.</div>}
        {searches.map((s, i) => (
          <div key={i} style={{ padding: "13px 16px", borderTop: i ? "1px solid #f4f3ee" : "none" }}>
            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 9, minWidth: 0 }}>
                <Icon name="search" size={15} color="#006747" />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f" }}>{s.name}</div>
                  <div style={{ fontSize: 12, color: "#8a8e88", marginTop: 1 }}>{s.crit}</div>
                </div>
              </div>
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 10 }}>
              <span style={{ fontSize: 11, color: "#a8aca6", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".5px" }}>Alert</span>
              <div style={{ display: "inline-flex", background: "#f1f0ea", borderRadius: 7, padding: 2 }}>
                {C.freqs.map((f) => (
                  <button key={f} onClick={() => setFreq(i, f)} style={{ fontFamily: "inherit", fontSize: 11.5, fontWeight: 600, cursor: "pointer", border: 0, borderRadius: 5, padding: "4px 10px",
                    background: s.freq === f ? "#fff" : "transparent", color: s.freq === f ? "#006747" : "#8a8e88", boxShadow: s.freq === f ? "0 1px 2px rgba(0,0,0,.12)" : "none" }}>{f}</button>
                ))}
              </div>
            </div>
          </div>
        ))}
      </CrmCard>

      <CrmCard title="Market Insights message">
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <span style={{ width: 32, height: 32, borderRadius: "50%", background: "#eef4f1", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="bar-chart-3" size={16} color="#006747" /></span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{p.market.area} · {p.market.scope}</div>
            <div style={{ fontSize: 12, color: "#8a8e88" }}>Recurring market digest from the Market Insights page</div>
          </div>
          <div style={{ display: "inline-flex", background: "#f1f0ea", borderRadius: 7, padding: 2 }}>
            {["Daily", "Weekly", "Monthly"].map((f) => (
              <span key={f} style={{ fontSize: 11.5, fontWeight: 600, borderRadius: 5, padding: "4px 9px", background: p.market.freq === f ? "#fff" : "transparent", color: p.market.freq === f ? "#006747" : "#8a8e88", boxShadow: p.market.freq === f ? "0 1px 2px rgba(0,0,0,.12)" : "none" }}>{f}</span>
            ))}
          </div>
        </div>
      </CrmCard>
    </div>
  );
}

function SavedHomes({ p, C }) {
  return (
    <CrmCard title={`Saved homes · ${p.saved.length}`} pad={14}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        {p.saved.map((hid) => {
          const h = C.homes[hid];
          return (
            <div key={hid} style={{ display: "flex", gap: 11, padding: 11, borderRadius: 6, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)" }}>
              <div style={{ width: 44, height: 44, borderRadius: 5, background: "#e7e1d4", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name="home" size={18} color="#006747" /></div>
              <div style={{ minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{h.addr}</div>
                <div style={{ fontSize: 11.5, color: "#8a8e88", marginTop: 2 }}>{h.area} · {h.beds}bd · {h.baths}ba</div>
                <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 13, fontWeight: 700, color: "#006747", marginTop: 3 }}>${(h.price / 1000).toFixed(0)}K</div>
              </div>
            </div>
          );
        })}
      </div>
    </CrmCard>
  );
}

function Household({ p, hh, C, onSel }) {
  const cross = C.crossover(hh.id);
  return (
    <div>
      <CrmCard title="Household" action={<span style={{ fontSize: 12, color: "#8a8e88" }}>{hh.note}</span>}>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {hh.members.map((mid) => {
            const m = C.person(mid);
            return (
              <div key={mid} onClick={() => onSel(mid)} className="rc-row" style={{ display: "flex", alignItems: "center", gap: 11, padding: "9px 10px", borderRadius: 7, cursor: "pointer", boxShadow: m.id === p.id ? "inset 0 0 0 1.5px #006747" : "inset 0 0 0 1px #ececec" }}>
                <div style={{ width: 36, height: 36, borderRadius: "50%", background: "#e7e1d4", color: "#006747", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 13, flex: "none" }}>{m.initials}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f" }}>{m.name} {m.id === p.id && <span style={{ fontSize: 11, color: "#a8aca6", fontWeight: 400 }}>· viewing</span>}</div>
                  <div style={{ fontSize: 11.5, color: "#8a8e88" }}>{m.role} · {m.saved.length} saved homes · score {m.score.total}</div>
                </div>
                <Icon name="chevron-right" size={16} color="#c4c7c1" />
              </div>
            );
          })}
          <button style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 6, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#006747", background: "#fff", border: "1px dashed #c8c6bc", borderRadius: 7, padding: "9px", cursor: "pointer", marginTop: 2 }}>
            <Icon name="link" size={14} color="#006747" /> Link another person to this household
          </button>
        </div>
      </CrmCard>

      {cross && (
        <CrmCard title="AI crossover — homes for both" action={<span style={{ display: "inline-flex", alignItems: "center", gap: 5, fontSize: 11, fontWeight: 600, color: "#006747", background: "#eef4f1", borderRadius: 999, padding: "3px 9px" }}><Icon name="sparkles" size={12} color="#006747" /> AI</span>}>
          <div style={{ fontSize: 13, color: "#2d332e", lineHeight: 1.55, marginBottom: 13 }}>
            Ranked from what <strong>{cross.members[0].name.split(" ")[0]}</strong> and <strong>{cross.members[1].name.split(" ")[0]}</strong> have viewed, saved, and liked — the homes most likely to win with <em>both</em>. Lead your next showing with the top of this list.
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {cross.ranked.slice(0, 5).map((c) => {
              const h = c.home;
              return (
                <div key={c.id} className="rc-row" style={{ display: "flex", alignItems: "center", gap: 12, padding: 11, borderRadius: 6, boxShadow: c.both ? "inset 0 0 0 1.5px #cfe0d7" : "inset 0 0 0 1px #ececec", background: c.both ? "#f4f6f4" : "#fff", cursor: "pointer" }}>
                  <div style={{ position: "relative", width: 40, height: 40, borderRadius: "50%", flex: "none" }}>
                    <svg width="40" height="40" viewBox="0 0 40 40">
                      <circle cx="20" cy="20" r="17" fill="none" stroke="#eeede7" strokeWidth="4" />
                      <circle cx="20" cy="20" r="17" fill="none" stroke={c.score >= 75 ? "#006747" : c.score >= 50 ? "#9a6a12" : "#2a6f8a"} strokeWidth="4" strokeLinecap="round" strokeDasharray={2 * Math.PI * 17} strokeDashoffset={2 * Math.PI * 17 * (1 - c.score / 100)} transform="rotate(-90 20 20)" />
                      <text x="20" y="21" dominantBaseline="middle" textAnchor="middle" fontFamily="'Space Mono', monospace" fontSize="12" fontWeight="700" fill="#1d241f">{c.score}</text>
                    </svg>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{h.addr}</div>
                    <div style={{ fontSize: 11.5, color: "#8a8e88", marginTop: 1 }}>{h.area} · {h.beds}bd · {h.baths}ba</div>
                    <div style={{ display: "inline-flex", alignItems: "center", gap: 5, marginTop: 5, fontSize: 11, fontWeight: 600, color: c.both ? "#006747" : "#9a6a12" }}>
                      <Icon name={c.both ? "heart-handshake" : "sparkles"} size={12} color={c.both ? "#006747" : "#9a6a12"} /> {c.reason}
                    </div>
                  </div>
                  <div style={{ textAlign: "right", flex: "none" }}>
                    <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 13, fontWeight: 700, color: "#006747" }}>${(h.price / 1000).toFixed(0)}K</div>
                    <button style={{ marginTop: 6, fontFamily: "inherit", fontSize: 11, fontWeight: 600, color: "#006747", background: "#eef4f1", border: 0, borderRadius: 6, padding: "4px 9px", cursor: "pointer" }}>Share both</button>
                  </div>
                </div>
              );
            })}
          </div>
          <div style={{ fontSize: 11, color: "#a8aca6", marginTop: 11 }}>Match score weighs mutual interest highest, then total engagement; one-sided saves rank lower.</div>
        </CrmCard>
      )}
    </div>
  );
}

function Activity({ p }) {
  const icon = { view: "eye", email: "mail-open", save: "heart", alert: "bell", deal: "file-check" };
  const col = { view: "#2a6f8a", email: "#9a6a12", save: "#c0612f", alert: "#006747", deal: "#1f8a5b" };
  return (
    <CrmCard title="Recent activity" pad={16}>
      <div style={{ display: "flex", flexDirection: "column" }}>
        {p.activity.map((a, i) => (
          <div key={i} style={{ display: "flex", gap: 12, paddingBottom: i < p.activity.length - 1 ? 16 : 0 }}>
            <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
              <div style={{ width: 30, height: 30, borderRadius: "50%", background: "#f4f3ef", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name={icon[a.t]} size={14} color={col[a.t]} /></div>
              {i < p.activity.length - 1 && <div style={{ width: 1.5, flex: 1, background: "#ececec", marginTop: 4 }} />}
            </div>
            <div style={{ flex: 1, paddingTop: 4 }}>
              <div style={{ fontSize: 13, color: "#1d241f" }}>{a.x}</div>
              <div style={{ fontSize: 11.5, color: "#bcbfba", marginTop: 1 }}>{a.ago} ago</div>
            </div>
          </div>
        ))}
      </div>
    </CrmCard>
  );
}

window.ClientsCRM = ClientsCRM;
