/* global React, I, StepHead, NavFooter, QuestionsFlow */
const { useState: useQA, useEffect: useQAE } = React;

const QA_LS = 'bevri_questions_v1';
const BI_REF_Q = 'bevri_borrower_v1';

function qaBorrowers() {
  try {
    const bi = JSON.parse(localStorage.getItem(BI_REF_Q))?.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' }]; }
}

/* ===================================================================== */
function QuestionsAboutYou({ loanType = 'purchase', onBack, onContinue, onProgress }) {
  const saved = (() => { try { return JSON.parse(localStorage.getItem(QA_LS)); } catch { return null; } })();
  const [answers, setAnswers] = useQA(saved?.answers || {}); // borrowerKey -> { ...flow data, complete }
  const [flow, setFlow] = useQA(null); // { borrowerKey, first, initial }
  const borrowers = qaBorrowers();

  useQAE(() => { try { localStorage.setItem(QA_LS, JSON.stringify({ answers })); } catch {} }, [answers]);
  // Live refresh: when the operator chat records a declaration, merge the
  // stored answers back into state so it shows without leaving the page.
  useQAE(() => {
    function onAutoFill(e) {
      if (!(e.detail?.posKeys || []).includes(QA_LS)) return;
      const updated = (() => { try { return JSON.parse(localStorage.getItem(QA_LS))?.answers; } catch { return null; } })();
      if (updated) setAnswers(prev => ({ ...prev, ...updated }));
    }
    window.addEventListener('bevri:fields-autofilled', onAutoFill);
    return () => window.removeEventListener('bevri:fields-autofilled', onAutoFill);
  }, []);
  useQAE(() => { onProgress && onProgress({ fill: flow ? 50 : 15, stepTitle: 'questions' }); }, [flow]);

  const allComplete = borrowers.every(b => answers[b.key]?.complete);

  function open(b) { setFlow({ borrowerKey: b.key, first: b.key === 'primary' ? '' : b.first, initial: answers[b.key] || null }); }
  function saveAnswers(d) {
    setAnswers(prev => ({ ...prev, [flow.borrowerKey]: d }));
    setFlow(null);
    const el = document.querySelector('.flow'); if (el) el.scrollTop = 0;
  }

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

  const single = borrowers.length === 1;

  return (
    <main className="flow">
      <div className="flow-col">
        <div className="step">
          <StepHead title="Background Questions"
            sub={single
              ? "A few short required questions about your loan and finances, plus optional demographic information. This is the last step before you review and submit."
              : "Each borrower needs to answer a few required questions about the loan and their finances, plus optional demographic information."} />

          <div className="ei-list">
            {borrowers.map(b => {
              const done = answers[b.key]?.complete;
              return (
                <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>
                  </div>
                  <div className="cr-bright">
                    {done ? <span className="cr-badge ok">{I.check(11)} Complete</span> : <span className="cr-badge">Not started</span>}
                    <button className={'btn btn-sm ' + (done ? 'btn-secondary' : 'btn-primary')} onClick={() => open(b)}>
                      {done ? 'Review / Edit' : 'Answer Questions'}
                    </button>
                  </div>
                </div>
              );
            })}
          </div>

          <p className="ei-prompt" style={{ marginTop: 16, fontSize: 12.5, color: 'var(--muted)' }}>
            The demographic section at the end is optional and collected as required by federal law (HMDA, the Home Mortgage Disclosure Act) to ensure fair lending practices. It does not affect your loan decision.
          </p>
          {!single && !allComplete &&
            <p className="ei-prompt">All borrowers must answer these questions before continuing to review.</p>}

          <div className="step-nav">
            <button className="btn btn-secondary" onClick={onBack}>{I.back(16)}Back</button>
            <button className="btn btn-primary" disabled={!allComplete} onClick={() => onContinue && onContinue()}>Continue to Review{I.arrow(16)}</button>
          </div>
        </div>
      </div>
    </main>
  );
}

window.QuestionsAboutYou = QuestionsAboutYou;
