// Recursive MLS — Consumer: make-an-offer + eSign flow.
// The buyer reviews the home, builds their offer, reviews the auto-selected
// state purchase agreement, and signs it with reCURSIVE (native eSign). The
// signed package is routed to their agent to review & submit to the listing
// side — keeping the agent in the loop. Consumer-facing, no agent chrome.
function ConsumerOffer({ home, onBack }) {
  const D = window.RC_DATA;
  const h = home || D.searchResults[0];
  const agent = { name: "Alex Morgan", brokerage: "Recursive Realty", phone: "(305) 555-0148", initials: "AM" };
  const buyer = { name: "Daniel Reyes", coName: "Sofia Reyes" };

  const STEPS = ["Your offer", "Terms", "Review", "Sign"];
  const [step, setStep] = useState(0);
  const [done, setDone] = useState(false);

  // ---- offer state ----
  const [price, setPrice] = useState(h.price);
  const [financing, setFinancing] = useState("Conventional");
  const [withCo, setWithCo] = useState(true);
  const [downPct, setDownPct] = useState(20);
  const [earnest, setEarnest] = useState(Math.round(h.price * 0.02 / 1000) * 1000);
  const [closeDays, setCloseDays] = useState(30);
  const [possession, setPossession] = useState("At closing");
  const [contins, setContins] = useState(["Inspection", "Appraisal", "Financing"]);
  const [notes, setNotes] = useState("");

  const isCash = financing === "Cash";
  const down = isCash ? price : Math.round(price * downPct / 100);
  const loan = price - down;
  const closeDate = (() => { const d = new Date(2026, 5, 22); d.setDate(d.getDate() + closeDays); return d.toLocaleDateString("en-US", { month: "short", day: "numeric" }); })();
  const vsAsk = price - h.price;
  const finOpts = ["Conventional", "Cash", "FHA", "VA", "Jumbo"];
  const continOpts = ["Inspection", "Appraisal", "Financing", "Sale of home", "HOA review", "Title", "Other"];
  const tog = (v) => setContins(contins.includes(v) ? contins.filter((x) => x !== v) : [...contins, v]);

  const next = () => setStep((s) => Math.min(s + 1, STEPS.length - 1));
  const back = () => setStep((s) => Math.max(s - 1, 0));

  return (
    <div style={{ minHeight: "100vh", background: "#faf9f5", fontFamily: "'Space Grotesk', -apple-system, system-ui, sans-serif" }}>
      {/* top bar */}
      <div style={{ position: "sticky", top: 0, zIndex: 10, background: "#fff", borderBottom: "1px solid #ece9e0", display: "flex", alignItems: "center", gap: 14, padding: "0 28px", height: 62 }}>
        <button onClick={onBack} style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "inherit", fontSize: 13.5, fontWeight: 600, color: "#006747", background: "none", border: 0, cursor: "pointer" }}><Icon name="arrow-left" size={16} color="#006747" /> Back to listing</button>
        <div style={{ flex: 1 }} />
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, fontWeight: 600, color: "#1f8a5b", background: "#e8f4ee", borderRadius: 999, padding: "5px 11px" }}><Icon name="lock" size={13} color="#1f8a5b" /> Secure offer</span>
      </div>

      <div style={{ maxWidth: 1080, margin: "0 auto", padding: "26px 28px 64px" }}>
        {done ? <OfferSubmitted h={h} price={price} agent={agent} D={D} onBack={onBack} />
          : (
            <React.Fragment>
              <h1 style={{ margin: "0 0 4px", fontSize: 24, fontWeight: 700, letterSpacing: "-0.5px", color: "#1d241f" }}>Review &amp; sign your offer</h1>
              <div style={{ fontSize: 14, color: "#8a8e88", marginBottom: 16 }}>{h.addr} · {h.city}</div>

              {/* agent-initiated context — this flow is started by the agent, not self-serve */}
              <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 15px", borderRadius: 11, background: "#eef4f1", marginBottom: 22 }}>
                <span style={{ width: 36, height: 36, borderRadius: "50%", background: "#006747", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 13, flex: "none" }}>{agent.initials}</span>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f" }}>{agent.name} started an offer with you</div>
                  <div style={{ fontSize: 12, color: "#6b706a", lineHeight: 1.45 }}>The terms you discussed are filled in below. Review or adjust anything, then sign — your agent submits it to the seller.</div>
                </div>
              </div>

              {/* stepper */}
              <div style={{ display: "flex", alignItems: "center", gap: 0, marginBottom: 26 }}>
                {STEPS.map((s, i) => (
                  <React.Fragment key={s}>
                    <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
                      <span style={{ width: 26, height: 26, borderRadius: "50%", flex: "none", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 12.5, fontWeight: 700,
                        background: i < step ? "#006747" : i === step ? "#006747" : "#ece9e0", color: i <= step ? "#fff" : "#a8aca6" }}>
                        {i < step ? <Icon name="check" size={14} color="#fff" /> : i + 1}</span>
                      <span style={{ fontSize: 13, fontWeight: i === step ? 600 : 500, color: i === step ? "#1d241f" : "#a8aca6" }}>{s}</span>
                    </div>
                    {i < STEPS.length - 1 && <div style={{ flex: 1, height: 2, background: i < step ? "#006747" : "#ece9e0", margin: "0 12px" }} />}
                  </React.Fragment>
                ))}
              </div>

              <div style={{ display: "grid", gridTemplateColumns: "1fr 312px", gap: 26, alignItems: "start" }}>
                {/* form */}
                <div style={{ background: "#fff", borderRadius: 14, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: 24, minHeight: 360 }}>
                  {step === 0 && <StepOffer {...{ h, price, setPrice, vsAsk, financing, setFinancing, finOpts, withCo, setWithCo, buyer, D }} />}
                  {step === 1 && <StepTerms {...{ isCash, downPct, setDownPct, down, earnest, setEarnest, closeDays, setCloseDays, closeDate, possession, setPossession, contins, continOpts, tog, notes, setNotes, D }} />}
                  {step === 2 && <StepReview {...{ h, price, vsAsk, financing, isCash, downPct, down, loan, earnest, closeDate, closeDays, possession, contins, notes, withCo, buyer, D }} />}
                  {step === 3 && <StepSign {...{ h, price, withCo, buyer, agent, D, onFinish: () => setDone(true) }} />}

                  {/* nav */}
                  {step < 3 && (
                    <div style={{ display: "flex", justifyContent: "space-between", marginTop: 26, paddingTop: 18, borderTop: "1px solid #f1f0ea" }}>
                      <button onClick={back} disabled={step === 0} style={{ ...cBtnGhost, opacity: step === 0 ? 0.35 : 1, cursor: step === 0 ? "default" : "pointer" }}><Icon name="arrow-left" size={15} color="#006747" /> Back</button>
                      <button onClick={next} style={cBtnPrimary}>{step === 2 ? "Continue to signing" : "Continue"} <Icon name="arrow-right" size={15} color="#fff" /></button>
                    </div>
                  )}
                </div>

                {/* sticky summary */}
                <div style={{ position: "sticky", top: 80, display: "flex", flexDirection: "column", gap: 14 }}>
                  <div style={{ background: "#fff", borderRadius: 14, boxShadow: "0 4px 16px rgba(0,0,0,.07), inset 0 0 0 1px rgba(0,0,0,.06)", overflow: "hidden" }}>
                    <div style={{ height: 120, backgroundImage: `url(${h.photos[0]})`, backgroundSize: "cover", backgroundPosition: "center" }} />
                    <div style={{ padding: 16 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: "#1d241f" }}>{h.addr}</div>
                      <div style={{ fontSize: 12.5, color: "#8a8e88", marginTop: 1 }}>{h.city}</div>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 12, paddingTop: 12, borderTop: "1px solid #f1f0ea" }}>
                        <span style={{ fontSize: 12.5, color: "#8a8e88" }}>List price</span>
                        <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 14, color: "#6b706a" }}>{D.usd(h.price)}</span>
                      </div>
                      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 8 }}>
                        <span style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>Your offer</span>
                        <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 19, fontWeight: 700, color: "#006747", letterSpacing: "-0.5px" }}>{D.usd(price)}</span>
                      </div>
                      {vsAsk !== 0 && <div style={{ textAlign: "right", fontSize: 11.5, fontWeight: 600, color: vsAsk > 0 ? "#1f8a5b" : "#9a6a12", marginTop: 3 }}>{vsAsk > 0 ? "+" : ""}{D.usd(vsAsk)} {vsAsk > 0 ? "over" : "under"} ask</div>}
                      <div style={{ marginTop: 12, paddingTop: 12, borderTop: "1px solid #f1f0ea", display: "flex", flexDirection: "column", gap: 6 }}>
                        {[["Financing", financing], ["Down payment", isCash ? "100%" : downPct + "%"], ["Earnest", D.usd(earnest)], ["Close", closeDate]].map(([k, v]) => (
                          <div key={k} style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5 }}><span style={{ color: "#8a8e88" }}>{k}</span><span style={{ color: "#1d241f", fontWeight: 500 }}>{v}</span></div>
                        ))}
                      </div>
                    </div>
                  </div>
                  <div style={{ background: "#fff", borderRadius: 12, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: 14, display: "flex", alignItems: "center", gap: 11 }}>
                    <span style={{ width: 38, height: 38, borderRadius: "50%", background: "#006747", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 13, flex: "none" }}>{agent.initials}</span>
                    <div style={{ minWidth: 0 }}>
                      <div style={{ fontSize: 11, color: "#8a8e88" }}>Represented by</div>
                      <div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f" }}>{agent.name}</div>
                      <div style={{ fontSize: 11.5, color: "#8a8e88" }}>{agent.brokerage}</div>
                    </div>
                  </div>
                </div>
              </div>
            </React.Fragment>
          )}
      </div>
    </div>
  );
}

// ---- Step 1: price + financing + buyers ----
function StepOffer({ h, price, setPrice, vsAsk, financing, setFinancing, finOpts, withCo, setWithCo, buyer, D }) {
  return (
    <div>
      <h2 style={cH2}>Your offer price</h2>
      <p style={cSub}>This is what you and your agent discussed. Adjust it here if anything's changed.</p>
      <div style={{ display: "flex", alignItems: "center", gap: 10, background: "#faf9f5", borderRadius: 11, padding: "14px 16px", boxShadow: "inset 0 0 0 1px #ece9e0", marginBottom: 26 }}>
        <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 26, fontWeight: 700, color: "#006747" }}>$</span>
        <input type="text" value={price.toLocaleString("en-US")} onChange={(e) => { const n = +e.target.value.replace(/[^0-9]/g, ""); if (!isNaN(n)) setPrice(n); }}
          style={{ flex: 1, border: 0, outline: 0, background: "transparent", fontFamily: "'Space Mono', monospace", fontSize: 26, fontWeight: 700, color: "#1d241f", width: "100%" }} />
        {vsAsk !== 0 && <span style={{ fontSize: 12.5, fontWeight: 600, color: vsAsk > 0 ? "#1f8a5b" : "#9a6a12", whiteSpace: "nowrap" }}>{vsAsk > 0 ? "+" : ""}{D.usd(vsAsk)}</span>}
      </div>

      <h2 style={cH2}>How are you financing?</h2>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 26 }}>
        {finOpts.map((f) => (
          <button key={f} onClick={() => setFinancing(f)} style={{ ...cChip, ...(financing === f ? cChipOn : {}) }}>
            {f === "Cash" && <Icon name="banknote" size={14} color={financing === f ? "#006747" : "#8a8e88"} style={{ marginRight: 5 }} />}{f}
          </button>
        ))}
      </div>

      <h2 style={cH2}>Who's making this offer?</h2>
      <div style={{ display: "flex", flexDirection: "column", gap: 9 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "12px 14px", borderRadius: 10, background: "#faf9f5", boxShadow: "inset 0 0 0 1px #ece9e0" }}>
          <span style={{ width: 32, height: 32, borderRadius: "50%", background: "#006747", color: "#fff", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 12 }}>{buyer.name.split(" ").map((w) => w[0]).join("")}</span>
          <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f" }}>{buyer.name}</div><div style={{ fontSize: 11.5, color: "#8a8e88" }}>Primary buyer · you</div></div>
        </div>
        <button onClick={() => setWithCo(!withCo)} style={{ display: "flex", alignItems: "center", gap: 11, padding: "12px 14px", borderRadius: 10, background: withCo ? "#eef4f1" : "#fff", border: withCo ? "1px solid #006747" : "1px dashed #d2d0c7", cursor: "pointer", fontFamily: "inherit", textAlign: "left" }}>
          <span style={{ width: 32, height: 32, borderRadius: "50%", background: withCo ? "#006747" : "#ece9e0", color: withCo ? "#fff" : "#a8aca6", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 600, fontSize: 12 }}>{withCo ? buyer.coName.split(" ").map((w) => w[0]).join("") : "+"}</span>
          <div style={{ flex: 1 }}><div style={{ fontSize: 13.5, fontWeight: 600, color: "#1d241f" }}>{buyer.coName}</div><div style={{ fontSize: 11.5, color: "#8a8e88" }}>Co-buyer · {withCo ? "included — will also sign" : "tap to add"}</div></div>
          {withCo && <Icon name="check-circle-2" size={18} color="#006747" />}
        </button>
      </div>
    </div>
  );
}

// ---- Step 2: terms ----
function StepTerms({ isCash, downPct, setDownPct, down, earnest, setEarnest, closeDays, setCloseDays, closeDate, possession, setPossession, contins, continOpts, tog, notes, setNotes, D }) {
  return (
    <div>
      {!isCash && (
        <React.Fragment>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
            <h2 style={cH2}>Down payment</h2>
            <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 14, fontWeight: 700, color: "#006747" }}>{downPct}% · {D.usd(down)}</span>
          </div>
          <input type="range" min="3" max="50" step="1" value={downPct} onChange={(e) => setDownPct(+e.target.value)} style={{ width: "100%", accentColor: "#006747", marginBottom: 24 }} />
        </React.Fragment>
      )}
      {isCash && <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "11px 14px", borderRadius: 10, background: "#e8f4ee", marginBottom: 24, fontSize: 13, color: "#1f8a5b", fontWeight: 600 }}><Icon name="banknote" size={16} color="#1f8a5b" /> All-cash offer — no financing contingency needed.</div>}

      <h2 style={cH2}>Earnest money deposit</h2>
      <p style={cSub}>Shows the seller you're serious — typically 1–3% of the price.</p>
      <div style={{ display: "flex", alignItems: "center", gap: 8, background: "#faf9f5", borderRadius: 10, padding: "11px 14px", boxShadow: "inset 0 0 0 1px #ece9e0", marginBottom: 24 }}>
        <span style={{ fontFamily: "'Space Mono', monospace", fontSize: 17, fontWeight: 700, color: "#006747" }}>$</span>
        <input type="text" value={earnest.toLocaleString("en-US")} onChange={(e) => { const n = +e.target.value.replace(/[^0-9]/g, ""); if (!isNaN(n)) setEarnest(n); }} style={{ flex: 1, border: 0, outline: 0, background: "transparent", fontFamily: "'Space Mono', monospace", fontSize: 17, fontWeight: 700, color: "#1d241f" }} />
      </div>

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
        <h2 style={cH2}>Target closing</h2>
        <span style={{ fontSize: 13, fontWeight: 600, color: "#006747" }}>{closeDate} · {closeDays} days</span>
      </div>
      <div style={{ display: "flex", gap: 8, marginBottom: 24 }}>
        {[15, 30, 45, 60].map((d) => <button key={d} onClick={() => setCloseDays(d)} style={{ ...cChip, flex: 1, justifyContent: "center", ...(closeDays === d ? cChipOn : {}) }}>{d} days</button>)}
      </div>

      <h2 style={cH2}>Possession</h2>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 24 }}>
        {["At closing", "1 day after", "30-day rent-back"].map((p) => <button key={p} onClick={() => setPossession(p)} style={{ ...cChip, ...(possession === p ? cChipOn : {}) }}>{p}</button>)}
      </div>

      <h2 style={cH2}>Contingencies</h2>
      <p style={cSub}>Conditions that must be met. More contingencies protect you but can weaken your offer.</p>
      <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 24 }}>
        {continOpts.map((c) => <button key={c} onClick={() => tog(c)} style={{ ...cChip, ...(contins.includes(c) ? cChipOn : {}) }}>{contins.includes(c) && <Icon name="check" size={13} color="#006747" style={{ marginRight: 4 }} />}{c}</button>)}
      </div>

      <h2 style={cH2}>Notes for the seller <span style={{ fontWeight: 400, color: "#a8aca6" }}>(optional)</span></h2>
      <textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={3} placeholder="A personal note can help your offer stand out…" style={{ width: "100%", boxSizing: "border-box", border: "1px solid #e2e0d8", borderRadius: 10, padding: "11px 13px", fontFamily: "inherit", fontSize: 13.5, color: "#1d241f", resize: "vertical", outline: "none", lineHeight: 1.5 }} />
    </div>
  );
}

// ---- Step 3: review ----
function StepReview({ h, price, vsAsk, financing, isCash, downPct, down, loan, earnest, closeDate, closeDays, possession, contins, notes, withCo, buyer, D }) {
  const rows = [
    ["Offer price", D.usd(price) + (vsAsk !== 0 ? `  (${vsAsk > 0 ? "+" : ""}${D.usd(vsAsk)} vs ask)` : "")],
    ["Buyers", withCo ? `${buyer.name} & ${buyer.coName}` : buyer.name],
    ["Financing", financing],
    ["Down payment", isCash ? "100% (cash)" : `${downPct}% · ${D.usd(down)}`],
    ...(isCash ? [] : [["Loan amount", D.usd(loan)]]),
    ["Earnest money", D.usd(earnest)],
    ["Target close", `${closeDate} (${closeDays} days)`],
    ["Possession", possession],
    ["Contingencies", contins.length ? contins.join(", ") : "None (waived)"],
    ...(notes ? [["Note to seller", notes]] : []),
  ];
  return (
    <div>
      <h2 style={cH2}>Review your offer</h2>
      <p style={cSub}>Check everything over. You'll sign the purchase agreement on the next step.</p>
      <div style={{ borderRadius: 11, overflow: "hidden", boxShadow: "inset 0 0 0 1px #ece9e0", marginBottom: 20 }}>
        {rows.map(([k, v], i) => (
          <div key={k} style={{ display: "flex", justifyContent: "space-between", gap: 16, padding: "12px 15px", background: i % 2 ? "#faf9f5" : "#fff" }}>
            <span style={{ fontSize: 12.5, color: "#8a8e88", flex: "none" }}>{k}</span>
            <span style={{ fontSize: 13, fontWeight: 500, color: "#1d241f", textAlign: "right" }}>{v}</span>
          </div>
        ))}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 11, padding: "13px 15px", borderRadius: 11, background: "#eef4f1", marginBottom: 16 }}>
        <Icon name="file-text" size={20} color="#006747" />
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f" }}>State purchase agreement</div>
          <div style={{ fontSize: 11.5, color: "#6b706a" }}>The correct contract & disclosures for this property's location are attached automatically.</div>
        </div>
      </div>
      <div style={{ fontSize: 12, color: "#8a8e88", lineHeight: 1.55, padding: "0 2px" }}>
        By continuing, you confirm the terms above are accurate and authorize {withCo ? "you and your co-buyer" : "yourself"} to electronically sign the purchase agreement. Your agent will review and submit the offer to the listing side.
      </div>
    </div>
  );
}

// ---- Step 4: reCURSIVE eSign ----
function StepSign({ h, price, withCo, buyer, agent, D, onFinish }) {
  const initialSigners = [
    { name: buyer.name, role: "Buyer", you: true, signed: false },
    ...(withCo ? [{ name: buyer.coName, role: "Co-buyer", you: false, signed: false }] : []),
  ];
  const [signers, setSigners] = useState(initialSigners);
  const [adopted, setAdopted] = useState("");           // adopted signature (typed name)
  const [typing, setTyping] = useState(buyer.name);
  const [showAdopt, setShowAdopt] = useState(true);

  const allSigned = signers.every((s) => s.signed);
  const signAt = (i) => setSigners(signers.map((s, j) => j === i ? { ...s, signed: true } : s));

  return (
    <div>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
        <h2 style={{ ...cH2, margin: 0 }}>Sign the purchase agreement</h2>
        <RcSign />
      </div>
      <p style={cSub}>Your offer is ready. Sign below to authorize it — secured by reCURSIVE.</p>

      {/* adopt signature */}
      {showAdopt && !adopted && (
        <div style={{ border: "1px solid #ece9e0", borderRadius: 12, padding: 18, marginBottom: 18, background: "#faf9f5" }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: "#1d241f", marginBottom: 4 }}>Adopt your signature</div>
          <div style={{ fontSize: 12, color: "#8a8e88", marginBottom: 12 }}>Type your name — this becomes your reCURSIVE signature.</div>
          <input value={typing} onChange={(e) => setTyping(e.target.value)} style={{ width: "100%", boxSizing: "border-box", border: "1px solid #e2e0d8", borderRadius: 9, padding: "10px 13px", fontFamily: "inherit", fontSize: 14, color: "#1d241f", outline: "none", marginBottom: 12 }} />
          <div style={{ height: 72, borderRadius: 9, background: "#fff", boxShadow: "inset 0 0 0 1px #ece9e0", display: "flex", alignItems: "center", justifyContent: "center", marginBottom: 14 }}>
            <span style={{ fontFamily: "'Brush Script MT', 'Segoe Script', cursive", fontSize: 34, color: "#1d3a2e", lineHeight: 1 }}>{typing || "Your name"}</span>
          </div>
          <button onClick={() => setAdopted(typing)} disabled={!typing.trim()} style={{ ...cBtnPrimary, opacity: typing.trim() ? 1 : 0.4 }}><Icon name="pen-line" size={15} color="#fff" /> Adopt & continue</button>
        </div>
      )}

      {/* the document */}
      {adopted && (
        <React.Fragment>
          <div style={{ border: "1px solid #ece9e0", borderRadius: 12, overflow: "hidden", marginBottom: 16 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8, padding: "10px 15px", background: "#f7f6f1", borderBottom: "1px solid #ece9e0" }}>
              <Icon name="file-text" size={15} color="#6b706a" />
              <span style={{ fontSize: 12.5, fontWeight: 600, color: "#4a504a" }}>Purchase Agreement — {h.addr}</span>
              <span style={{ flex: 1 }} />
              <span style={{ fontSize: 11, color: "#a8aca6" }}>Page 1 of 9</span>
            </div>
            <div style={{ padding: "20px 22px", background: "#fff", maxHeight: 230, overflow: "hidden", position: "relative" }}>
              <div style={{ fontSize: 11.5, color: "#4a504a", lineHeight: 1.7 }}>
                <p style={{ margin: "0 0 9px" }}><b>1. Parties &amp; Property.</b> This agreement is made between the Buyer(s) named below and the Seller of the property located at <b>{h.addr}, {h.city}</b>.</p>
                <p style={{ margin: "0 0 9px" }}><b>2. Purchase Price.</b> The total purchase price is <b>{D.usd(price)}</b>, payable per the financing terms specified in the buyer's offer.</p>
                <p style={{ margin: "0 0 9px" }}><b>3. Earnest Money.</b> Buyer shall deposit earnest money into escrow within three (3) business days of acceptance, applied toward the purchase price at closing.</p>
                <p style={{ margin: 0 }}><b>4. Contingencies &amp; Closing.</b> This offer is subject to the contingencies elected by Buyer and shall close on or about the target date stated in the offer…</p>
              </div>
              <div style={{ position: "absolute", left: 0, right: 0, bottom: 0, height: 60, background: "linear-gradient(180deg, transparent, #fff)" }} />
            </div>
            {/* signature fields */}
            <div style={{ padding: "16px 22px 20px", background: "#fff", borderTop: "1px solid #f1f0ea" }}>
              <div style={{ fontSize: 11, fontWeight: 600, textTransform: "uppercase", letterSpacing: ".5px", color: "#a8aca6", marginBottom: 12 }}>Signatures required</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 11 }}>
                {signers.map((s, i) => (
                  <div key={i} style={{ display: "flex", alignItems: "center", gap: 13 }}>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ height: 46, borderRadius: 8, display: "flex", alignItems: "center", padding: "0 14px", position: "relative",
                        background: s.signed ? "#f3f9f5" : "#fffaf0", boxShadow: s.signed ? "inset 0 0 0 1px #cfe6da" : "inset 0 0 0 1.5px #e6c98a" }}>
                        {s.signed
                          ? <span style={{ fontFamily: "'Brush Script MT', 'Segoe Script', cursive", fontSize: 26, color: "#1d3a2e" }}>{s.you ? adopted : s.name}</span>
                          : <span style={{ fontSize: 12, fontWeight: 600, color: "#9a6a12", display: "inline-flex", alignItems: "center", gap: 6 }}><Icon name="pen-line" size={13} color="#9a6a12" /> {s.you ? "Tap to sign here" : "Awaiting " + s.name.split(" ")[0]}</span>}
                        {s.signed && <span style={{ marginLeft: "auto" }}><RcStamp /></span>}
                      </div>
                      <div style={{ fontSize: 11.5, color: "#8a8e88", marginTop: 4 }}>{s.name} · {s.role}</div>
                    </div>
                    {!s.signed && (
                      <button onClick={() => signAt(i)} style={{ ...cBtnPrimary, padding: "9px 14px", fontSize: 12.5, flex: "none" }}>
                        <Icon name="pen-line" size={14} color="#fff" /> {s.you ? "Sign" : "Sign for " + s.name.split(" ")[0]}</button>
                    )}
                    {s.signed && <Icon name="check-circle-2" size={20} color="#1f8a5b" style={{ flex: "none" }} />}
                  </div>
                ))}
              </div>
            </div>
          </div>

          <button onClick={onFinish} disabled={!allSigned} style={{ ...cBtnPrimary, width: "100%", justifyContent: "center", padding: "13px", fontSize: 14.5, opacity: allSigned ? 1 : 0.4, cursor: allSigned ? "pointer" : "default" }}>
            <Icon name="send" size={16} color="#fff" /> {allSigned ? "Submit signed offer to my agent" : "Sign all fields to continue"}</button>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 6, fontSize: 11.5, color: "#a8aca6", marginTop: 10 }}>
            <Icon name="shield-check" size={13} color="#a8aca6" /> Signed & sealed with reCURSIVE · {agent.name} reviews before it reaches the seller
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

// ---- confirmation ----
function OfferSubmitted({ h, price, agent, D, onBack }) {
  const steps = [
    { icon: "user-check", title: `${agent.name} reviews your offer`, body: "Your agent gives it a final check and submits it to the listing agent." },
    { icon: "send", title: "Delivered to the seller", body: "The listing agent presents your offer to the seller for a decision." },
    { icon: "bell", title: "You'll hear back here", body: "Accept, counter, or decline — you'll be notified and can respond with your agent." },
  ];
  return (
    <div style={{ maxWidth: 620, margin: "10px auto 0", textAlign: "center" }}>
      <span style={{ width: 64, height: 64, borderRadius: "50%", background: "#e8f4ee", display: "inline-flex", alignItems: "center", justifyContent: "center", marginBottom: 18 }}><Icon name="check" size={32} color="#1f8a5b" /></span>
      <h1 style={{ margin: "0 0 8px", fontSize: 26, fontWeight: 700, letterSpacing: "-0.5px", color: "#1d241f" }}>Offer signed &amp; sent</h1>
      <p style={{ margin: "0 0 6px", fontSize: 15, color: "#6b706a", lineHeight: 1.5 }}>Your <b style={{ color: "#006747" }}>{D.usd(price)}</b> offer on {h.addr} has been signed with reCURSIVE and sent to {agent.name}.</p>
      <div style={{ display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12, color: "#8a8e88", marginBottom: 28 }}><RcSign small /></div>

      <div style={{ background: "#fff", borderRadius: 14, boxShadow: "inset 0 0 0 1px rgba(0,0,0,.07)", padding: "8px 22px", textAlign: "left", marginBottom: 24 }}>
        {steps.map((s, i) => (
          <div key={i} style={{ display: "flex", gap: 14, padding: "16px 0", borderBottom: i < steps.length - 1 ? "1px solid #f1f0ea" : "none" }}>
            <span style={{ width: 40, height: 40, borderRadius: 10, background: "#eef4f1", display: "flex", alignItems: "center", justifyContent: "center", flex: "none" }}><Icon name={s.icon} size={19} color="#006747" /></span>
            <div><div style={{ fontSize: 14, fontWeight: 600, color: "#1d241f" }}>{s.title}</div><div style={{ fontSize: 12.5, color: "#8a8e88", marginTop: 2, lineHeight: 1.5 }}>{s.body}</div></div>
          </div>
        ))}
      </div>
      <div style={{ display: "flex", gap: 10, justifyContent: "center" }}>
        <button onClick={onBack} style={cBtnGhost}><Icon name="arrow-left" size={15} color="#006747" /> Back to listing</button>
        <button style={cBtnPrimary}><Icon name="download" size={15} color="#fff" /> Download signed copy</button>
      </div>
    </div>
  );
}

// reCURSIVE sign mark (consumer flow — self-contained, no agent-screen dependency)
function RcSign({ small }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
      <svg width={small ? 20 : 24} height={small ? 13 : 16} viewBox="0 0 28 18"><path d="M2 12 C5 3 8 3 8 10 C8 14 11 14 13 9 C15 4 18 4 18 11 C20 7 23 6 26 8" fill="none" stroke="#006747" strokeWidth="2" strokeLinecap="round" /></svg>
      <span style={{ fontSize: small ? 12 : 13.5, fontWeight: 700, color: "#006747", letterSpacing: "-0.3px" }}>re<span style={{ color: "#1d241f" }}>CURSIVE</span></span>
    </span>
  );
}
function RcStamp() {
  return (
    <span title="Signed with reCURSIVE" style={{ display: "inline-flex", alignItems: "center", gap: 4, opacity: 0.85 }}>
      <svg width="15" height="11" viewBox="0 0 28 18"><path d="M2 12 C5 3 8 3 8 10 C8 14 11 14 13 9 C15 4 18 4 18 11 C20 7 23 6 26 8" fill="none" stroke="#1f8a5b" strokeWidth="2" strokeLinecap="round" /></svg>
      <span style={{ fontSize: 9.5, fontWeight: 700, color: "#1f8a5b" }}>reCURSIVE</span>
    </span>
  );
}

const cH2 = { margin: "0 0 4px", fontSize: 16, fontWeight: 600, color: "#1d241f" };
const cSub = { margin: "0 0 14px", fontSize: 13, color: "#8a8e88", lineHeight: 1.5 };
const cChip = { display: "inline-flex", alignItems: "center", fontFamily: "inherit", fontSize: 13, fontWeight: 600, cursor: "pointer", padding: "9px 14px", borderRadius: 9, border: "1px solid #e2e0d8", background: "#fff", color: "#4a504a" };
const cChipOn = { border: "1px solid #006747", background: "#eef4f1", color: "#006747" };
const cBtnPrimary = { display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 13.5, fontWeight: 600, cursor: "pointer", borderRadius: 9, padding: "11px 18px", border: 0, background: "#006747", color: "#fff" };
const cBtnGhost = { display: "inline-flex", alignItems: "center", gap: 7, fontFamily: "inherit", fontSize: 13.5, fontWeight: 600, cursor: "pointer", borderRadius: 9, padding: "11px 16px", border: "1px solid #d7ddd9", background: "#fff", color: "#006747" };

window.ConsumerOffer = ConsumerOffer;
