/* global React, BrainMark, I, StepHead, CheckRow, incomeSummary, assetSummary, reoAddrLine, CB_CREDIT_LABEL, REPORT_LIABS */
const { useState: useRS, useEffect: useRSE } = React;

const RS_PTYPE = { single: 'Single-Family Home', condo: 'Condo', multi: 'Multi-Family Home (2 to 4 Units)', manufactured: 'Manufactured Home', coop: 'Co-op' };
const RS_USE = { primary: 'Primary Residence', second: 'Second Home', investment: 'Investment Property' };
const RS_BUYING = { 'very-early': 'Very early', 'signed': "Signed a purchase contract", 'asap': 'As soon as possible' };
const RS_GOAL = { 'reduce-payment': 'Reduce My Monthly Payment', 'reduce-term': 'Reduce My Mortgage Term', 'cash-out': 'Take Cash Out' };
const RS_MARITAL = { Married: 'Married', Unmarried: 'Unmarried', Separated: 'Separated' };

const rsGet = k => { try { return JSON.parse(localStorage.getItem(k)); } catch { return null; } };

const rsMoney = n => '$' + Math.round(Number(n) || 0).toLocaleString();
const rsPct = n => (Number(n) * 100).toFixed(1) + '%';

function rsBorrowers(bi) {
  if (!bi) return [];
  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 list = [{ key: 'primary', name: nm, role: 'Primary Borrower' }];
  (bi.coBorrowers || []).forEach((c, i) => list.push({ key: 'co-' + i, name: `${c.name.first} ${c.name.last}`.trim(), role: 'Co-Borrower' }));
  return list;
}
const addrStr = a => a ? (a.intl
  ? `${a.street}${a.unit ? ', ' + a.unit : ''}, ${[a.city, a.province].filter(Boolean).join(', ')} ${a.postal}, ${a.country}`
  : `${a.street}${a.unit ? ', ' + a.unit : ''}, ${[a.city, a.state].filter(Boolean).join(', ')} ${a.zip}`) : '—';

/* ---- summary card shell ---- */
function RCard({ title, status, statusKind = 'ok', children, onEdit, editLabel = 'Edit', extraAction }) {
  return (
    <div className="rs-card">
      <div className="rs-card-head">
        <div className="rs-card-titles">
          <span className="rs-card-title">{title}</span>
          {status && <span className={'cr-badge ' + statusKind}>{statusKind === 'ok' && I.check(11)} {status}</span>}
        </div>
        <div className="rs-card-actions">
          {extraAction}
          {onEdit && <button className="co-act" onClick={onEdit}>{I.pencil(13)}{editLabel}</button>}
        </div>
      </div>
      <div className="rs-card-body">{children}</div>
    </div>
  );
}
const Row = ({ k, v }) => <div className="rs-row"><span>{k}</span><span className="rs-row-v">{v}</span></div>;

/* ===================================================================== */
function ReviewSubmit({ loanType = 'purchase', onEdit, onBack, onSubmitted, onProgress }) {
  const [confirm, setConfirm] = useRS(false);
  // Playbook handoff: when readiness fails, the borrower may still proceed,
  // but only after explicitly acknowledging the direct readiness message.
  const [proceedAnyway, setProceedAnyway] = useRS(false);
  // Submitted-aware: a loan that was already submitted shows its submission
  // state and offers "send updates" instead of a first-time submit.
  const [loanStatus, setLoanStatus] = useRS(window.__bevriLoanStatus && window.__bevriLoanStatus.submitted ? window.__bevriLoanStatus : null);
  useRSE(() => {
    let alive = true;
    const check = window.fetchPosLoanStatus ? window.fetchPosLoanStatus() : Promise.resolve(null);
    check.then(d => { if (alive && d && d.success && d.submitted) setLoanStatus(d); }).catch(() => {});
    return () => { alive = false; };
    // eslint-disable-next-line
  }, []);
  const alreadySubmitted = Boolean(loanStatus && loanStatus.submitted);
  const [submitted, setSubmitted] = useRS(false);
  const [submitting, setSubmitting] = useRS(false);
  const [submitError, setSubmitError] = useRS('');
  const [submitRef, setSubmitRef] = useRS(null);
  const [uploads, setUploads] = useRS([]);
  const [uploading, setUploading] = useRS(false);
  const [uploadError, setUploadError] = useRS('');
  const [autoFillNote, setAutoFillNote] = useRS('');
  const [docStatuses, setDocStatuses] = useRS({});

  // Real submission: flush the latest draft to the server, then mark the
  // application submitted. Success is only shown when the server confirms.
  async function submitApplication() {
    if (submitting) return;
    setSubmitting(true); setSubmitError('');
    try {
      const loanId = window.BevriPosStorage?.loanId || new URLSearchParams(window.location.search).get('loanId') || '';
      if (!loanId) throw new Error('Missing application link. Refresh and try again.');
      try { await window.BevriPosStorage?.syncNow?.(); } catch {}
      const res = await fetch('/api/pos/intake/submit', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          loanId,
          // Handoff acknowledgment (playbook Stage 2): recorded with the
          // submission. The authoritative readiness grade is recomputed
          // server-side from the synced draft; this only records intent.
          proceededDespiteFail: Boolean(scorecard && !scorecard.pass && proceedAnyway),
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (res.status === 422 && data && data.error === 'required_fields_missing' && Array.isArray(data.missing)) {
        setRequired({ success: true, complete: false, missing: data.missing });
        try { window.__bevriRequiredMissing = data.missing.map(m => m.label + ' (' + m.section + ')'); } catch {}
        throw new Error('A few required items still need to be finished. They are listed above with a shortcut to each one.');
      }
      if (!res.ok || !data.success) throw new Error(data.error || 'Could not submit your application. Please try again.');
      setSubmitRef(data);
      if (alreadySubmitted) {
        try { window.showToast && window.showToast('Your updates were sent to your loan team', 'ok'); } catch {}
        if (window.fetchPosLoanStatus) window.fetchPosLoanStatus();
        onSubmitted && onSubmitted();
        return;
      }
      const el = document.querySelector('.flow'); if (el) el.scrollTop = 0;
      setSubmitted(true);
    } catch (err) {
      setSubmitError(err?.message || 'Could not submit your application. Please try again.');
    } finally {
      setSubmitting(false);
    }
  }
  const [snap, setSnap] = useRS(null);
  const [checklist, setChecklist] = useRS([]);
  const [gates, setGates] = useRS([]);
  const [snapState, setSnapState] = useRS('loading'); // loading | ready | error
  // Live refresh: any operator/auto-fill write bumps the tick, which re-renders
  // (the section summaries below read storage during render) and re-runs the
  // qualification snapshot fetch. No page reload.
  const [refreshTick, setRefreshTick] = useRS(0);
  // Required-field gate (LOS parity): the server evaluates the synced draft
  // against the same list the submit route enforces. null means unknown (the
  // UI stays permissive; the server gate still protects).
  const [required, setRequired] = useRS(null);
  useRSE(() => {
    let alive = true;
    const loanId = window.BevriPosStorage?.loanId || new URLSearchParams(window.location.search).get('loanId') || '';
    if (!loanId) return undefined;
    Promise.resolve(window.BevriPosStorage?.syncNow?.()).catch(() => {})
      .then(() => fetch('/api/pos/intake/required?loanId=' + encodeURIComponent(loanId), { credentials: 'same-origin' }))
      .then(r => (r && r.ok ? r.json() : null))
      .then(d => {
        if (!alive || !d || !d.success) return;
        setRequired(d);
        // Ride the operator context so the chat can point at the same gaps.
        try { window.__bevriRequiredMissing = (d.missing || []).map(m => m.label + ' (' + m.section + ')'); } catch {}
      })
      .catch(() => {});
    return () => { alive = false; };
    // eslint-disable-next-line
  }, [refreshTick]);
  useRSE(() => {
    function onAutoFill() { setRefreshTick(t => t + 1); }
    window.addEventListener('bevri:fields-autofilled', onAutoFill);
    return () => window.removeEventListener('bevri:fields-autofilled', onAutoFill);
  }, []);
  useRSE(() => { onProgress && onProgress({ fill: 95, stepTitle: 'review' }); }, []);

  // Read-only qualification snapshot: send the saved intake to the canonical
  // readiness engine (server-side mapping) and render the result. No writes.
  useRSE(() => {
    let alive = true;
    const applicationContext = {
      purchase: rsGet('bevri_purchase_v1'),
      refinance: rsGet('bevri_refinance_v1'),
      income: rsGet('bevri_income_v1'),
      assets: rsGet('bevri_assets_v1'),
      credit: rsGet('bevri_credit_v1'),
    };
    fetch('/api/pos/intake/readiness', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ applicationContext }),
    })
      .then(r => (r.ok ? r.json() : Promise.reject(new Error('readiness unavailable'))))
      .then(d => { if (alive && d && d.summary) { setSnap(d.summary); setChecklist(Array.isArray(d.checklist) ? d.checklist : []); setGates(Array.isArray(d.gates) ? d.gates : []); setSnapState('ready'); } else if (alive) setSnapState('error'); })
      .catch(() => { if (alive) setSnapState('error'); });
    return () => { alive = false; };
  }, [refreshTick]);

  // Readiness scorecard (playbook Stage 1 view): graded pass/fail from the
  // backend. Fully additive: when the endpoint is unavailable the card simply
  // does not render, and nothing else depends on it.
  const [scorecard, setScorecard] = useRS(null);
  useRSE(() => {
    let alive = true;
    const applicationContext = {
      purchase: rsGet('bevri_purchase_v1'),
      refinance: rsGet('bevri_refinance_v1'),
      borrower: rsGet('bevri_borrower_v1'),
      income: rsGet('bevri_income_v1'),
      assets: rsGet('bevri_assets_v1'),
      credit: rsGet('bevri_credit_v1'),
      questions: rsGet('bevri_questions_v1'),
      documents: rsGet('bevri_documents_v1'),
    };
    const loanId = window.BevriPosStorage?.loanId || '';
    fetch('/api/pos/intake/scorecard', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ applicationContext, loanId }),
    })
      .then(r => (r.ok ? r.json() : null))
      .then(d => { if (alive) setScorecard(d && d.scorecard ? d.scorecard : null); })
      .catch(() => { if (alive) setScorecard(null); });
    return () => { alive = false; };
  }, [refreshTick]);

  async function uploadBorrowerDocs(files, documentType = 'borrower_upload') {
    const loanId = window.BevriPosStorage?.loanId || new URLSearchParams(window.location.search).get('loanId') || '';
    if (!loanId) { setUploadError('Missing application link. Refresh and try again.'); return; }
    const picked = Array.from(files || []);
    if (!picked.length) return;
    setUploading(true); setUploadError('');
    const completed = [];
    for (const file of picked) {
      const body = new FormData();
      body.append('loanId', loanId);
      body.append('documentType', documentType);
      body.append('file', file, file.name);
      const res = await fetch('/api/pos/intake/documents/upload', { method: 'POST', body });
      const data = await res.json().catch(() => ({}));
      if (res.status === 429 || data.limitReached) {
        window.dispatchEvent(new CustomEvent('bevri:signup-open'));
        throw new Error(data.error || 'You can upload up to 5 documents to get started. Sign up to upload more.');
      }
      if (!res.ok || !data.success) throw new Error(data.error || `Could not upload ${file.name}`);
      completed.push(data.document || { name: file.name, status: 'uploaded' });
    }
    setUploads(u => [...completed, ...u]);
    for (const doc of completed) {
      if (doc.id) {
        setDocStatuses(s => ({ ...s, [doc.id]: 'analyzing' }));
        window.pollAndAutoFill?.(doc.id, loanId).then(result => {
          const status = result?.filled?.length > 0 ? 'filled' : 'uploaded';
          setDocStatuses(s => ({ ...s, [doc.id]: status }));
          if (result?.filled?.length > 0) {
            setAutoFillNote(`${result.filled.length} field${result.filled.length === 1 ? '' : 's'} from your document ${result.filled.length === 1 ? 'was' : 'were'} filled in automatically. Review your application before submitting.`);
          }
        }).catch(() => setDocStatuses(s => ({ ...s, [doc.id]: 'uploaded' })));
      }
    }
    setUploading(false);
  }

  async function onDocInput(e, type) {
    try { await uploadBorrowerDocs(e.target.files, type); }
    catch (err) { setUploading(false); setUploadError(err?.message || 'Upload failed'); }
    finally { e.target.value = ''; }
  }

  const bi = rsGet('bevri_borrower_v1')?.data;
  const pu = rsGet('bevri_purchase_v1')?.data;
  const rf = rsGet('bevri_refinance_v1')?.data;
  const income = rsGet('bevri_income_v1')?.incomes || {};
  const assets = rsGet('bevri_assets_v1')?.assets || {};
  const reo = rsGet('bevri_reo_v1')?.properties || {};
  const credit = rsGet('bevri_credit_v1') || { auth: {}, attachments: {}, pulled: false };
  const questions = rsGet('bevri_questions_v1')?.answers || {};

  const borrowers = rsBorrowers(bi);
  const isRefi = loanType === 'refinance';
  const bName = key => (borrowers.find(b => b.key === key) || {}).name || 'Borrower';

  // declarations "yes" highlights for primary
  const decl = questions.primary || {};
  const declYes = [];
  if (decl.complete) {
    if (decl.undisclosed === 'yes') declYes.push(`Undisclosed funds: $${decl.undisclosedAmt}`);
    if (decl.coSigner === 'yes') declYes.push('Co-signer / guarantor disclosed');
    if (decl.judgments === 'yes') declYes.push(`Outstanding judgment: $${decl.judgmentAmt}`);
    if (decl.fedDebt === 'yes') declYes.push(`Delinquent federal debt: $${decl.fedDebtAmt}`);
    if (decl.lawsuit === 'yes') declYes.push('Lawsuit with potential liability');
    if (decl.bankruptcy === 'yes') declYes.push(`Bankruptcy: ${decl.bkType}${decl.notDischarged ? ' (not discharged)' : ''}`);
    if (decl.foreclosure === 'yes') declYes.push('Prior foreclosure (7 yrs)');
  }

  const authLabel = key => {
    const s = credit.auth[key];
    if (credit.pulled && s === 'authorized') return { t: 'Authorized & pulled', k: 'ok' };
    if (s === 'authorized') return { t: 'Authorized', k: 'ok' };
    if (s === 'invited') return { t: 'Invitation sent', k: 'pending' };
    return { t: 'Not authorized', k: '' };
  };

  if (submitted) {
    return (
      <main className="flow">
        <div className="flow-col">
          <div className="step rs-success">
            <div className="rs-success-burst">
              <span className="rs-burst-ring" /><span className="rs-burst-ring r2" />
              <span className="rs-success-mark">{I.checkDark ? I.checkDark(40) : '✓'}</span>
            </div>
            <p className="eyebrow mono" style={{ color: 'var(--sage)' }}>APPLICATION SUBMITTED</p>
            <h1 className="hero-title" style={{ fontSize: 34 }}>Great job! Your application has been submitted.</h1>
            <p className="hero-sub" style={{ maxWidth: 520 }}>Thank you for completing your application. Your loan team now has what they need to begin reviewing your file. This is just the beginning.</p>
            {submitRef?.loanCode && <p className="eyebrow mono" style={{ marginTop: 4 }}>Reference: {submitRef.loanCode}</p>}
            {submitRef?.readiness?.grade && (
              <p className="eyebrow mono" style={{ marginTop: 2 }}>
                Submitted with readiness grade {submitRef.readiness.grade} ({submitRef.readiness.score}/100)
              </p>
            )}
            <div className="rs-next">
              <div className="rs-next-title">What happens next?</div>
              <div className="rs-next-step"><span className="rs-next-num mono">1</span><div><div className="rs-next-h">Upload required documents</div><div className="rs-next-d">We'll guide you through the documents needed to support your application.</div></div></div>
              <div className="rs-next-step"><span className="rs-next-num mono">2</span><div><div className="rs-next-h">Loan officer review</div><div className="rs-next-d">Your loan officer will review your information and reach out if anything else is needed.</div></div></div>
            </div>
            <div className="rs-success-actions">
              <button className="btn btn-primary btn-block" onClick={() => onSubmitted && onSubmitted()}>Continue{I.arrow(16)}</button>
              <button className="btn btn-secondary btn-block" onClick={() => onSubmitted && onSubmitted()}>Return to Dashboard</button>
            </div>
          </div>
        </div>
      </main>
    );
  }

  return (
    <main className="flow">
      <div className="flow-col flow-col-wide">
        <div className="step">
          <StepHead title="Review &amp; Submit"
            sub="Take a final look at your application before submitting it to your loan team. If anything looks incorrect or incomplete, you can edit it before submitting." />

          {/* Readiness Scorecard — playbook Stage 1 graded view. Renders only
              when the backend scorecard is available; read-only. */}
          {scorecard && (
            <RCard title="Readiness Scorecard"
              status={scorecard.pass ? 'On track' : 'Needs work'}
              statusKind={scorecard.pass ? 'ok' : 'pending'}>
              <Row k="Readiness grade" v={<span className={'cr-badge ' + (scorecard.pass ? 'ok' : 'pending')}>{scorecard.grade} · {scorecard.score}/100</span>} />
              <div className="rs-muted" style={{ marginTop: 2 }}>
                {scorecard.pass
                  ? 'Your file meets the readiness bar for your loan team to pick it up.'
                  : 'Based on what we have gathered, this loan is not yet positioned for a one-touch review. The items below will improve its readiness.'}
              </div>
              {Array.isArray(scorecard.missingItems) && scorecard.missingItems.length > 0 && (
                <div style={{ marginTop: 12 }}>
                  <div className="rs-person-name sm" style={{ marginBottom: 6 }}>To strengthen your file</div>
                  {scorecard.missingItems.map(item => (
                    <div key={item.id} style={{ marginBottom: 6 }}>
                      <Row k={item.label} v={<span className="cr-badge pending">Needed</span>} />
                      <div className="rs-muted" style={{ marginTop: 2 }}>{item.detail}</div>
                    </div>
                  ))}
                </div>
              )}
              <div className="rs-muted" style={{ marginTop: 8 }}>
                Underwriting, disclosures, and loan product selection are handled with your loan team and are not part of this grade.
              </div>
            </RCard>
          )}

          {/* 0. Qualification Snapshot — read-only estimate from the canonical engine */}
          <RCard title="Qualification Snapshot"
            status={snapState === 'ready' ? 'Estimate' : snapState === 'loading' ? 'Calculating…' : 'Unavailable'}
            statusKind="pending">
            {snapState === 'loading' && <div>
              <div className="skel skel-row w-60" />
              <div className="skel skel-row w-40" />
              <div className="skel skel-row w-80" style={{ marginBottom: 0 }} />
            </div>}
            {snapState === 'error' && <div className="rs-muted">We couldn't build a snapshot right now. This doesn't affect your application.</div>}
            {snapState === 'ready' && snap && <>
              <Row k="Qualifying monthly income" v={rsMoney(snap.income.qualifyingMonthlyIncome)} />
              <Row k="Liquid assets" v={rsMoney(snap.assets.liquidAssets)} />
              {snap.loan.loanAmount > 0 && snap.loan.propertyValue > 0 &&
                <Row k="Loan-to-value (LTV)" v={rsPct(snap.loan.ltv)} />}
              {checklist.length > 0 && <div style={{ marginTop: 12 }}>
                <div className="rs-person-name sm" style={{ marginBottom: 6 }}>Application checklist</div>
                {checklist.map(item => (
                  <div key={item.id} style={{ marginBottom: 6 }}>
                    <Row
                      k={item.done ? <span className="ei-verified">{I.check(11)} {item.label}</span> : item.label}
                      v={<span className={'cr-badge ' + (item.done ? 'ok' : 'pending')}>{item.done ? 'Added' : 'Needed'}</span>} />
                    {!item.done && <div className="rs-muted" style={{ marginTop: 2 }}>{item.hint}</div>}
                  </div>
                ))}
                <div className="rs-muted" style={{ marginTop: 8 }}>Credit authorization and final income and asset verification are completed with your loan team.</div>
              </div>}
              {gates.length > 0 && <div style={{ marginTop: 12 }}>
                <div className="rs-person-name sm" style={{ marginBottom: 6 }}>File readiness</div>
                {gates.map(gate => (
                  <div key={gate.id} style={{ marginBottom: 6 }}>
                    <Row
                      k={gate.ready ? <span className="ei-verified">{I.check(11)} {gate.label}</span> : gate.label}
                      v={<span className={'cr-badge ' + (gate.ready ? 'ok' : 'pending')}>{gate.ready ? 'Ready' : 'Not yet'}</span>} />
                    <div className="rs-muted" style={{ marginTop: 2 }}>{gate.detail}</div>
                  </div>
                ))}
                <div className="rs-muted" style={{ marginTop: 8 }}>These show readiness only. Underwriting, disclosures, and signing are handled by your loan team.</div>
              </div>}
              <div className="rs-muted" style={{ marginTop: 8 }}>Preliminary estimate based on the information you provided. It is not a credit decision, pre-approval, or final loan offer.</div>
            </>}
          </RCard>

          {/* 1. Borrower Information (borrower-first order) */}
          <RCard title="Borrower Information" status="Complete" onEdit={() => onEdit('borrower')} editLabel="Edit Borrower Info"
            extraAction={(bi?.coBorrowers || []).length < 3 ? <button className="co-act" onClick={() => onEdit('borrower')}>{I.plus(13)}Add Co-Borrower</button> : null}>
            {borrowers.map((b, i) => {
              const src = b.key === 'primary' ? bi : bi.coBorrowers[i - 1];
              return (
                <div className="rs-person" key={b.key}>
                  <div className="rs-person-head"><span className="co-card-ava sm">{(b.name[0] || '') + (b.name.split(' ')[1]?.[0] || '')}</span><div><div className="rs-person-name">{b.name}</div><div className="person-bar-tag">{b.role}</div></div></div>
                  <Row k="Current address" v={addrStr(src.curAddr)} />
                  <Row k="Citizenship" v={src.citizenship || '—'} />
                  <Row k="Marital status" v={RS_MARITAL[src.marital] || '—'} />
                  <Row k="Credit range" v={CB_CREDIT_LABEL?.[src.credit] || src.credit || '—'} />
                </div>
              );
            })}
          </RCard>

          {/* 2. Loan Details */}
          <RCard title="Loan Details" status="Complete" onEdit={() => onEdit('loan')} editLabel="Edit Loan Details">
            {isRefi ? <>
              <Row k="Loan purpose" v="Refinance" />
              <Row k="Primary goal" v={RS_GOAL[rf?.mainGoal] || '—'} />
              {rf?.mainGoal === 'cash-out' && <Row k="Cash out" v={`$${rf?.cashOut || '0'}`} />}
              <Row k="Current use" v={RS_USE[rf?.currentUse] || '—'} />
              <Row k="Future use" v={RS_USE[rf?.futureUse] || '—'} />
              <Row k="Property type" v={RS_PTYPE[rf?.ptype] || '—'} />
            </> : <>
              <Row k="Loan purpose" v="Purchase" />
              <Row k="Buying process" v={RS_BUYING[pu?.buying] || '—'} />
              <Row k="Property use" v={RS_USE[pu?.use] || '—'} />
              <Row k="Property type" v={RS_PTYPE[pu?.ptype] || '—'} />
              <Row k="Target price" v={`$${pu?.price || '0'}`} />
              <Row k="Down payment" v={`$${pu?.dpAmt || '0'}${pu?.dpPct ? ` · ${pu.dpPct}%` : ''}`} />
              <Row k="Real estate agent" v={pu?.hasAgent === 'yes' ? `${pu.agent.first} ${pu.agent.last}` : 'Not working with an agent'} />
            </>}
          </RCard>

          {/* 3. Subject Property */}
          <RCard title="Subject Property" status="Complete" onEdit={() => onEdit('loan')} editLabel="Edit Subject Property">
            {isRefi ? <>
              <Row k="Address" v={addrStr(rf?.addr)} />
              <Row k="Estimated value" v={`$${rf?.value || '0'}`} />
              <Row k="Current use" v={RS_USE[rf?.currentUse] || '—'} />
              <Row k="Future use" v={RS_USE[rf?.futureUse] || '—'} />
              <Row k="Property type" v={RS_PTYPE[rf?.ptype] || '—'} />
            </> : <>
              <Row k="Address" v={pu?.addr?.noAddr ? `Searching in ${[pu.addr.city, pu.addr.state].filter(Boolean).join(', ') || 'target area'}` : (pu?.addr?.street ? addrStr(pu.addr) : 'No exact property address provided yet')} />
              <Row k="Intended use" v={RS_USE[pu?.use] || '—'} />
              <Row k="Property type" v={RS_PTYPE[pu?.ptype] || '—'} />
              <Row k="Target price" v={`$${pu?.price || '0'}`} />
              <Row k="Down payment" v={`$${pu?.dpAmt || '0'}`} />
            </>}
          </RCard>

          {/* 4. Employment & Income */}
          <RCard title="Employment &amp; Income" status="Complete" onEdit={() => onEdit('employment')} editLabel="Edit Income"
            extraAction={<button className="co-act" onClick={() => onEdit('employment')}>{I.plus(13)}Add Income</button>}>
            {borrowers.map(b => {
              const list = income[b.key] || [];
              return (
                <div className="rs-person" key={b.key}>
                  <div className="rs-person-name sm">{b.name}</div>
                  {list.length === 0 ? <div className="rs-muted">No income added</div>
                    : list.map(s => { const sm = incomeSummary(s); return <Row key={s.id} k={sm.title} v={<>{sm.detail}{sm.verified && <span className="ei-verified" style={{ marginLeft: 8 }}>{I.check(11)} Verified</span>}</>} />; })}
                </div>
              );
            })}
          </RCard>

          {/* 5. Assets */}
          <RCard title="Assets" status="Complete" onEdit={() => onEdit('assets')} editLabel="Edit Assets"
            extraAction={<button className="co-act" onClick={() => onEdit('assets')}>{I.plus(13)}Add Asset</button>}>
            {borrowers.map(b => {
              const list = assets[b.key] || [];
              return (
                <div className="rs-person" key={b.key}>
                  <div className="rs-person-name sm">{b.name}</div>
                  {list.length === 0 ? <div className="rs-muted">No assets added</div>
                    : list.map(a => { const sm = assetSummary(a); return <Row key={a.id} k={sm.title} v={<>{sm.detail}{sm.verified && <span className="ei-verified" style={{ marginLeft: 8 }}>{I.check(11)} Verified</span>}</>} />; })}
                </div>
              );
            })}
          </RCard>

          {/* 6. Real Estate Owned */}
          <RCard title="Real Estate Owned" status="Complete" onEdit={() => onEdit('reo')} editLabel="Edit Real Estate"
            extraAction={<button className="co-act" onClick={() => onEdit('reo')}>{I.plus(13)}Add Property</button>}>
            {borrowers.map(b => {
              const list = reo[b.key] || [];
              if (!list.length) return null;
              return (
                <div className="rs-person" key={b.key}>
                  <div className="rs-person-name sm">{b.name}</div>
                  {list.map(p => (
                    <div key={p.id} className="rs-prop">
                      <Row k={reoAddrLine(p)} v={[p.ptype, p.usage].filter(Boolean).join(' · ')} />
                      {p.value && <div className="rs-sub">Est. value ${p.value} · {p.status || '—'}{p.usage === 'Investment Property' && p.rentalIncome ? ` · $${p.rentalIncome}/mo rent` : ''}</div>}
                      {p.mortgage && <div className="rs-sub mort">{I.home(12)} {p.mortgage.creditor} · ${p.mortgage.balance} · ${p.mortgage.payment}/mo</div>}
                    </div>
                  ))}
                </div>
              );
            })}
            {Object.values(reo).every(l => !l || !l.length) && <div className="rs-muted">No real estate owned</div>}
          </RCard>

          {/* 7. Liabilities */}
          <RCard title="Liabilities" status={(window.REPORT_LIABS || []).length ? 'From credit report' : 'Pending credit report'} statusKind="pending" onEdit={() => onEdit('credit')} editLabel="View Credit Step">
            {(window.REPORT_LIABS || []).map(l => (
              <div key={l.id} className="rs-liab">
                <Row k={`${l.creditor} · ${l.type}`} v={`$${l.balance} · $${l.payment}/mo`} />
                {credit.attachments?.[l.id] && <div className="rs-sub mort">{I.check(11)} Attached to a property</div>}
              </div>
            ))}
            {(window.REPORT_LIABS || []).length === 0
              ? <div className="rs-muted">Liabilities are imported from your credit report after it is ordered and processed with your loan team. Nothing is needed from you here.</div>
              : <div className="rs-muted" style={{ marginTop: 8 }}>Credit-report liabilities are view-only. Only mortgages can attach to a property.</div>}
          </RCard>

          {/* 8. Credit Authorization */}
          <RCard title="Credit Authorization" status={credit.pulled ? 'Credit pulled' : 'In progress'} statusKind={credit.pulled ? 'ok' : 'pending'} onEdit={() => onEdit('credit')} editLabel="Review">
            {borrowers.map(b => { const a = authLabel(b.key); return <Row key={b.key} k={b.name} v={<span className={'cr-badge ' + a.k}>{a.k === 'ok' && I.check(11)} {a.t}</span>} />; })}
          </RCard>

          {/* 9. Borrower Documents */}
          <RCard title="Upload Documents" status={uploads.length ? `${uploads.length} uploaded` : 'Optional now'} statusKind={uploads.length ? 'ok' : 'pending'}>
            <div className="rs-muted" style={{ marginBottom: 10 }}>Upload PDFs or images that support the application. Common items: photo ID, pay stubs, W-2s/1099s, bank statements, purchase contract, insurance, and other requested conditions.</div>
            <div className="resume-actions" style={{ alignItems: 'stretch', flexWrap: 'wrap' }}>
              {[['income', 'Pay stubs / income'], ['asset', 'Bank statements / assets'], ['identity', 'Photo ID'], ['title', 'Purchase contract'], ['borrower_upload', 'Other document']].map(([type, label]) => (
                <label key={type} className="resume-secondary" style={{ cursor: 'pointer', textAlign: 'center' }}>
                  {label}
                  <input type="file" multiple accept=".pdf,image/*" style={{ display: 'none' }} onChange={e => onDocInput(e, type)} />
                </label>
              ))}
            </div>
            {uploading && <div className="rs-muted" style={{ marginTop: 10 }}>Uploading…</div>}
            {uploadError && <div className="rs-muted" style={{ marginTop: 10, color: '#b42318' }}>{uploadError}</div>}
            {autoFillNote && <div className="rs-muted" style={{ marginTop: 10, color: 'var(--sage, #16a34a)', fontWeight: 500 }}>{autoFillNote}</div>}
            {uploads.length > 0 && (
              <div style={{ marginTop: 12 }}>
                {uploads.map(doc => {
                  const st = doc.id ? (docStatuses[doc.id] || 'uploaded') : 'uploaded';
                  return (
                    <div key={doc.id || doc.name} className="doc-status-row">
                      <span className="doc-status-name">{doc.name}</span>
                      <span className={'doc-status-badge ' + st}>
                        {st === 'analyzing' && <span className="doc-status-spin" />}
                        {st === 'analyzing' && 'Analyzing…'}
                        {st === 'filled' && <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.8" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12.5 10 17.5 19 7" /></svg>}
                        {st === 'filled' && 'Fields filled'}
                        {st === 'uploaded' && 'Uploaded'}
                      </span>
                    </div>
                  );
                })}
              </div>
            )}
          </RCard>

          {/* 10. Declarations */}
          <RCard title="Declarations" status={decl.complete ? 'Complete' : 'Incomplete'} statusKind={decl.complete ? 'ok' : 'pending'} onEdit={() => onEdit('questions')} editLabel="Edit Declarations">
            {declYes.length ? declYes.map((d, i) => <Row key={i} k={I.yes ? 'Disclosed' : '•'} v={d} />) : <div className="rs-muted">All declaration questions answered. No items requiring attention.</div>}
          </RCard>

          {/* 11. Demographics */}
          <RCard title="Demographics" status={questions.primary?.complete ? 'Complete' : 'Incomplete'} statusKind={questions.primary?.complete ? 'ok' : 'pending'} onEdit={() => onEdit('questions')} editLabel="Edit Demographics">
            <div className="rs-muted">Demographic information completed. Your specific selections are kept private and not shown here.</div>
          </RCard>

          {/* Submitted-aware banner: this application is already with the loan
              team; the page is now for viewing and sending updates. */}
          {alreadySubmitted && (
            <div className="rs-readiness ok">
              Submitted{loanStatus.submittedAt ? ' on ' + new Date(loanStatus.submittedAt).toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' }) : ''}
              {loanStatus.readiness && loanStatus.readiness.grade ? ' with readiness grade ' + loanStatus.readiness.grade : ''}.
              Your loan team has your application. If you change anything, use "Send updates" below so they see the latest.
            </div>
          )}

          {/* Required-field checklist: what still blocks submission, why each
              item matters, and a shortcut straight to the section. */}
          {required && required.missing.length > 0 && (
            <div className="rs-required">
              <div className="rs-required-head">
                Almost there. {required.missing.length === 1 ? 'One required item' : `${required.missing.length} required items`} to finish before your loan team can review your application:
              </div>
              <div className="rs-required-list">
                {required.missing.map(m => (
                  <div className="rs-required-row" key={m.field}>
                    <div className="rs-required-txt">
                      <span className="rs-required-label">{m.label}</span>
                      <span className="rs-required-why">{m.why}</span>
                    </div>
                    <button className="co-act" onClick={() => onEdit(m.stage)}>Finish this{I.arrow(13)}</button>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* handoff readiness moment (playbook Stage 2). Renders only when a
              scorecard is available; otherwise submit behaves exactly as before. */}
          {!alreadySubmitted && scorecard && scorecard.pass && (
            <div className="rs-readiness ok">
              Readiness grade <b>{scorecard.grade}</b> ({scorecard.score}/100). Your file is ready for your loan team's review.
            </div>
          )}
          {!alreadySubmitted && scorecard && !scorecard.pass && (
            <div className="rs-readiness warn">
              <div className="rs-readiness-msg">
                Based on what we have gathered, this loan is not yet positioned for a one-touch review.
                To improve its readiness, the following {scorecard.missingItems.length === 1 ? 'item is' : 'items are'} still needed:
              </div>
              <ul className="rs-readiness-list">
                {scorecard.missingItems.slice(0, 4).map(item => <li key={item.id}>{item.label}</li>)}
              </ul>
              <CheckRow checked={proceedAnyway} onToggle={() => setProceedAnyway(v => !v)}>
                I understand and want to submit my application anyway. My loan team may follow up for the missing items.
              </CheckRow>
            </div>
          )}

          {/* confirmation (first-time submissions only) */}
          {!alreadySubmitted && (
            <div className="rs-confirm">
              <CheckRow checked={confirm} onToggle={() => setConfirm(c => !c)}>
                {scorecard && scorecard.pass
                  ? 'I confirm that the information provided is accurate and this application is ready for my loan team to review.'
                  : 'I confirm that the information provided is accurate to the best of my knowledge.'}
              </CheckRow>
            </div>
          )}

          {submitError && <div className="rs-muted" style={{ marginTop: 10, color: '#b42318' }}>{submitError}</div>}

          <div className="step-nav">
            <button className="btn btn-secondary" onClick={onBack}>{I.back(16)}Back</button>
            {alreadySubmitted ? (
              <>
                <button className="btn btn-secondary" disabled={submitting || Boolean(required && required.missing.length > 0)} onClick={submitApplication}>
                  {submitting ? 'Sending…' : 'Send updates to my loan team'}
                </button>
                <button className="btn btn-primary" onClick={() => onSubmitted && onSubmitted()}>
                  Back to tracking{I.arrow(16)}
                </button>
              </>
            ) : (
              <button className="btn btn-primary"
                disabled={!confirm || submitting || Boolean(required && required.missing.length > 0) || Boolean(scorecard && !scorecard.pass && !proceedAnyway)}
                onClick={submitApplication}>{submitting ? 'Submitting…' : 'Confirm and Submit'}{I.arrow(16)}</button>
            )}
          </div>
        </div>
      </div>
    </main>
  );
}

window.ReviewSubmit = ReviewSubmit;
