/* =====================================================================
   LOI / OFFER — adaptive submission form + generated PDF receipt
   ===================================================================== */
function loiMoney(v) {
  const n = parseFloat(String(v).replace(/[^0-9.]/g, ""));
  return isNaN(n) ? "—" : "$" + Math.round(n).toLocaleString("en-US");
}

function LoiModal({ listing, me, existing, onClose }) {
  const G = window.GLR;
  const l = listing;
  const isSale = l.deal === "Sale";
  const [phase, setPhase] = useState(existing ? "done" : "form");
  const [receipt, setReceipt] = useState(existing || null);
  const [cap, setCap] = useState("Principal");
  const [fin, setFin] = useState("Financed");
  const [f, setF] = useState({
    price: "", emd: "", finDays: "30", ddDays: "45", close: "",
    rate: l.rate ? String(l.rate).replace(/[^0-9.]/g, "") : "", term: "7", commence: "", ti: "", freeRent: "2", notes: "",
  });
  const set = (k) => (e) => setF({ ...f, [k]: e.target.value });

  useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => { window.removeEventListener("keydown", onKey); document.body.style.overflow = ""; };
  }, []);

  const valid = isSale ? parseFloat(f.price) > 0 : parseFloat(f.rate) > 0;

  function submit() {
    if (!valid) return;
    const terms = isSale ? [
      ["Offer price", loiMoney(f.price)],
      ["Price / SF", l.sf ? loiMoney(parseFloat(f.price.replace(/[^0-9.]/g, "")) / l.sf) : "—"],
      ["Earnest money deposit", f.emd ? loiMoney(f.emd) : "—"],
      ["Financing", fin],
      ...(fin === "Financed" ? [["Financing contingency", (f.finDays || "0") + " days"]] : []),
      ["Due diligence period", (f.ddDays || "0") + " days"],
      ["Target closing", f.close ? new Date(f.close).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" }) : "30 days post-DD"],
    ] : [
      ["Proposed base rate", "$" + (f.rate || "0") + " /SF NNN"],
      ["Annual base rent (yr 1)", l.sf ? loiMoney(parseFloat(f.rate || 0) * l.sf) : "—"],
      ["Lease term", (f.term || "0") + " years"],
      ["Requested commencement", f.commence ? new Date(f.commence).toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" }) : "Upon execution"],
      ["TI allowance", f.ti ? "$" + f.ti + " /SF" : "Negotiable"],
      ["Free rent", (f.freeRent || "0") + " months"],
    ];
    const loi = {
      slug: l.slug, name: me.name, company: me.company, email: me.email, cap,
      deal: l.deal, terms, notes: f.notes.trim(), dateTime: new Date().toLocaleString("en-US", { dateStyle: "medium", timeStyle: "short" }),
    };
    const rec = G.addLoi(loi);
    setReceipt({ ...loi, ...rec });
    setPhase("done");
    showToast("LOI submitted to the deal team");
  }

  const receiptDoc = useMemo(() => (receipt ? window.GLRDOCS.loiReceipt(receipt, l) : null), [receipt, l]);
  const dlReceipt = () => {
    window.GLRDOCS.downloadFromDoc(receiptDoc, "LOI - " + l.address + " - " + (receipt.ref || "receipt") + ".pdf", me.name);
    showToast("Receipt downloaded");
  };

  return ReactDOM.createPortal((
    <div className="docmodal-scrim" onClick={onClose}>
      <div className="formcard" onClick={(e) => e.stopPropagation()} role="dialog" aria-label="Submit letter of intent">
        <div className="formcard-head">
          <div style={{ minWidth: 0 }}>
            <div className="eyebrow brass">{isSale ? "Letter of Intent — Acquisition" : "Letter of Intent — Lease"}</div>
            <h2 className="h3" style={{ marginTop: 6 }}>{phase === "done" ? "Submission received" : "Submit LOI / Offer"}</h2>
            <p className="xsmall muted" style={{ marginTop: 4 }}>{l.address} · {l.submarket}</p>
          </div>
          <button className="wr-icbtn" aria-label="Close" onClick={onClose}><Icon name="x" size={18} /></button>
        </div>

        {phase === "form" ? (
          <React.Fragment>
            <div className="formcard-body">
              <div className="card surface" style={{ padding: 14, display: "flex", gap: 12, alignItems: "center" }}>
                <div style={{ width: 36, height: 36, borderRadius: "50%", background: "var(--navy)", color: "#fff", display: "grid", placeItems: "center", flex: "none", fontWeight: 700, fontSize: 14 }}>{me.name.split(" ").map((w) => w[0]).slice(0, 2).join("")}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="small b6">{me.name}</div>
                  <div className="xsmall muted">{me.company} · {me.email}</div>
                </div>
              </div>

              <div className="field" style={{ marginTop: 16 }}><label>Submitting as</label>
                <div className="row gap8">{["Principal", "Broker", "Lender"].map((c) => <button key={c} className={"chip" + (cap === c ? " on" : "")} onClick={() => setCap(c)}>{c}</button>)}</div>
              </div>

              <hr className="divider" style={{ margin: "18px 0" }} />

              {isSale ? (
                <React.Fragment>
                  <div className="form-grid">
                    <div className="field"><label>Offer price (USD)</label><div className="input-ic"><span className="ic" style={{ fontWeight: 700, color: "var(--slate)" }}>$</span><input className="input" style={{ paddingLeft: 28 }} inputMode="numeric" placeholder="9,100,000" value={f.price} onChange={set("price")} /></div></div>
                    <div className="field"><label>Earnest money</label><div className="input-ic"><span className="ic" style={{ fontWeight: 700, color: "var(--slate)" }}>$</span><input className="input" style={{ paddingLeft: 28 }} inputMode="numeric" placeholder="250,000" value={f.emd} onChange={set("emd")} /></div></div>
                  </div>
                  <div className="field" style={{ marginTop: 14 }}><label>Financing</label>
                    <div className="row gap8">{["Cash", "Financed"].map((c) => <button key={c} className={"chip" + (fin === c ? " on" : "")} onClick={() => setFin(c)}>{c}</button>)}</div>
                  </div>
                  <div className="form-grid" style={{ marginTop: 14 }}>
                    {fin === "Financed" && <div className="field"><label>Financing contingency (days)</label><input className="input" inputMode="numeric" value={f.finDays} onChange={set("finDays")} /></div>}
                    <div className="field"><label>Due diligence (days)</label><input className="input" inputMode="numeric" value={f.ddDays} onChange={set("ddDays")} /></div>
                    <div className="field"><label>Target closing date</label><input className="input" type="date" value={f.close} onChange={set("close")} /></div>
                  </div>
                </React.Fragment>
              ) : (
                <React.Fragment>
                  <div className="form-grid">
                    <div className="field"><label>Proposed base rate ($/SF)</label><div className="input-ic"><span className="ic" style={{ fontWeight: 700, color: "var(--slate)" }}>$</span><input className="input" style={{ paddingLeft: 28 }} inputMode="decimal" placeholder="24.50" value={f.rate} onChange={set("rate")} /></div></div>
                    <div className="field"><label>Lease term (years)</label><input className="input" inputMode="numeric" value={f.term} onChange={set("term")} /></div>
                  </div>
                  <div className="form-grid" style={{ marginTop: 14 }}>
                    <div className="field"><label>Requested commencement</label><input className="input" type="date" value={f.commence} onChange={set("commence")} /></div>
                    <div className="field"><label>TI allowance ($/SF)</label><input className="input" inputMode="decimal" placeholder="35" value={f.ti} onChange={set("ti")} /></div>
                    <div className="field"><label>Free rent (months)</label><input className="input" inputMode="numeric" value={f.freeRent} onChange={set("freeRent")} /></div>
                  </div>
                </React.Fragment>
              )}

              <div className="field" style={{ marginTop: 14 }}><label>Additional terms &amp; conditions</label>
                <textarea className="textarea" value={f.notes} onChange={set("notes")} placeholder="Contingencies, exclusions, assignment, timing, or other deal points…" style={{ minHeight: 84 }} />
              </div>

              <div className="row gap8 ac" style={{ marginTop: 14, color: "var(--slate)" }}>
                <Icon name="shield" size={14} /><span className="xsmall">Non-binding and for discussion only. A PDF receipt is generated on submission and logged to the data room.</span>
              </div>
            </div>
            <div className="formcard-foot">
              <button className="btn ghost" onClick={onClose}>Cancel</button>
              <button className="btn" disabled={!valid} onClick={submit}><Icon name="signature" size={16} /> Submit LOI</button>
            </div>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div className="formcard-body">
              <div className="row gap12 ac" style={{ padding: "4px 0 16px" }}>
                <div style={{ width: 46, height: 46, borderRadius: "50%", background: "var(--avail-bg)", color: "var(--avail)", display: "grid", placeItems: "center", flex: "none" }}><Icon name="check" size={24} /></div>
                <div>
                  <div className="b6">Letter of Intent submitted</div>
                  <div className="xsmall muted">Ref {receipt.ref} · {receipt.dateTime || receipt.date} · the deal team has been notified.</div>
                </div>
              </div>
              <div className="label" style={{ marginBottom: 8 }}>Receipt</div>
              <div className="card" style={{ overflow: "hidden", maxHeight: 320, overflowY: "auto" }}>
                <DocBody doc={receiptDoc} watermark={me.name} compact />
              </div>
            </div>
            <div className="formcard-foot">
              <button className="btn ghost" onClick={onClose}>Done</button>
              <button className="btn" onClick={dlReceipt}><Icon name="download" size={16} /> Download receipt (PDF)</button>
            </div>
          </React.Fragment>
        )}
      </div>
    </div>
  ), document.body);
}

Object.assign(window, { LoiModal });
