const OFFER_PREFS_KEY = 'casabilia-offer-prefs-v1';
function loadOfferPrefs() {
  try { return JSON.parse(localStorage.getItem(OFFER_PREFS_KEY)) || {}; } catch (e) { return {}; }
}

function OfferLetterButton({ deal, calc }) {
  const [open, setOpen] = React.useState(false);
  return (
    <React.Fragment>
      <button className="btn primary offer-letter-btn" onClick={() => setOpen(true)}>
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16v16H4zM4 8h16M8 13h8M8 16h5" /></svg>
        Offer Letter
      </button>
      {open ? <OfferLetterModal deal={deal} calc={calc} onClose={() => setOpen(false)} /> : null}
    </React.Fragment>
  );
}

function OfferLetterModal({ deal, calc, onClose }) {
  const offer = computeOffer(deal, calc);
  const saved = loadOfferPrefs();
  const [f, setF] = React.useState({
    buyer: saved.buyer || 'Casabilia Investments LLC',
    entity: saved.entity || 'a Georgia limited liability company',
    seller: saved.seller || 'Property Owner',
    price: Math.round(offer.atGoal),
    earnest: saved.earnest || 5000,
    financing: saved.financing || 'Cash / hard money',
    closeDays: saved.closeDays || 21,
    inspectionDays: saved.inspectionDays || 10,
    expireDays: saved.expireDays || 3,
    contingencies: saved.contingencies || 'Inspection, clear title, and satisfactory walkthrough.',
    notes: saved.notes || 'Buyer is an active local investor able to close quickly with proof of funds available on request.',
  });
  const set = (k, v) => setF((s) => ({ ...s, [k]: v }));
  React.useEffect(() => {
    const { buyer, entity, seller, earnest, financing, closeDays, inspectionDays, expireDays, contingencies, notes } = f;
    try { localStorage.setItem(OFFER_PREFS_KEY, JSON.stringify({ buyer, entity, seller, earnest, financing, closeDays, inspectionDays, expireDays, contingencies, notes })); } catch (e) {}
  }, [f]);

  const p = deal.property;
  const addr = [p.address, p.city + ', ' + p.state + ' ' + p.zip].filter(Boolean).join(', ');
  const today = new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
  const lwUrl = (getSettings().keys && getSettings().keys.lonewolf) || '';

  const letterText = () =>
`LETTER OF INTENT TO PURCHASE REAL ESTATE
${today}

RE: ${addr}

Dear ${f.seller},

${f.buyer}, ${f.entity} ("Buyer"), is pleased to submit this non-binding Letter of Intent to purchase the property located at ${addr} under the following terms:

  Purchase Price:      ${fmtMoney(f.price)}
  Earnest Money:       ${fmtMoney(f.earnest)}
  Financing:           ${f.financing}
  Inspection Period:   ${f.inspectionDays} days
  Closing:             on or before ${f.closeDays} days from acceptance
  Contingencies:       ${f.contingencies}

${f.notes}

This Letter of Intent is non-binding and expires ${f.expireDays} business days from the date above unless extended in writing. We look forward to working toward a definitive purchase agreement.

Sincerely,
${f.buyer}`;

  const copy = () => { navigator.clipboard && navigator.clipboard.writeText(letterText()); };
  const printLetter = () => {
    const w = window.open('', '_blank');
    if (!w) return;
    w.document.write('<pre style="font:14px/1.6 Georgia,serif;white-space:pre-wrap;max-width:680px;margin:48px auto;padding:0 24px">' + letterText().replace(/</g, '&lt;') + '</pre>');
    w.document.close(); w.focus(); setTimeout(() => w.print(), 250);
  };
  const download = () => {
    const blob = new Blob([letterText()], { type: 'text/plain' });
    const a = document.createElement('a'); a.href = URL.createObjectURL(blob);
    a.download = 'LOI-' + (p.address || 'offer').replace(/\s+/g, '-') + '.txt'; a.click();
  };

  const Row = ({ label, children }) => <div className="ol-field"><label>{label}</label>{children}</div>;

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <h2>Offer Letter / LOI</h2>
          <button className="btn" onClick={onClose}><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12" /></svg></button>
        </div>
        <div className="modal-body">
          <div className="ol-form">
            <Row label="Buyer / entity"><input className="set-input" value={f.buyer} onChange={(e) => set('buyer', e.target.value)} /></Row>
            <Row label="Entity type"><input className="set-input" value={f.entity} onChange={(e) => set('entity', e.target.value)} /></Row>
            <Row label="Seller name"><input className="set-input" value={f.seller} onChange={(e) => set('seller', e.target.value)} /></Row>
            <Row label="Offer price"><MoneyInput value={f.price} onChange={(v) => set('price', v)} /></Row>
            <Row label="Earnest money"><MoneyInput value={f.earnest} onChange={(v) => set('earnest', v)} /></Row>
            <Row label="Financing"><input className="set-input" value={f.financing} onChange={(e) => set('financing', e.target.value)} /></Row>
            <Row label="Inspection (days)"><NumInput value={f.inspectionDays} onChange={(v) => set('inspectionDays', v || 0)} /></Row>
            <Row label="Close within (days)"><NumInput value={f.closeDays} onChange={(v) => set('closeDays', v || 0)} /></Row>
            <Row label="Offer expires (days)"><NumInput value={f.expireDays} onChange={(v) => set('expireDays', v || 0)} /></Row>
            <div className="ol-quick">
              <span>Quick price:</span>
              <button onClick={() => set('price', Math.round(offer.atGoal))}>Goal {fmtMoney(offer.atGoal)}</button>
              <button onClick={() => set('price', Math.round(offer.mao70))}>70% {fmtMoney(offer.mao70)}</button>
              <button onClick={() => set('price', deal.terms.acceptedPrice)}>Accepted {fmtMoney(deal.terms.acceptedPrice)}</button>
            </div>
          </div>
          <div className="ol-preview">
            <pre>{letterText()}</pre>
          </div>
        </div>
        <div className="modal-foot">
          <div style={{ fontSize: 11.5, color: 'var(--muted)', flex: 1, lineHeight: 1.4 }}>
            Non-binding draft. Lone Wolf has no public API to push letters — copy/download this into Lone Wolf zipForm or your contract software.
          </div>
          <button className="btn" onClick={download}>Download .txt</button>
          <button className="btn" onClick={copy}>Copy text</button>
          <a className="btn" href={lwUrl || 'https://zipformplus.lwolf.com'} target="_blank" rel="noopener noreferrer">Open Lone Wolf</a>
          <button className="btn primary" onClick={printLetter}>Print / PDF</button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { OfferLetterButton, OfferLetterModal });
