/* global React, I, StepHead, NavFooter, PropertyFlow, reoAddrLine, REO_PROP_DEFAULT */
const { useState: useREO, useEffect: useREOE } = React;

const REO_LS = 'bevri_reo_v1';
const BI_REF = 'bevri_borrower_v1';
const PU_REF = 'bevri_purchase_v1';
const RF_REF = 'bevri_refinance_v1';

const PTYPE_MAP = { single: 'Single-Family Home', condo: 'Condo', multi: 'Multi-Family 2 to 4 Units', manufactured: 'Mobile Home', coop: 'Co-op' };
const USE_MAP = { primary: 'Primary Residence', second: 'Second Home', investment: 'Investment Property' };

function reoBorrowers() {
  try {
    const bi = JSON.parse(localStorage.getItem(BI_REF))?.data;
    if (!bi) return [{ key: 'primary', first: 'You', name: 'You', role: 'Primary Borrower' }];
    const list = [{ key: 'primary', first: bi.name.first || 'Primary', name: `${bi.name.first} ${bi.name.last}`.trim(), role: 'Primary Borrower' }];
    (bi.coBorrowers || []).forEach((c, i) => list.push({ key: 'co-' + i, first: c.name.first || 'Co-borrower', name: `${c.name.first} ${c.name.last}`.trim(), role: 'Co-Borrower' }));
    return list;
  } catch { return [{ key: 'primary', first: 'You', name: 'You', role: 'Primary Borrower' }]; }
}

/* compute expected auto-created properties keyed by borrower */
function reoAutoProps(loanType) {
  const out = {}; // borrowerKey -> [prop]
  let bi, pu, rf;
  try { bi = JSON.parse(localStorage.getItem(BI_REF))?.data; } catch {}
  try { pu = JSON.parse(localStorage.getItem(PU_REF))?.data; } catch {}
  try { rf = JSON.parse(localStorage.getItem(RF_REF))?.data; } catch {}
  if (!bi) return out;

  const addrFrom = a => ({ street: a?.street || '', unit: a?.unit || '', city: a?.city || '', state: a?.state || '', zip: a?.zip || '' });

  if (loanType === 'refinance' && rf?.addr) {
    out.primary = [{
      ...REO_PROP_DEFAULT, id: 'auto-subject', auto: true, autoLabel: 'Subject property',
      ...addrFrom(rf.addr),
      ptype: PTYPE_MAP[rf.ptype] || '', usage: USE_MAP[rf.currentUse] || 'Primary Residence',
      value: rf.value || '', status: 'Retained',
    }];
  } else if (bi.housing === 'Own') {
    out.primary = [{
      ...REO_PROP_DEFAULT, id: 'auto-primary', auto: true, autoLabel: 'Current residence',
      ...addrFrom(bi.curAddr),
      ptype: '', usage: 'Primary Residence', status: 'Retained',
    }];
  }

  (bi.coBorrowers || []).forEach((c, i) => {
    if (c.housing === 'Own') {
      const a = c.sharedAddress ? bi.curAddr : c.curAddr;
      out['co-' + i] = [{
        ...REO_PROP_DEFAULT, id: 'auto-co-' + i, auto: true, autoLabel: 'Current residence',
        ...addrFrom(a),
        ptype: '', usage: 'Primary Residence', status: 'Retained',
      }];
    }
  });
  return out;
}

/* merge saved props with expected auto props (reconcile housing changes) */
function reconcile(saved, loanType) {
  const auto = reoAutoProps(loanType);
  const result = {};
  const keys = new Set([...Object.keys(saved || {}), ...Object.keys(auto)]);
  keys.forEach(k => {
    const savedList = (saved && saved[k]) || [];
    const autoList = auto[k] || [];
    const autoIds = new Set(autoList.map(p => p.id));
    // keep manual props + saved auto props that are still expected (preserve edits)
    const kept = savedList.filter(p => !p.auto || autoIds.has(p.id));
    // add any expected auto props not already saved
    autoList.forEach(ap => { if (!kept.some(p => p.id === ap.id)) kept.push(ap); });
    if (kept.length) result[k] = kept;
  });
  return result;
}

function propSummaryLines(p) {
  const lines = [];
  if (p.ptype) lines.push(p.ptype);
  if (p.usage) lines.push('Current Usage: ' + p.usage);
  if (p.usage === 'Investment Property' && p.rentalIncome) lines.push('Monthly Rental Income: $' + p.rentalIncome);
  if (p.status) lines.push('Status at Closing: ' + p.status);
  return lines;
}

/* ===================================================================== */
function RealEstateOwned({ loanType = 'purchase', onBack, onContinue, onProgress }) {
  const saved = (() => { try { return JSON.parse(localStorage.getItem(REO_LS))?.properties; } catch { return null; } })();
  const [props, setProps] = useREO(() => reconcile(saved, loanType));
  const [flow, setFlow] = useREO(null);   // { mode, borrowerKey, first, initial }
  const [confirmRemove, setConfirmRemove] = useREO(null); // { key, id }
  const borrowers = reoBorrowers();

  useREOE(() => { try { localStorage.setItem(REO_LS, JSON.stringify({ properties: props })); } catch {} }, [props]);
  // Live refresh: when the operator chat writes a property, re-read and
  // reconcile so the record appears without leaving the page.
  useREOE(() => {
    function onAutoFill(e) {
      if (!(e.detail?.posKeys || []).includes(REO_LS)) return;
      const updated = (() => { try { return JSON.parse(localStorage.getItem(REO_LS))?.properties; } catch { return null; } })();
      if (updated) setProps(reconcile(updated, loanType));
    }
    window.addEventListener('bevri:fields-autofilled', onAutoFill);
    return () => window.removeEventListener('bevri:fields-autofilled', onAutoFill);
  }, [loanType]);
  useREOE(() => { onProgress && onProgress({ fill: flow ? 50 : 20, stepTitle: 'reo' }); }, [flow]);

  function openAdd(b) { setFlow({ mode: 'add', borrowerKey: b.key, first: b.first, initial: null }); }
  function openEdit(b, p) { setFlow({ mode: 'edit', borrowerKey: b.key, first: b.first, initial: p }); }
  function saveProp(p) {
    setProps(prev => {
      const list = [...(prev[flow.borrowerKey] || [])];
      const i = list.findIndex(x => x.id === p.id);
      if (i >= 0) list[i] = p; else list.push(p);
      return { ...prev, [flow.borrowerKey]: list };
    });
    setFlow(null);
    const el = document.querySelector('.flow'); if (el) el.scrollTop = 0;
  }
  function removeProp(key, id) {
    setProps(prev => ({ ...prev, [key]: (prev[key] || []).filter(p => p.id !== id) }));
    setConfirmRemove(null);
  }

  if (flow) {
    return <PropertyFlow mode={flow.mode} borrowerName={flow.first} initial={flow.initial}
      onCancel={() => { setFlow(null); const el = document.querySelector('.flow'); if (el) el.scrollTop = 0; }}
      onSave={saveProp} onProgress={onProgress} />;
  }

  return (
    <main className="flow">
      <div className="flow-col">
        <div className="step">
          <StepHead title="Real Estate Owned"
            sub="Review any real estate you currently own and add any additional properties that should be included with this loan application." />

          <div className="ei-list">
            {borrowers.map(b => {
              const list = props[b.key] || [];
              return (
                <div className="ei-borrower" key={b.key}>
                  <div className="ei-bhead">
                    <span className="co-card-ava">{(b.name[0] || '') + (b.name.split(' ')[1]?.[0] || '')}</span>
                    <div className="ei-bmeta">
                      <div className="co-card-name">{b.name}</div>
                      <div className="person-bar-tag">{b.role}</div>
                    </div>
                  </div>

                  {list.length === 0
                    ? <div className="ei-empty-state">
                        <div className="ei-empty">No properties added</div>
                        <div className="ei-reo-skip">
                          If {b.key === 'primary' ? 'you don\'t' : `${b.first} doesn't`} own any real estate, no action needed. Click "Confirm &amp; Continue" below.
                        </div>
                      </div>
                    : <div className="reo-props">
                        {list.map(p => (
                          <div className="reo-prop" key={p.id}>
                            <div className="reo-prop-top">
                              <span className="reo-prop-icon">{I.home(20)}</span>
                              <div className="reo-prop-body">
                                <div className="reo-prop-addr">
                                  {reoAddrLine(p) || 'Address not set'}
                                  {p.auto && <span className="reo-auto-tag">{p.autoLabel || 'Auto-added'}</span>}
                                </div>
                                {propSummaryLines(p).map((l, i) => <div className="reo-prop-line" key={i}>{l}</div>)}
                                {p.mortgage && <div className="reo-mortgage">{I.home(14)}<span><strong>{p.mortgage.creditor}</strong> · ${p.mortgage.balance} balance · ${p.mortgage.payment}/mo<br /><span style={{ color: 'var(--sage)' }}>Attached from credit report</span></span></div>}
                              </div>
                            </div>
                            <div className="reo-prop-actions">
                              <button className="co-act" onClick={() => openEdit(b, p)}>{I.pencil(13)}Edit Property</button>
                              {!p.auto && <button className="co-act danger" onClick={() => setConfirmRemove({ key: b.key, id: p.id })}>{I.trash(13)}Remove Property</button>}
                            </div>
                          </div>
                        ))}
                      </div>}

                  <button className="ei-add" onClick={() => openAdd(b)}>
                    <span className="co-add-icon">{I.plus(18)}</span>
                    Add a Property
                  </button>
                </div>
              );
            })}
          </div>

          <div className="step-nav">
            <button className="btn btn-secondary" onClick={onBack}>{I.back(16)}Back</button>
            <button className="btn btn-primary" onClick={() => onContinue && onContinue()}>Confirm & Continue{I.arrow(16)}</button>
          </div>
        </div>
      </div>

      {confirmRemove && (
        <div className="modal-scrim" onClick={() => setConfirmRemove(null)}>
          <div className="modal" onClick={e => e.stopPropagation()}>
            <div className="modal-title">Remove this property?</div>
            <div className="modal-body">This will remove this property from the loan application.</div>
            <div className="modal-actions">
              <button className="btn btn-secondary" onClick={() => setConfirmRemove(null)}>Cancel</button>
              <button className="btn btn-danger" onClick={() => removeProp(confirmRemove.key, confirmRemove.id)}>Remove Property</button>
            </div>
          </div>
        </div>
      )}
    </main>
  );
}

window.RealEstateOwned = RealEstateOwned;
