// Recursive MLS — Screen 6: Offers (offer management / negotiation).
// Buy-side (offers my buyers made) + list-side (offers on my listings).
// Works with the Clients CRM — every offer links to a client record.

// reCURSIVE — the platform's native eSign mark (a play on "cursive"), stamped
// on signatures the way DocuSign brands its envelopes.
function SignMark({ stamp = false, light = false }) {
  const ink = light ? "#fff" : "#006747";
  const swoosh = (
    <svg width="26" height="16" viewBox="0 0 28 18" style={{ flex: "none" }}>
      <path d="M2 12 C5 3 8 3 8 10 C8 15 5 15 7 11 C9 7 13 7 13 12 Q13 16 16 11 C18 7 22 8 26 5" fill="none" stroke={ink} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />
      <line x1="2" y1="16" x2="26" y2="16" stroke={ink} strokeWidth="1" opacity="0.35" />
    </svg>
  );
  if (stamp) return <span title="Signed with reCURSIVE" style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><svg width="15" height="11" viewBox="0 0 28 18"><path d="M2 12 C5 3 8 3 8 10 C8 15 5 15 7 11 C9 7 13 7 13 12 Q13 16 16 11 C18 7 22 8 26 5" fill="none" stroke="#1f8a5b" strokeWidth="2" strokeLinecap="round" /></svg><span style={{ fontSize: 9, fontWeight: 700, color: "#1f8a5b", letterSpacing: ".2px" }}>re<span style={{ textTransform: "uppercase" }}>cursive</span></span></span>;
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
      {swoosh}
      <span style={{ fontSize: 12.5, fontWeight: 600, color: light ? "#fff" : "#1d241f", letterSpacing: ".2px" }}>re<span style={{ color: ink, textTransform: "uppercase", letterSpacing: "1px" }}>cursive</span></span>
    </span>
  );
}

function Offers({ go }) {
  const O = window.RC_OFFERS;
  const img = (id) => `https://images.unsplash.com/photo-${id}?auto=format&fit=crop&w=400&q=70`;
  const [side, setSide] = useState("all");
  const [selId, setSelId] = useState("OF-2041");
  const [composing, setComposing] = useState(false);
  const [comparing, setComparing] = useState(null); // property name to compare

  const multiProps = O.listingsWithMultiple();

  let list = O.offers.filter((o) => side === "all" ? true : o.side === side);
  const o = O.offers.find((x) => x.id === selId) || list[0];

  const counts = {
    all: O.offers.length,
    buy: O.offers.filter((x) => x.side === "buy").length,
    list: O.offers.filter((x) => x.side === "list").length,
  };
  const needsAction = O.offers.filter((x) => x.status === "Countered" || (x.side === "list" && x.status === "Submitted")).length;

  const StatusPill = ({ s, sm }) => { const c = O.statusColor[s]; return <span style={{ fontSize: sm ? 10.5 : 11, fontWeight: 600, color: c.c, background: c.b, borderRadius: 999, padding: sm ? "2px 8px" : "3px 10px", 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" }}>Offers</h1>
          <p style={{ margin: "4px 0 0", fontSize: 13.5, color: "#8a8e88" }}>{counts.all} active · {needsAction} need{needsAction === 1 ? "s" : ""} your response</p>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          {multiProps.length > 0 && (
            <button onClick={() => { setComparing(multiProps[0]); setComposing(false); }} style={btnOutline}><Icon name="columns-3" size={15} color="#006747" /> Compare Offers</button>
          )}
          <button onClick={() => { setComposing(true); setComparing(null); }} style={btnPrimary}><Icon name="file-plus-2" size={15} color="#fff" /> New Offer</button>
        </div>
      </div>

      <div style={{ flex: 1, display: "grid", gridTemplateColumns: "minmax(340px, 0.85fr) 1.6fr", 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: "11px 14px", borderBottom: "1px solid #f1f0ea", display: "flex", gap: 6 }}>
            {[["all", "All"], ["buy", "My buyers"], ["list", "My listings"]].map(([k, lab]) => (
              <button key={k} onClick={() => setSide(k)} style={{ fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, cursor: "pointer", border: 0, borderRadius: 6, padding: "6px 11px",
                background: side === k ? "#eef4f1" : "transparent", color: side === k ? "#006747" : "#8a8e88" }}>{lab} <span style={{ color: "#bcbfba" }}>{counts[k]}</span></button>
            ))}
          </div>
          <div style={{ flex: 1, overflowY: "auto" }}>
            {list.map((x) => {
              const on = x.id === selId;
              return (
                <div key={x.id} onClick={() => { setSelId(x.id); setComposing(false); setComparing(null); }} className="rc-row" style={{ display: "flex", gap: 11, 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: 52, height: 52, borderRadius: 4, backgroundImage: `url(${img(x.photo)})`, backgroundSize: "cover", backgroundPosition: "center", flex: "none" }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
                      <span style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{x.property}</span>
                      {x.unread && <span style={{ width: 7, height: 7, borderRadius: "50%", background: "#c0612f", flex: "none" }} />}
                    </div>
                    <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 3 }}>
                      <span style={{ fontSize: 10.5, fontWeight: 600, color: x.side === "buy" ? "#2a6f8a" : "#9a6a12", background: x.side === "buy" ? "#e8f0f3" : "#fbf2dc", borderRadius: 4, padding: "1px 6px" }}>{x.side === "buy" ? "BUY-SIDE" : "LISTING"}</span>
                      <span style={{ fontSize: 11.5, color: "#8a8e88", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{x.client}</span>
                    </div>
                    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 6 }}>
                      <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 13.5, fontWeight: 700, color: "#006747" }}>{O.usd(x.offer)}</span>
                      <StatusPill s={x.status} sm />
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* DETAIL / COMPOSE */}
        <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)" }}>
          {composing ? <OfferCompose O={O} onClose={() => setComposing(false)} />
            : comparing ? <CompareOffers O={O} property={comparing} img={img} onClose={() => setComparing(null)} onPick={(id) => { setSelId(id); setComparing(null); }} />
            : <OfferDetail o={o} O={O} StatusPill={StatusPill} img={img} go={go} onCompare={(prop) => setComparing(prop)} />}
        </div>
      </div>
    </div>
  );
}

function OfferDetail({ o, O, StatusPill, img, go, onCompare }) {
  const term = (label, val, strong) => (
    <div style={{ background: "#fff", borderRadius: 6, padding: "10px 12px", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)" }}>
      <div style={{ fontSize: 10, color: "#8a8e88", textTransform: "uppercase", letterSpacing: ".6px" }}>{label}</div>
      <div style={{ fontFamily: strong ? "'Space Mono', monospace" : "inherit", fontSize: strong ? 16 : 13.5, fontWeight: strong ? 700 : 600, color: strong ? "#006747" : "#1d241f", marginTop: 3 }}>{val}</div>
    </div>
  );
  const vsList = o.offer - o.listPrice;
  const siblings = o.side === "list" ? O.offersForProperty(o.property) : [];
  const clientFirst = o.client.split(/[ &,]/).filter(Boolean)[0];
  return (
    <React.Fragment>
      {/* header */}
      <div style={{ flex: "none", padding: "16px 20px", borderBottom: "1px solid #f1f0ea", background: "#fff", borderRadius: "0 3px 0 0", display: "flex", gap: 14, alignItems: "center" }}>
        <div style={{ width: 64, height: 64, borderRadius: 5, backgroundImage: `url(${img(o.photo)})`, backgroundSize: "cover", backgroundPosition: "center", flex: "none" }} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: "#1d241f" }}>{o.property}</h2>
            <StatusPill s={o.status} />
          </div>
          <div style={{ fontSize: 12.5, color: "#8a8e88", marginTop: 3 }}>{o.area} · Listed {O.usd(o.listPrice)} · Offer {o.id}</div>
          <div style={{ display: "flex", alignItems: "center", gap: 7, marginTop: 6 }}>
            <span style={{ fontSize: 10.5, fontWeight: 600, color: o.side === "buy" ? "#2a6f8a" : "#9a6a12", background: o.side === "buy" ? "#e8f0f3" : "#fbf2dc", borderRadius: 4, padding: "1px 7px" }}>{o.side === "buy" ? "BUY-SIDE" : "LISTING"}</span>
            <button onClick={() => go && go("clients")} style={{ display: "inline-flex", alignItems: "center", gap: 5, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#006747", background: "none", border: 0, cursor: "pointer", padding: 0 }}>
              <Icon name="user" size={13} color="#006747" /> {o.client} <Icon name="external-link" size={12} color="#006747" />
            </button>
          </div>
        </div>
        {o.expires !== "—" && <div style={{ textAlign: "right", flex: "none" }}>
          <div style={{ fontSize: 10.5, color: "#8a8e88", textTransform: "uppercase", letterSpacing: ".5px" }}>Expires</div>
          <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 14, fontWeight: 700, color: o.expires.includes("h") ? "#c0612f" : "#1d241f" }}>{o.expires}</div>
        </div>}
      </div>

      <div style={{ flex: 1, overflowY: "auto", padding: 20 }}>
        {siblings.length > 1 && (
          <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "11px 13px", marginBottom: 14, borderRadius: 7, background: "#eef4f1", border: "1px solid #d7e6dd" }}>
            <Icon name="columns-3" size={17} color="#006747" />
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{siblings.length} competing offers on this listing</div>
              <div style={{ fontSize: 12, color: "#6b706a" }}>Compare price, net, terms, and financing strength side by side.</div>
            </div>
            <button onClick={() => onCompare && onCompare(o.property)} style={{ ...btnPrimary, padding: "8px 13px" }}>Compare all</button>
          </div>
        )}
        {/* terms */}
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 10, marginBottom: 10 }}>
          {term("Offer price", O.usd(o.offer), true)}
          {term("vs list", (vsList >= 0 ? "+" : "−") + "$" + Math.abs(vsList).toLocaleString())}
          {term("Financing", o.financing)}
          {term("Down", o.down + "%")}
          {term("Earnest money", O.usd(o.earnest))}
          {term("Close date", o.closeDate)}
          {term("Contingencies", o.contingencies.length)}
          {term("Concessions", o.concessions === "—" ? "None" : "Yes")}
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: 7, marginBottom: 18 }}>
          {o.contingencies.map((c) => <span key={c} style={{ fontSize: 11.5, color: "#4a504a", background: "#f1f0ea", borderRadius: 999, padding: "4px 10px" }}>{c}</span>)}
          {o.concessions !== "—" && <span style={{ fontSize: 11.5, color: "#9a6a12", background: "#fbf2dc", borderRadius: 999, padding: "4px 10px" }}>{o.concessions}</span>}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 11.5, color: "#a8aca6", marginBottom: 18 }}>
          <Icon name="file-badge" size={13} color="#a8aca6" /> {o.contractForm} · possession: {o.possession}{o.inclusions && o.inclusions !== "Standard" ? ` · includes ${o.inclusions}` : ""}
        </div>

        {/* actions — the agent sends; the client reviews, signs & decides */}
        {(o.status === "Submitted" || o.status === "Countered" || o.status === "Draft") && (
          <div style={{ marginBottom: 20 }}>
            <div style={{ display: "flex", gap: 9 }}>
              {o.side === "buy" ? (
                <React.Fragment>
                  <button style={{ ...btnPrimary, flex: 1, justifyContent: "center" }}><Icon name="send" size={15} color="#fff" /> Send to {clientFirst} to sign</button>
                  <button style={{ ...btnOutline, flex: 1, justifyContent: "center" }}><Icon name="building-2" size={15} color="#006747" /> Submit to listing agent</button>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <button style={{ ...btnPrimary, flex: 1, justifyContent: "center" }}><Icon name="send" size={15} color="#fff" /> Send to {clientFirst} for decision</button>
                  <button style={{ ...btnOutline, flex: 1, justifyContent: "center" }}><Icon name="repeat" size={15} color="#006747" /> Prepare counter</button>
                </React.Fragment>
              )}
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 11.5, color: "#a8aca6", marginTop: 8 }}>
              <Icon name="info" size={12} color="#a8aca6" /> You prepare and send — {clientFirst} reviews, {o.side === "buy" ? "signs" : "decides"}, and {o.side === "buy" ? "e-signs" : "approves"} in reCURSIVE.
            </div>
          </div>
        )}

        {/* negotiation timeline */}
        <div style={{ fontSize: 12, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".8px", color: "#a8aca6", marginBottom: 12 }}>Negotiation</div>
        <div style={{ display: "flex", flexDirection: "column" }}>
          {o.timeline.map((e, i) => {
            const meta = {
              "out": { ic: "arrow-up-right", c: "#2a6f8a", bg: "#e8f0f3" },
              "in": { ic: "arrow-down-left", c: "#9a6a12", bg: "#fbf2dc" },
              "counter-in": { ic: "repeat", c: "#9a6a12", bg: "#fbf2dc" },
              "accept": { ic: "check", c: "#1f8a5b", bg: "#e8f4ee" },
              "reject": { ic: "x", c: "#b3261e", bg: "#fbe9e7" },
              "sys": { ic: "file-text", c: "#a8aca6", bg: "#f0efe9" },
            }[e.kind] || { ic: "dot", c: "#a8aca6", bg: "#f0efe9" };
            return (
              <div key={i} style={{ display: "flex", gap: 13, paddingBottom: i < o.timeline.length - 1 ? 16 : 0 }}>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}>
                  <div style={{ width: 32, height: 32, borderRadius: "50%", background: meta.bg, display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name={meta.ic} size={15} color={meta.c} /></div>
                  {i < o.timeline.length - 1 && <div style={{ width: 1.5, flex: 1, background: "#ececec", marginTop: 4 }} />}
                </div>
                <div style={{ flex: 1, paddingtop: 2, paddingBottom: 4 }}>
                  <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: 10 }}>
                    <span style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f" }}>{e.act}{e.amount ? <span style={{ fontFamily: "'Space Mono', monospace", color: meta.c, marginLeft: 8 }}>{O.usd(e.amount)}</span> : null}</span>
                    <span style={{ fontSize: 11.5, color: "#bcbfba", flex: "none" }}>{e.time}</span>
                  </div>
                  {e.role && <div style={{ fontSize: 11.5, color: "#a8aca6", marginTop: 1 }}>{e.role}</div>}
                  {e.note && <div style={{ fontSize: 12.5, color: "#6b706a", lineHeight: 1.5, marginTop: 5, background: "#fff", borderRadius: 6, padding: "9px 11px", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.06)" }}>{e.note}</div>}
                </div>
              </div>
            );
          })}
        </div>

        {/* eSign — reCURSIVE */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "22px 0 12px" }}>
          <SignMark />
          <span style={{ fontSize: 11.5, fontWeight: 600, color: o.envelope.status.toLowerCase().includes("execut") ? "#1f8a5b" : "#9a6a12" }}>{o.envelope.status}</span>
        </div>
        <div style={{ background: "#fff", borderRadius: 6, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "6px 0", marginBottom: 4 }}>
          {o.envelope.signers.map((s, i) => {
            const done = s.status === "Signed";
            return (
              <div key={i} style={{ display: "flex", alignItems: "center", gap: 11, padding: "9px 14px", borderTop: i ? "1px solid #f4f3ee" : "none" }}>
                <span style={{ width: 26, height: 26, borderRadius: "50%", display: "flex", alignItems: "center", justifyContent: "center", flex: "none", background: done ? "#e8f4ee" : "#f0efe9" }}><Icon name={done ? "check" : "clock"} size={14} color={done ? "#1f8a5b" : "#9a6a12"} /></span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>{s.name}</div>
                  <div style={{ fontSize: 11.5, color: "#a8aca6" }}>{s.role}</div>
                </div>
                {done ? <SignMark stamp /> : <span style={{ fontSize: 11, fontWeight: 600, color: "#9a6a12", background: "#fbf2dc", borderRadius: 999, padding: "2px 9px" }}>{s.status}</span>}
              </div>
            );
          })}
        </div>
        <button style={{ display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#fff", background: "#006747", border: 0, borderRadius: 7, padding: "9px 14px", cursor: "pointer" }}>
          <Icon name="pen-line" size={14} color="#fff" /> Send to {clientFirst} to sign via reCURSIVE
        </button>

        {/* documents */}
        <div style={{ fontSize: 12, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".8px", color: "#a8aca6", margin: "22px 0 12px" }}>Documents</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
          {o.docs.map((d) => (
            <div key={d.name} style={{ display: "flex", alignItems: "center", gap: 11, padding: "10px 12px", background: "#fff", borderRadius: 6, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)" }}>
              <Icon name="file-text" size={16} color="#8a8e88" />
              <span style={{ flex: 1, fontSize: 13, color: "#1d241f", fontWeight: 500 }}>{d.name}</span>
              <span style={{ fontSize: 11, fontWeight: 600, color: d.status === "Signed" ? "#1f8a5b" : "#6b706a", background: d.status === "Signed" ? "#e8f4ee" : "#f0efe9", borderRadius: 999, padding: "2px 9px" }}>{d.status}</span>
            </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" }}>
            <Icon name="paperclip" size={14} color="#006747" /> Attach document
          </button>
        </div>
      </div>
    </React.Fragment>
  );
}

function OfferCompose({ O, onClose }) {
  const C = window.RC_CRM;
  const [price, setPrice] = useState(820000);
  const [fin, setFin] = useState("Conventional");
  const [client, setClient] = useState(C ? C.people[0].name : "");
  const inp = { width: "100%", boxSizing: "border-box", border: "1px solid #e2e0d8", borderRadius: 7, padding: "9px 11px", fontFamily: "inherit", fontSize: 13.5, color: "#1d241f", background: "#fff", outline: "none" };
  const lab = { fontSize: 11.5, fontWeight: 600, color: "#6b706a", display: "block", marginBottom: 6 };
  const [conts, setConts] = useState(["Inspection", "Appraisal", "Financing"]);
  const toggle = (c) => setConts(conts.includes(c) ? conts.filter((x) => x !== c) : [...conts, c]);
  return (
    <React.Fragment>
      <div style={{ flex: "none", padding: "16px 20px", borderBottom: "1px solid #f1f0ea", background: "#fff", borderRadius: "0 3px 0 0", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: "#1d241f" }}>New offer</h2>
          <p style={{ margin: "3px 0 0", fontSize: 12.5, color: "#8a8e88" }}>Submit on behalf of a client</p>
        </div>
        <button onClick={onClose} style={{ border: "1px solid #e2e0d8", background: "#fff", borderRadius: 7, width: 34, height: 34, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><Icon name="x" size={16} color="#4a504a" /></button>
      </div>
      <div style={{ flex: 1, overflowY: "auto", padding: 20 }}>
        <div style={{ display: "flex", flexDirection: "column", gap: 16, maxWidth: 560 }}>
          <div>
            <label style={lab}>Client (from CRM)</label>
            <div style={{ position: "relative" }}>
              <select value={client} onChange={(e) => setClient(e.target.value)} style={{ ...inp, appearance: "none", cursor: "pointer" }}>
                {C && C.people.map((p) => <option key={p.id}>{p.name}</option>)}
              </select>
              <span style={{ position: "absolute", right: 11, top: "50%", transform: "translateY(-50%)", pointerEvents: "none" }}><Icon name="chevron-down" size={15} color="#8a8e88" /></span>
            </div>
          </div>
          <div>
            <label style={lab}>Property</label>
            <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#f4f3ef", borderRadius: 7, padding: "9px 11px" }}>
              <Icon name="search" size={15} color="#a8aca6" />
              <input placeholder="Search MLS or paste address…" defaultValue="1100 S Miami Ave #3504" style={{ flex: 1, border: 0, background: "transparent", outline: 0, fontFamily: "inherit", fontSize: 13.5 }} />
            </div>
          </div>
          <div style={{ display: "flex", gap: 12 }}>
            <div style={{ flex: 1 }}>
              <label style={lab}>Offer price</label>
              <div style={{ position: "relative" }}><span style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)", fontFamily: "'Space Mono', monospace", color: "#8a8e88" }}>$</span>
                <input type="number" value={price} onChange={(e) => setPrice(+e.target.value)} style={{ ...inp, paddingLeft: 22, fontFamily: "'Space Mono', monospace", fontWeight: 700 }} /></div>
            </div>
            <div style={{ flex: 1 }}>
              <label style={lab}>Financing</label>
              <div style={{ position: "relative" }}>
                <select value={fin} onChange={(e) => setFin(e.target.value)} style={{ ...inp, appearance: "none", cursor: "pointer" }}>{O.financingOpts.map((f) => <option key={f}>{f}</option>)}</select>
                <span style={{ position: "absolute", right: 11, top: "50%", transform: "translateY(-50%)", pointerEvents: "none" }}><Icon name="chevron-down" size={15} color="#8a8e88" /></span>
              </div>
            </div>
          </div>
          <div style={{ display: "flex", gap: 12 }}>
            <div style={{ flex: 1 }}><label style={lab}>Earnest money</label><input style={inp} defaultValue="$25,000" /></div>
            <div style={{ flex: 1 }}><label style={lab}>Close date</label><input style={inp} type="date" /></div>
            <div style={{ flex: 1 }}><label style={lab}>Offer expires</label><input style={inp} type="date" /></div>
          </div>
          <div>
            <label style={lab}>Contingencies</label>
            <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
              {O.contingencyOpts.map((c) => {
                const on = conts.includes(c);
                return <button key={c} onClick={() => toggle(c)} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "inherit", fontSize: 13, fontWeight: 500, cursor: "pointer", padding: "7px 12px", borderRadius: 999, border: on ? "1px solid #006747" : "1px solid #e2e0d8", background: on ? "#eef4f1" : "#fff", color: on ? "#006747" : "#4a504a" }}>{on && <Icon name="check" size={13} color="#006747" />}{c}</button>;
              })}
            </div>
          </div>
          <div style={{ display: "flex", gap: 10, paddingTop: 4 }}>
            <button style={btnPrimary}><Icon name="send" size={15} color="#fff" /> Submit offer</button>
            <button style={btnOutline}>Save draft</button>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
}

// ---- multi-offer comparison (for listing agents) ----
// Neutral, factual side-by-side + per-offer AI strengths/weaknesses write-up
// (no winner declared) + bulk actions for high-volume offer situations.
function CompareOffers({ O, property, img, onClose, onPick }) {
  const offers = O.offersForProperty(property);
  const listPrice = offers[0].listPrice;
  const [threshold, setThreshold] = useState("");
  const [ai, setAi] = useState(null);     // { [id]: {strengths:[], watchouts:[]} }
  const [loading, setLoading] = useState(false);

  // data-derived analysis (the default write-up; AI can refine it)
  const analyze = (o) => {
    const strengths = [], watchouts = [];
    if (o.financing === "Cash") strengths.push("All-cash — no financing or appraisal risk");
    if (o.offer >= listPrice) strengths.push(`At or above list (${O.usd(o.offer - listPrice)} over)`);
    if (o.down >= 25 && o.financing !== "Cash") strengths.push(`Strong down payment (${o.down}%)`);
    if (o.earnest / o.offer >= 0.03) strengths.push(`Sizable earnest deposit (${O.usd(o.earnest)})`);
    if (o.contingencies.length <= 1) strengths.push("Minimal contingencies");
    if (o.daysToClose <= 20) strengths.push(`Fast close (${o.daysToClose} days)`);
    if (!o.credit) strengths.push("No seller credits requested");
    if (o.financing === "FHA" || o.financing === "VA") watchouts.push(`${o.financing} — stricter appraisal & property condition standards`);
    if (o.offer < listPrice) watchouts.push(`Below list (${O.usd(listPrice - o.offer)} under)`);
    if (o.down < 20 && o.financing !== "Cash") watchouts.push(`Lower down payment (${o.down}%)`);
    if (o.contingencies.includes("Sale of home")) watchouts.push("Contingent on sale of buyer's home");
    if (o.contingencies.length >= 3) watchouts.push(`Several contingencies (${o.contingencies.join(", ")})`);
    if (o.credit) watchouts.push(`Requests ${O.usd(o.credit)} credit — lowers net`);
    if (o.daysToClose > 45) watchouts.push(`Longer close (${o.daysToClose} days)`);
    if (!strengths.length) strengths.push("Standard terms");
    if (!watchouts.length) watchouts.push("No notable concerns");
    return { strengths, watchouts };
  };

  const runAI = async () => {
    setLoading(true);
    try {
      if (window.claude && window.claude.complete) {
        const lines = offers.map((o) => `${o.id} (${o.buyerAgent}): ${O.usd(o.offer)}, ${o.financing}, ${o.down}% down, ${O.usd(o.earnest)} earnest, contingencies [${o.contingencies.join(", ") || "none"}], close ${o.daysToClose}d, credit ${O.usd(o.credit || 0)}.`).join("\n");
        const prompt = `You are a neutral real-estate transaction analyst helping a SELLER weigh ${offers.length} offers on ${property} (list ${O.usd(listPrice)}). For EACH offer, give a balanced read of strengths and weaknesses. Do NOT pick a winner or say which is best. Be concise and factual.\n\n${lines}\n\nReturn JSON only: {"OF-XXXX":{"strengths":["..."],"watchouts":["..."]}, ...}`;
        const txt = await window.claude.complete(prompt);
        const parsed = JSON.parse(txt.slice(txt.indexOf("{"), txt.lastIndexOf("}") + 1));
        setAi(parsed);
      } else {
        await new Promise((r) => setTimeout(r, 700));
        const fb = {}; offers.forEach((o) => { fb[o.id] = analyze(o); }); setAi(fb);
      }
    } catch (e) {
      const fb = {}; offers.forEach((o) => { fb[o.id] = analyze(o); }); setAi(fb);
    }
    setLoading(false);
  };

  const Cell = ({ children, mono }) => (
    <td style={{ padding: "11px 14px", borderBottom: "1px solid #f1f0ea", fontSize: 13, fontFamily: mono ? "'Space Mono', monospace" : "inherit", fontWeight: 500, color: "#1d241f", whiteSpace: "nowrap" }}>{children}</td>
  );
  const RowLabel = ({ children, sub }) => (
    <td style={{ padding: "11px 14px", borderBottom: "1px solid #f1f0ea", fontSize: 12, fontWeight: 600, color: "#6b706a", textTransform: "uppercase", letterSpacing: ".4px", position: "sticky", left: 0, background: "#faf9f5", whiteSpace: "nowrap" }}>
      {children}{sub && <div style={{ fontSize: 10, fontWeight: 400, color: "#a8aca6", textTransform: "none", letterSpacing: 0, marginTop: 1 }}>{sub}</div>}
    </td>
  );

  return (
    <React.Fragment>
      <div style={{ flex: "none", padding: "16px 20px", borderBottom: "1px solid #f1f0ea", background: "#fff", borderRadius: "0 3px 0 0", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <div>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 600, color: "#1d241f" }}>Compare offers</h2>
          <p style={{ margin: "3px 0 0", fontSize: 12.5, color: "#8a8e88" }}>{offers.length} offers on {property} · listed {O.usd(listPrice)}</p>
        </div>
        <button onClick={onClose} style={{ border: "1px solid #e2e0d8", background: "#fff", borderRadius: 7, width: 34, height: 34, display: "flex", alignItems: "center", justifyContent: "center", cursor: "pointer" }}><Icon name="x" size={16} color="#4a504a" /></button>
      </div>
      <div style={{ flex: 1, overflow: "auto", padding: 20 }}>
        {/* bulk actions */}
        <div style={{ display: "flex", alignItems: "center", gap: 9, flexWrap: "wrap", padding: "12px 14px", marginBottom: 16, borderRadius: 8, background: "#fff", boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)" }}>
          <span style={{ fontSize: 11, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".7px", color: "#a8aca6", marginRight: 2 }}>Bulk actions</span>
          <button style={{ ...btnPrimary, padding: "8px 13px", fontSize: 12.5 }}><Icon name="megaphone" size={14} color="#fff" /> Request highest &amp; best from all</button>
          <button style={{ ...btnOutline, padding: "8px 13px", fontSize: 12.5 }}><Icon name="repeat" size={14} color="#006747" /> Counter all…</button>
          <div style={{ display: "flex", alignItems: "center", gap: 0, marginLeft: "auto" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "inherit", fontSize: 12.5, fontWeight: 600, color: "#b3261e", background: "#fff", border: "1px solid #f0d6d3", borderRadius: "7px 0 0 7px", padding: "8px 11px", borderRight: 0 }}><Icon name="x" size={14} color="#b3261e" /> Decline below</span>
            <div style={{ position: "relative" }}>
              <span style={{ position: "absolute", left: 9, top: "50%", transform: "translateY(-50%)", fontFamily: "'Space Mono', monospace", fontSize: 12.5, color: "#8a8e88" }}>$</span>
              <input value={threshold} onChange={(e) => setThreshold(e.target.value)} placeholder="1,450,000" style={{ width: 110, border: "1px solid #f0d6d3", borderRadius: "0 7px 7px 0", padding: "8px 9px 8px 20px", fontFamily: "'Space Mono', monospace", fontSize: 12.5, outline: 0 }} />
            </div>
          </div>
        </div>

        {/* factual comparison */}
        <div style={{ overflowX: "auto", background: "#fff", borderRadius: 6, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)" }}>
          <table style={{ borderCollapse: "collapse", width: "100%", minWidth: 520 }}>
            <thead>
              <tr>
                <th style={{ padding: "12px 14px", borderBottom: "2px solid #ececec", position: "sticky", left: 0, background: "#faf9f5", zIndex: 1 }}></th>
                {offers.map((o) => (
                  <th key={o.id} style={{ padding: "12px 14px", borderBottom: "2px solid #ececec", textAlign: "left", minWidth: 150 }}>
                    <span style={{ fontSize: 13, fontWeight: 700, color: "#1d241f" }}>{o.id}</span>
                    <div style={{ fontSize: 11.5, color: "#8a8e88", fontWeight: 400, marginTop: 2 }}>{o.buyerAgent}</div>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              <tr><RowLabel>Offer price</RowLabel>{offers.map((o) => <Cell key={o.id} mono>{O.usd(o.offer)}</Cell>)}</tr>
              <tr><RowLabel sub="offer − credits">Net to seller</RowLabel>{offers.map((o) => <Cell key={o.id} mono>{O.usd(O.netToSeller(o))}</Cell>)}</tr>
              <tr><RowLabel>vs list</RowLabel>{offers.map((o) => { const d = o.offer - listPrice; return <Cell key={o.id} mono>{(d >= 0 ? "+" : "−") + "$" + Math.abs(d).toLocaleString()}</Cell>; })}</tr>
              <tr><RowLabel>Financing</RowLabel>{offers.map((o) => <Cell key={o.id}>{o.financing}</Cell>)}</tr>
              <tr><RowLabel>Down payment</RowLabel>{offers.map((o) => <Cell key={o.id} mono>{o.down}%</Cell>)}</tr>
              <tr><RowLabel>Earnest money</RowLabel>{offers.map((o) => <Cell key={o.id} mono>{O.usd(o.earnest)}</Cell>)}</tr>
              <tr><RowLabel>Contingencies</RowLabel>{offers.map((o) => <Cell key={o.id}>{o.contingencies.length} · {o.contingencies.join(", ")}</Cell>)}</tr>
              <tr><RowLabel>Close</RowLabel>{offers.map((o) => <Cell key={o.id}>{o.closeDate} · {o.daysToClose}d</Cell>)}</tr>
              <tr><RowLabel>Possession</RowLabel>{offers.map((o) => <Cell key={o.id}>{o.possession}</Cell>)}</tr>
              <tr><RowLabel>Status</RowLabel>{offers.map((o) => { const c = O.statusColor[o.status]; return <td key={o.id} style={{ padding: "11px 14px", borderBottom: "1px solid #f1f0ea" }}><span style={{ fontSize: 11, fontWeight: 600, color: c.c, background: c.b, borderRadius: 999, padding: "2px 9px" }}>{o.status}</span></td>; })}</tr>
              <tr>
                <RowLabel></RowLabel>
                {offers.map((o) => (
                  <td key={o.id} style={{ padding: "11px 14px" }}>
                    <button onClick={() => onPick(o.id)} style={{ ...btnOutline, padding: "7px 10px", justifyContent: "center", fontSize: 12.5, width: "100%" }}>Open</button>
                  </td>
                ))}
              </tr>
            </tbody>
          </table>
        </div>

        {/* AI strengths & weaknesses — per offer, no winner */}
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", margin: "22px 0 12px" }}>
          <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 13, fontWeight: 600, color: "#1d241f" }}><Icon name="sparkles" size={15} color="#006747" /> Strengths &amp; weaknesses <span style={{ fontSize: 11, fontWeight: 600, color: "#006747", background: "#eef4f1", borderRadius: 999, padding: "2px 8px" }}>reCURSIVE AI</span></span>
          <button onClick={runAI} disabled={loading} style={{ ...btnOutline, padding: "7px 12px", fontSize: 12.5, opacity: loading ? 0.6 : 1 }}>
            <Icon name={loading ? "loader" : "sparkles"} size={14} color="#006747" style={loading ? { animation: "rc-spin 1s linear infinite" } : {}} /> {ai ? "Regenerate" : "Generate write-up"}
          </button>
        </div>
        <div style={{ fontSize: 12, color: "#8a8e88", marginBottom: 12, lineHeight: 1.5 }}>A balanced read of each offer — strengths and watch-outs side by side, so you and your seller can decide. {ai ? "" : "Generate to draft it for every offer at once."}</div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
          {offers.map((o) => {
            const a = (ai && ai[o.id]) || analyze(o);
            return (
              <div key={o.id} style={{ background: "#fff", borderRadius: 6, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "13px 15px" }}>
                <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 10 }}>
                  <span style={{ fontSize: 13, fontWeight: 700, color: "#1d241f" }}>{o.id} <span style={{ fontWeight: 400, color: "#8a8e88" }}>· {o.buyerAgent}</span></span>
                  <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 13, fontWeight: 700, color: "#006747" }}>{O.usd(o.offer)}</span>
                </div>
                <div style={{ fontSize: 10.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".5px", color: "#1f8a5b", marginBottom: 5 }}>Strengths</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 4, marginBottom: 10 }}>
                  {a.strengths.map((s, i) => <div key={i} style={{ display: "flex", gap: 7, fontSize: 12.5, color: "#2d332e", lineHeight: 1.4 }}><Icon name="plus" size={13} color="#1f8a5b" style={{ marginTop: 1, flex: "none" }} />{s}</div>)}
                </div>
                <div style={{ fontSize: 10.5, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".5px", color: "#c0612f", marginBottom: 5 }}>Watch-outs</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                  {a.watchouts.map((s, i) => <div key={i} style={{ display: "flex", gap: 7, fontSize: 12.5, color: "#2d332e", lineHeight: 1.4 }}><Icon name="minus" size={13} color="#c0612f" style={{ marginTop: 1, flex: "none" }} />{s}</div>)}
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ fontSize: 11, color: "#a8aca6", marginTop: 14, display: "flex", alignItems: "center", gap: 6 }}><Icon name="scale" size={12} color="#a8aca6" /> Presented without ranking — the seller decides. Terms are state-generic; per-state contract forms apply automatically.</div>
      </div>
    </React.Fragment>
  );
}

window.Offers = Offers;
