/* global React, BrainMark, I, StepHead, Field, CheckRow, NavFooter */
const { useState: useCR, useEffect: useCRE, useRef: useCRR } = React;

const BI_REF_C = 'bevri_borrower_v1';
const REO_REF_C = 'bevri_reo_v1';

const MORTGAGE_CO = 'Bevri Home Loans';

function crBorrowers() {
  try {
    const bi = JSON.parse(localStorage.getItem(BI_REF_C))?.data;
    if (!bi) return [{ key: 'primary', first: 'You', name: 'You', role: 'Primary Borrower', email: '', addr: '' }];
    const nm = `${bi.name.first}${bi.name.middle ? ' ' + bi.name.middle : ''} ${bi.name.last}${bi.name.suffix ? ' ' + (bi.name.suffix === 'Other' ? bi.name.suffixOther : bi.name.suffix) : ''}`.trim();
    const a = bi.curAddr || {};
    const addr = a.intl
      ? `${a.street}${a.unit ? ', ' + a.unit : ''}\n${[a.city, a.province].filter(Boolean).join(', ')} ${a.postal}\n${a.country}`
      : `${a.street}${a.unit ? ', ' + a.unit : ''}\n${[a.city, a.state].filter(Boolean).join(', ')} ${a.zip}`;
    const list = [{ key: 'primary', first: bi.name.first || 'Primary', name: nm || 'Primary Borrower', role: 'Primary Borrower', email: '', addr }];
    (bi.coBorrowers || []).forEach((c, i) => {
      const ca = c.sharedAddress ? bi.curAddr : c.curAddr;
      const caStr = ca ? `${ca.street}${ca.unit ? ', ' + ca.unit : ''}\n${[ca.city, ca.state].filter(Boolean).join(', ')} ${ca.zip}` : '';
      list.push({ key: 'co-' + i, first: c.name.first || 'Co-borrower', name: `${c.name.first} ${c.name.last}`.trim(), role: 'Co-Borrower', email: c.email || '', addr: caStr });
    });
    return list;
  } catch { return [{ key: 'primary', first: 'You', name: 'You', role: 'Primary Borrower', email: '', addr: '' }]; }
}

/* Liabilities come from the real credit report once it is ordered and
   processed with the loan team. The island shows no rows until a real
   report source is wired; it must never display sample/demo debts. */
const REPORT_LIABS = [];

const LIAB_ICON = t => t === 'Mortgage' ? I.home(18) : t === 'Auto Loan' ? I.cash(18) : I.cash(18);
const onlyDigits = s => (s || '').replace(/[^\d]/g, '');

/* read REO properties flattened with owner */
function reoFlat() {
  try {
    const props = JSON.parse(localStorage.getItem(REO_REF_C))?.properties || {};
    const bmap = {};
    crBorrowers().forEach(b => { bmap[b.key] = b.name; });
    const out = [];
    Object.keys(props).forEach(k => (props[k] || []).forEach(p => out.push({ ...p, ownerKey: k, ownerName: bmap[k] || 'Borrower' })));
    return out;
  } catch { return []; }
}
function propAddr(p) {
  return `${p.street}${p.unit ? ', ' + p.unit : ''}, ${[p.city, p.state].filter(Boolean).join(', ')} ${p.zip}`.trim();
}

/* ====================== SSN input ====================== */
function SSNField({ value, onChange, error }) {
  const [masked, setMasked] = useCR(false);
  const digits = onlyDigits(value);
  const fmt = d => { if (d.length > 5) return `${d.slice(0,3)}-${d.slice(3,5)}-${d.slice(5,9)}`; if (d.length > 3) return `${d.slice(0,3)}-${d.slice(3)}`; return d; };
  const display = masked && digits.length === 9 ? `•••-••-${digits.slice(5)}` : fmt(digits);
  return (
    <label className="field">
      <span>Social Security number</span>
      <span className="ssn-wrap">
        <span className="ssn-ico">{I.lock(16)}</span>
        <input className={'input ssn-input' + (error ? ' err' : '')} inputMode="numeric" placeholder="XXX-XX-XXXX"
          value={display} onChange={e => onChange(onlyDigits(e.target.value).slice(0, 9))}
          onFocus={() => setMasked(false)} onBlur={() => setMasked(true)} />
      </span>
      {error ? <span className="field-err">{error}</span>
        : <span className="field-hint">Your Social Security number is required to securely identify your credit profile.</span>}
    </label>
  );
}

/* ====================== Authorize modal ====================== */
function AuthorizeModal({ borrower, onClose, onAuthorize }) {
  const [ssn, setSsn] = useCR('');
  const [consent, setConsent] = useCR(false);
  const [touched, setTouched] = useCR(false);
  const valid = onlyDigits(ssn).length === 9 && consent;
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal modal-lg" onClick={e => e.stopPropagation()}>
        <div className="modal-title">Please review your information</div>
        <div className="modal-scroll">
          <div className="cr-review">
            <div className="cr-review-row">
              <div>
                <div className="sum-label">Full Legal Name</div>
                <div className="sum-value">{borrower.name}</div>
              </div>
              <button className="sum-edit" onClick={() => alert('Returns to Borrower Information to edit, then back here.')}>{I.pencil(13)}Edit</button>
            </div>
            <div className="cr-review-row">
              <div>
                <div className="sum-label">Current Address</div>
                <div className="sum-value" style={{ whiteSpace: 'pre-line' }}>{borrower.addr || '—'}</div>
              </div>
              <button className="sum-edit" onClick={() => alert('Returns to Borrower Information to edit, then back here.')}>{I.pencil(13)}Edit</button>
            </div>
          </div>

          <SSNField value={ssn} onChange={setSsn} error={touched && onlyDigits(ssn).length !== 9 ? 'Enter a valid 9-digit SSN' : ''} />

          <div className="consent-box">
            <p>You understand that by clicking <strong>Confirm and Authorize</strong> below, you are providing your consent to have credit information pulled in your name for the purposes of a mortgage loan.</p>
            <p>This authorization includes authorization to pull credit in connection with a request for a pre-qualification and/or an actual application for a mortgage loan.</p>
            <p>You are providing written instructions to <strong>{MORTGAGE_CO}</strong> under the Fair Credit Reporting Act, authorizing {MORTGAGE_CO} to obtain information from your personal credit profile or other information from Experian, Equifax, TransUnion, or all three in a tri-merge credit report.</p>
          </div>

          <div className="bi-inline-check" style={{ marginTop: 4 }}>
            <CheckRow checked={consent} onToggle={() => setConsent(c => !c)}>
              I have reviewed my information and authorize {MORTGAGE_CO} to pull my credit.
            </CheckRow>
          </div>
        </div>
        <div className="modal-actions">
          <button className="btn btn-secondary" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary" disabled={!valid}
            onClick={() => { if (!valid) { setTouched(true); return; } onAuthorize(borrower.key, onlyDigits(ssn)); }}>
            {I.lock(15)} Confirm and Authorize
          </button>
        </div>
      </div>
    </div>
  );
}

/* ====================== Attach mortgage modal ====================== */
function AttachModal({ liability, properties, currentPropId, onClose, onAttach }) {
  const suggested = properties.find(p => p.ownerKey === 'primary' && p.usage === 'Primary Residence') || properties[0];
  const [sel, setSel] = useCR(currentPropId || (suggested ? suggested.id : null));
  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal modal-lg" onClick={e => e.stopPropagation()}>
        <div className="modal-title">Attach mortgage to property</div>
        <div className="modal-body" style={{ marginBottom: 12 }}>Select the property this mortgage belongs to.</div>
        <div className="modal-scroll">
          {properties.length === 0
            ? <div className="ei-empty">No real estate owned properties yet. Add one in Real Estate Owned first.</div>
            : <div className="opt-list">
                {properties.map(p => {
                  const isSug = suggested && p.id === suggested.id;
                  return (
                    <button key={p.id} className={'opt' + (sel === p.id ? ' sel' : '')} onClick={() => setSel(p.id)}>
                      <span className="opt-icon">{I.home(20)}</span>
                      <span className="opt-main">
                        <span className="opt-title">{propAddr(p)}{isSug && <span className="opt-badge">Suggested Match</span>}</span>
                        <span className="opt-sub">{[p.ownerName, p.ptype, p.usage].filter(Boolean).join(' · ')}{p.value ? ` · $${p.value}` : ''}</span>
                      </span>
                      <span className="opt-radio">{I.check(13)}</span>
                    </button>
                  );
                })}
              </div>}
        </div>
        <div className="modal-actions">
          <button className="btn btn-secondary" onClick={onClose}>Cancel</button>
          <button className="btn btn-primary" disabled={!sel} onClick={() => onAttach(liability.id, sel)}>Attach Mortgage</button>
        </div>
      </div>
    </div>
  );
}

/* ===================================================================== */
function CreditLiabilities({ loanType = 'purchase', onBack, onContinue, onProgress }) {
  // POC island guardrail: credit authorization/liability state must remain
  // memory-only. Do not persist credit-derived data into browser storage.
  const [phase, setPhase] = useCR('authorize'); // authorize | pulling | liabilities
  const [auth, setAuth] = useCR({});           // borrowerKey -> 'invited' | 'authorized'
  const [attachments, setAttachments] = useCR({}); // liabId -> propId
  // Report tradelines, memory-only per the island guardrail (state + window,
  // never browser storage). Populated by the credit status poll.
  const [reportLiabs, setReportLiabs] = useCR(window.REPORT_LIABS || REPORT_LIABS);
  const [authModal, setAuthModal] = useCR(null);   // borrower
  const [attachModal, setAttachModal] = useCR(null); // liability
  const [detailLiab, setDetailLiab] = useCR(null); // liability for drawer
  const [confirmDetach, setConfirmDetach] = useCR(null); // liabId
  const [paymentRequired, setPaymentRequired] = useCR(false);

  const borrowers = crBorrowers();
  const properties = reoFlat();

  useCRE(() => { onProgress && onProgress({ fill: phase === 'liabilities' ? 80 : 20, stepTitle: 'credit-' + phase }); }, [phase]);

  const allAuthorized = auth['primary'] === 'authorized';
  const crAlive = React.useRef(true);
  useCRE(() => () => { crAlive.current = false; }, []);
  const crLoanId = () => window.BevriPosStorage?.loanId || new URLSearchParams(window.location.search).get('loanId') || '';

  // Real pull wiring (Path A): the SSN goes straight to the session-guarded
  // authorize route and nowhere else -- never into state, storage, or the
  // draft. The route records FCRA consent server-side and runs the configured
  // POS credit-pull policy under the assigned LO's credit credentials; we poll
  // for the outcome when a vendor pull starts. Borrower-paid policies wait for
  // the payment-link handoff instead of hard-coding an order.
  // Every failure lands on the liabilities view's loan-team copy.
  function finishWith(liabs) {
    if (!crAlive.current) return;
    const list = Array.isArray(liabs) ? liabs : [];
    setReportLiabs(list);
    try {
      window.REPORT_LIABS = list;
      window.__bevriCreditStatus = { authorized: auth['primary'] === 'authorized' || true, liabilities: list.length };
    } catch {}
    setPhase('liabilities');
  }
  function pollCredit(tries) {
    if (!crAlive.current) return;
    fetch('/api/pos/intake/credit/status?loanId=' + encodeURIComponent(crLoanId()), { credentials: 'same-origin' })
      .then(r => (r.ok ? r.json() : null))
      .then(d => {
        if (!crAlive.current) return;
        if (d && d.success && d.status === 'completed') return finishWith(d.liabilities);
        if (d && d.success && d.status === 'pulling' && tries < 15) {
          setTimeout(() => pollCredit(tries + 1), 4000);
          return;
        }
        finishWith([]);
      })
      .catch(() => finishWith([]));
  }
  function authorize(key, ssnDigits) {
    const nextAuth = { ...auth, [key]: 'authorized' };
    setAuth(nextAuth);
    setAuthModal(null);
    if (!borrowers.every(b => nextAuth[b.key] === 'authorized')) return;
    setPhase('pulling');
    fetch('/api/pos/intake/credit/authorize', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'same-origin',
      body: JSON.stringify({ loanId: crLoanId(), ssn: ssnDigits }),
    })
      .then(r => r.json().catch(() => ({})))
      .then(d => {
        if (!crAlive.current) return;
        if (d && d.success && d.pull === 'started') return pollCredit(0);
        if (d && d.success && d.pull === 'payment_required') setPaymentRequired(true);
        finishWith([]);
      })
      .catch(() => finishWith([]));
  }
  function startPull() {
    // Continue after an earlier authorization (e.g. a resumed session): the
    // SSN is gone by design, so only check the server for an outcome.
    setPhase('pulling');
    pollCredit(14);
  }

  function attach(liabId, propId) {
    setAttachments(a => ({ ...a, [liabId]: propId }));
    // write mortgage back to REO property record
    try {
      const reo = JSON.parse(localStorage.getItem(REO_REF_C)) || { properties: {} };
      const liab = reportLiabs.find(l => l.id === liabId);
      Object.keys(reo.properties).forEach(k => {
        reo.properties[k] = reo.properties[k].map(p => p.id === propId
          ? { ...p, mortgage: { creditor: liab.creditor, balance: liab.balance, payment: liab.payment, fromCredit: true } }
          : p);
      });
      // POC island guardrail: do not persist credit-derived mortgage data back
      // into browser storage. The accepted Next.js integration must route any
      // borrower-supplied updates through approved application intake paths.
    } catch {}
    setAttachModal(null);
  }
  function detach(liabId) {
    const propId = attachments[liabId];
    setAttachments(a => { const n = { ...a }; delete n[liabId]; return n; });
    try {
      const reo = JSON.parse(localStorage.getItem(REO_REF_C)) || { properties: {} };
      Object.keys(reo.properties).forEach(k => {
        reo.properties[k] = reo.properties[k].map(p => p.id === propId ? (() => { const q = { ...p }; delete q.mortgage; return q; })() : p);
      });
      // POC island guardrail: keep detach local-only; do not write credit-linked
      // mortgage data back into browser storage from this static prototype.
    } catch {}
    setConfirmDetach(null);
    setDetailLiab(null);
  }

  const statusBadge = (key) => {
    const s = auth[key];
    if (s === 'authorized') return <span className="cr-badge ok">{I.check(11)} Authorized</span>;
    if (key !== 'primary') return <span className="cr-badge">Pending</span>;
    return <span className="cr-badge">Not Authorized</span>;
  };

  /* ---------- AUTHORIZE PHASE ---------- */
  if (phase === 'authorize') {
    return (
      <main className="flow">
        <div className="flow-col">
          <div className="step">
            <StepHead title="Credit Authorization"
              sub="Click Authorize to confirm your information and accept the terms for credit authorization. Once all borrowers have authorized, your credit report will be ordered and reviewed with your loan team." />

            <div className="ei-list">
              {borrowers.map(b => (
                <div className="cr-borrower" key={b.key}>
                  <span className="co-card-ava">{(b.name[0] || '') + (b.name.split(' ')[1]?.[0] || '')}</span>
                  <div className="cr-binfo">
                    <div className="co-card-name">{b.name}</div>
                    <div className="person-bar-tag">{b.role}</div>
                    {b.key !== 'primary' &&
                      <div className="cr-invite-note">The loan team will reach out to authorize their credit.</div>}
                  </div>
                  <div className="cr-bright">
                    {statusBadge(b.key)}
                    {b.key === 'primary' && auth[b.key] !== 'authorized' &&
                      <button className="btn btn-primary btn-sm" onClick={() => setAuthModal(b)}>Authorize</button>}
                  </div>
                </div>
              ))}
            </div>

            {borrowers.length > 1 &&
              <p className="ei-prompt">Your credit report will be ordered after you authorize. The loan team will contact your co-borrower separately.</p>}

            <div className="step-nav">
              <button className="btn btn-secondary" onClick={onBack}>{I.back(16)}Back</button>
              <button className="btn btn-primary" disabled={!allAuthorized} onClick={startPull}>Continue{I.arrow(16)}</button>
            </div>
          </div>
        </div>
        {authModal && <AuthorizeModal borrower={authModal} onClose={() => setAuthModal(null)} onAuthorize={authorize} />}
      </main>
    );
  }

  /* ---------- PULLING PHASE ---------- */
  if (phase === 'pulling') {
    return (
      <main className="flow">
        <div className="flow-col">
          <div className="step step-anim">
            <StepHead title="Checking your credit"
              sub="We're securely ordering your credit report. This usually takes under a minute; please keep this page open." />
            <div className="liab-helper">
              <div className="liab-helper-title"><span className="zip-spin" style={{ marginRight: 8, verticalAlign: 'middle' }} />Contacting the credit bureaus</div>
              <p>Your authorization has been recorded. If this takes longer than expected, your loan team will finish the credit check and follow up with you directly.</p>
            </div>
          </div>
        </div>
      </main>
    );
  }

  /* ---------- LIABILITIES PHASE ---------- */
  const liabAttachedProp = id => { const pid = attachments[id]; return pid ? properties.find(p => p.id === pid) : null; };

  return (
    <main className="flow">
      <div className="flow-col flow-col-wide">
        <div className="step">
          <StepHead title="Credit Report Liabilities"
            sub={reportLiabs.length
              ? "Review the liabilities from your credit report below. If you have questions about anything shown here, please contact your loan officer directly."
              : "Your credit authorization has been recorded. Your credit report will be ordered and reviewed with your loan team, and any liabilities will be confirmed with you before anything is finalized."} />

          {reportLiabs.length === 0 &&
            <div className="liab-helper">
              <div className="liab-helper-title">{paymentRequired ? 'Payment link required' : 'What happens next'}</div>
              <p>{paymentRequired
                ? 'Your credit authorization has been recorded. Your loan team will send the required secure payment link before the credit report is ordered.'
                : 'Nothing else is needed from you on this step. Once your credit report is processed, your loan team will review mortgages, credit cards, auto loans, student loans, and other obligations with you directly.'}</p>
            </div>}

          <div className="liab-list">
            {reportLiabs.map(l => {
              const attachedProp = liabAttachedProp(l.id);
              return (
                <div className="liab-card" key={l.id}>
                  <button className="liab-main" onClick={() => setDetailLiab(l)}>
                    <span className="liab-icon">{LIAB_ICON(l.type)}</span>
                    <span className="liab-body">
                      <span className="liab-cred">{l.creditor}</span>
                      <span className="liab-type">{l.type}</span>
                      <span className="liab-nums">
                        <span>Balance <strong>${l.balance}</strong></span>
                        <span>Monthly <strong>${l.payment}</strong></span>
                      </span>
                      {attachedProp && <span className="liab-attached">{I.check(11)} Attached to: {propAddr(attachedProp)}</span>}
                    </span>
                    <span className="liab-chev">{I.chev(18)}</span>
                  </button>
                  {l.type === 'Mortgage' &&
                    <div className="liab-actions">
                      {attachedProp
                        ? <button className="co-act" onClick={() => setAttachModal(l)}>{I.home(13)} Change Attached Property</button>
                        : <button className="btn btn-primary btn-sm" onClick={() => setAttachModal(l)}>{I.home(14)} Attach to Property</button>}
                    </div>}
                </div>
              );
            })}
          </div>

          {REPORT_LIABS.length > 0 &&
            <div className="liab-helper">
              <div className="liab-helper-title">About these liabilities</div>
              <p>These liabilities come from your credit report. They may include mortgages, credit cards, revolving debt, installment loans, auto loans, student loans, and other obligations. If you notice something that does not look right, please contact your loan officer directly.</p>
            </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 and Continue{I.arrow(16)}</button>
          </div>
        </div>
      </div>

      {/* detail drawer */}
      {detailLiab && (
        <div className="drawer-scrim" onClick={() => setDetailLiab(null)}>
          <div className="drawer" onClick={e => e.stopPropagation()}>
            <div className="drawer-head">
              <span className="liab-icon">{LIAB_ICON(detailLiab.type)}</span>
              <div style={{ flex: 1 }}>
                <div className="drawer-title">{detailLiab.creditor}</div>
                <div className="person-bar-tag">{detailLiab.type}</div>
              </div>
              <button className="chat-x" onClick={() => setDetailLiab(null)}>{I.no(18)}</button>
            </div>
            <div className="drawer-body">
              {[['Current Balance', '$' + detailLiab.balance], ['Monthly Payment', '$' + detailLiab.payment],
                detailLiab.limit && ['Credit Limit', '$' + detailLiab.limit],
                detailLiab.original && ['Original Loan Amount', '$' + detailLiab.original],
                detailLiab.status && ['Account Status', detailLiab.status],
                detailLiab.reported && ['Last Reported', detailLiab.reported]].filter(Boolean).map(([k, v]) => (
                <div className="drawer-row" key={k}><span>{k}</span><strong>{v}</strong></div>
              ))}
              {detailLiab.type === 'Mortgage' && liabAttachedProp(detailLiab.id) &&
                <button className="co-act danger" style={{ marginTop: 14 }} onClick={() => setConfirmDetach(detailLiab.id)}>{I.trash(13)} Remove Attachment</button>}
              <div className="liab-notice">{I.lock(14)} This information comes from your credit report. If you have questions or believe something is incorrect, please contact your loan officer directly.</div>
            </div>
          </div>
        </div>
      )}

      {attachModal && <AttachModal liability={attachModal} properties={properties} currentPropId={attachments[attachModal.id]}
        onClose={() => setAttachModal(null)} onAttach={attach} />}

      {confirmDetach && (
        <div className="modal-scrim" onClick={() => setConfirmDetach(null)}>
          <div className="modal" onClick={e => e.stopPropagation()}>
            <div className="modal-title">Remove mortgage attachment?</div>
            <div className="modal-body">This will disconnect this mortgage from the property, but it will not remove the liability from the credit report.</div>
            <div className="modal-actions">
              <button className="btn btn-secondary" onClick={() => setConfirmDetach(null)}>Cancel</button>
              <button className="btn btn-danger" onClick={() => detach(confirmDetach)}>Remove Attachment</button>
            </div>
          </div>
        </div>
      )}
    </main>
  );
}

window.CreditLiabilities = CreditLiabilities;
window.REPORT_LIABS = REPORT_LIABS;
