/* global React, BrainMark, I, Progress, StepHead, Opt, Field, CheckRow, NavFooter, Helper, HelpLink, ZipField */
const { useState: useRF, useEffect: useRFE } = React;

/* ---------------- helpers (refi) ---------------- */
const rfDigits = s => (s || '').replace(/[^\d]/g, '');
const rfMoney = s => { const d = rfDigits(s); return d ? Number(d).toLocaleString('en-US') : ''; };
const rfNum = s => Number(rfDigits(s)) || 0;

const RF_SECTIONS = ['Refinance Details', 'Property Information', 'Borrower Information', 'Employment & Income', 'Assets', 'Credit / Declarations', 'Review & Submit'];

/* ordered steps */
const RF_STEPS = ['refi-goal', 'app-start', 'agreements', 'main-goal', 'current-use', 'address', 'value', 'future-use', 'type', 'review', 'property-info'];
const RF_PRE_APP = ['refi-goal', 'app-start', 'agreements'];
/* which section each step belongs to (for progress) */
const RF_SECTION_OF = {
  'app-start': 0, 'main-goal': 0, 'current-use': 0, 'address': 0, 'value': 0,
  'future-use': 0, 'type': 0, 'review': 0, 'property-info': 1,
};
/* steps that advance the "Refinance Details" fill bar */
const RF_DETAIL_STEPS = ['app-start', 'main-goal', 'current-use', 'address', 'value', 'future-use', 'type', 'review'];

const RF_INITGOAL = { 'lower-rate': 'Lower My Rate', 'change-term': 'Change My Loan Term', 'cash-out': 'Take Cash Out' };
const RF_MAINGOAL = { 'reduce-payment': 'Reduce My Monthly Payment', 'reduce-term': 'Reduce My Mortgage Term', 'cash-out': 'Take Cash Out' };
const RF_USE = { primary: 'Primary Residence', second: 'Second Home', investment: 'Investment Property' };
const RF_PTYPE = { single: 'Single-Family Home', condo: 'Condo', multi: 'Multi-Family Home (2 to 4 Units)', manufactured: 'Manufactured Home', coop: 'Co-op' };

const RF_DEFAULT = {
  profile: {
    name: '',
    dob: '',
    current: '',
    mailingSame: false,
  },
  agree: { electronic: false, privacy: false, origination: false },
  initGoal: null,
  mainGoal: null,
  cashOut: '',
  currentUse: null,
  addr: { street: '', unit: '', city: '', state: '', zip: '' },
  value: '',
  currentBalance: '', currentPayment: '', currentRate: '', currentServicer: '',
  futureUse: null,
  ptype: null,
  taxIncluded: false,
  taxes: '', insurance: '', hoa: '', noHoa: false,
  touched: false,
};

const RF_LS = 'bevri_refinance_v1';

/* ===================================================================== */
function RefinanceFlow({ onExit, onContinue, onProgress }) {
  const saved = (() => { try { return JSON.parse(localStorage.getItem(RF_LS)); } catch { return null; } })();
  // The retired 'review-info' profile card maps to 'agreements' so legacy
  // saved sessions don't land on a removed step. Borrower identity is
  // collected and edited in the Borrower Info section.
  const initialRefinanceStep = saved?.step === 'review-info' ? 'agreements' : (saved?.step || 'refi-goal');
  const [step, setStep] = useRF(initialRefinanceStep);
  const [data, setData] = useRF(saved?.data ? { ...RF_DEFAULT, ...saved.data, profile: { ...RF_DEFAULT.profile, ...(saved.data.profile || {}) }, touched: false } : RF_DEFAULT);
  const [editReturn, setEditReturn] = useRF(false);

  useRFE(() => {
    try { localStorage.setItem(RF_LS, JSON.stringify({ step, data })); } catch {}
  }, [step, data]);
  useRFE(() => {
    function onAutoFill(e) {
      if (!(e.detail?.posKeys || []).includes(RF_LS)) return;
      const updated = (() => { try { return JSON.parse(localStorage.getItem(RF_LS)); } catch { return null; } })();
      if (updated?.data) setData(d => ({ ...d, ...updated.data, addr: { ...d.addr, ...updated.data.addr } }));
    }
    window.addEventListener('bevri:fields-autofilled', onAutoFill);
    return () => window.removeEventListener('bevri:fields-autofilled', onAutoFill);
  }, []);

  const set = patch => setData(d => ({ ...d, ...patch }));
  const flowTop = () => { const el = document.querySelector('.flow'); if (el) el.scrollTop = 0; };

  // ZIP-first autofill for the refinanced property's address. Functional
  // updater reads the live draft so an in-flight lookup never clobbers a
  // typed value; a re-fill only replaces our own previous fill.
  const zipFillRef = React.useRef({ city: '', state: '' });
  const applyZipFill = hit => setData(d => {
    const a = d.addr;
    const patch = {};
    if (!String(a.city || '').trim() || a.city === zipFillRef.current.city) { patch.city = hit.city; zipFillRef.current.city = hit.city; }
    if (!a.state || a.state === zipFillRef.current.state) { patch.state = hit.state; zipFillRef.current.state = hit.state; }
    return Object.keys(patch).length ? { ...d, addr: { ...a, ...patch } } : d;
  });
  function goTo(key) { setData(d => ({ ...d, touched: false })); setStep(key); flowTop(); }

  // Consent is normally collected by the AgreementsGate before Borrower Info
  // (borrower-first order); the in-flow step remains only for legacy drafts
  // that predate the gate and is skipped once consent exists.
  const rfAgreed = d => Boolean(d.agree && d.agree.electronic && d.agree.privacy && d.agree.origination);

  function next() {
    if (editReturn) { setEditReturn(false); return goTo('review'); }
    const i = RF_STEPS.indexOf(step);
    let n = RF_STEPS[i + 1];
    if (n === 'agreements' && rfAgreed(data)) n = RF_STEPS[i + 2];
    goTo(n);
  }
  function back() {
    if (editReturn) { setEditReturn(false); return goTo('review'); }
    if (step === 'refi-goal') return onExit();
    const i = RF_STEPS.indexOf(step);
    let p = RF_STEPS[i - 1];
    if (p === 'agreements' && rfAgreed(data)) p = RF_STEPS[i - 2];
    goTo(p);
  }
  function edit(key) { setEditReturn(true); goTo(key); }

  // progress (reported up to the shell rail) — whole refinance is the "loan" stage
  const RF_POST = ['app-start', 'main-goal', 'current-use', 'address', 'value', 'future-use', 'type', 'review', 'property-info'];
  const pi = RF_POST.indexOf(step);
  const fill = pi >= 0 ? Math.round((pi / (RF_POST.length - 1)) * 100) : 0;
  useRFE(() => { onProgress && onProgress({ fill, stepTitle: step }); }, [step, fill]);
  const nextLabel = editReturn ? 'Save changes' : 'Next';

  let body = null;

  /* ---- Page 1: Initial Refinance Goal ---- */
  if (step === 'refi-goal') {
    body = <>
      <StepHead title="What is the primary goal for the refinance?"
        sub="This helps us tailor the right options before we review your information." />
      <div className="opt-list">
        <Opt icon={I.invest(22)} title="Lower My Rate" sub="I want to see if I can lower my interest rate."
          selected={data.initGoal === 'lower-rate'} onClick={() => set({ initGoal: 'lower-rate' })} />
        <Opt icon={I.refresh(22)} title="Change My Loan Term" sub="I want to shorten or adjust the length of my mortgage."
          selected={data.initGoal === 'change-term'} onClick={() => set({ initGoal: 'change-term' })} />
        <Opt icon={I.cash(22)} title="Take Cash Out" sub="I want to access some of my home's equity."
          selected={data.initGoal === 'cash-out'} onClick={() => set({ initGoal: 'cash-out' })} />
      </div>
      <NavFooter onBack={back} onNext={next} nextLabel={nextLabel} nextDisabled={!data.initGoal} />
    </>;
  }

  /* ---- Page 3: Agreements ---- */
  else if (step === 'agreements') {
    const a = data.agree;
    const all = a.electronic && a.privacy && a.origination;
    const tgl = k => setData(d => ({ ...d, agree: { ...d.agree, [k]: !d.agree[k] } }));
    body = <>
      <StepHead title="Let's get started"
        sub="Please review and agree to the following before we continue. Tap a title to read the full document." />
      <div className="sum-card">
        <div className="agree-list">
          <CheckRow checked={a.electronic} onToggle={() => tgl('electronic')}>
            I have read and agree to the <a className="agree-link" href="/terms" target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()}>Electronic Communication Agreement</a>.
          </CheckRow>
          <CheckRow checked={a.privacy} onToggle={() => tgl('privacy')}>
            I have read and agree to Bevri's <a className="agree-link" href="/privacy" target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()}>Privacy Policy</a>.
          </CheckRow>
          <CheckRow checked={a.origination} onToggle={() => tgl('origination')}>
            I have read and agree to Bevri's <a className="agree-link" href="/terms" target="_blank" rel="noopener noreferrer" onClick={e => e.stopPropagation()}>Mortgage Loan Origination Agreement</a>.
          </CheckRow>
        </div>
      </div>
      <NavFooter onBack={back} onNext={next} nextLabel="Confirm and Continue" nextDisabled={!all} />
    </>;
  }

  /* ---- Page 2: Refinance Application Start ---- */
  else if (step === 'app-start') {
    body = <>
      <div className="start-card">
        <div className="start-burst">{I.checkDark(34)}</div>
        <h1 className="step-title" style={{ fontSize: 28 }}>Your refinance application is off to a great start</h1>
        <p className="step-sub" style={{ marginTop: 14 }}>
          Please continue providing the refinance details so we can further evaluate your loan options.
        </p>
        <button className="start-cta" onClick={next}>
          <span className="opt-icon">{I.refresh(24)}</span>
          <span className="start-cta-text">
            <span className="start-cta-title">Add Refinance Details</span>
            <span className="start-cta-sub">About 2 minutes · 6 quick questions</span>
          </span>
          <span style={{ color: 'var(--sage)' }}>{I.arrow(18)}</span>
        </button>
      </div>
      <div className="step-nav">
        <button className="btn btn-secondary btn-block" onClick={back}>{I.back(16)}Back</button>
      </div>
    </>;
  }

  /* ---- Page 5: Main Refinance Goal (+ conditional cash-out) ---- */
  else if (step === 'main-goal') {
    const t = data.touched;
    const isCash = data.mainGoal === 'cash-out';
    const errCash = t && isCash && !rfNum(data.cashOut) ? 'Enter a cash-out amount' : '';
    const valid = data.mainGoal && (!isCash || rfNum(data.cashOut) > 0);
    const onNext = () => { if (!valid) { set({ touched: true }); return; } next(); };
    body = <>
      <StepHead title="What is the main goal for your refinance?"
        sub="This confirms your main objective so we can match the right loan options." />
      <div className="opt-list">
        <Opt icon={I.invest(22)} title="Reduce My Monthly Payment" sub="I want to try to lower my monthly mortgage payment."
          selected={data.mainGoal === 'reduce-payment'} onClick={() => set({ mainGoal: 'reduce-payment' })} />
        <Opt icon={I.rocket(22)} title="Reduce My Mortgage Term" sub="I want to pay off my mortgage faster or shorten my loan term."
          selected={data.mainGoal === 'reduce-term'} onClick={() => set({ mainGoal: 'reduce-term' })} />
        <Opt icon={I.cash(22)} title="Take Cash Out" sub="I want to access equity from my home."
          selected={isCash} onClick={() => set({ mainGoal: 'cash-out' })} />
      </div>
      {isCash && (
        <div style={{ marginTop: 20 }} className="step">
          <Field label="How much cash out are you looking for?" prefix="$" inputMode="numeric"
            value={data.cashOut} onChange={v => set({ cashOut: rfMoney(v) })} placeholder="50,000" error={errCash} />
        </div>
      )}
      <NavFooter onBack={back} onNext={onNext} nextLabel={nextLabel} nextDisabled={!data.mainGoal} />
    </>;
  }

  /* ---- Page 6: Current Property Use ---- */
  else if (step === 'current-use') {
    body = <>
      <StepHead title="How do you currently use your property?" />
      <div className="opt-list">
        <Opt icon={I.home(24)} title="Primary Residence" sub="A home you currently live in most of the year."
          selected={data.currentUse === 'primary'} onClick={() => set({ currentUse: 'primary' })} />
        <Opt icon={I.building(22)} title="Second Home" sub="A home you use personally, but not as your main residence."
          selected={data.currentUse === 'second'} onClick={() => set({ currentUse: 'second' })} />
        <Opt icon={I.invest(22)} title="Investment Property" sub="A property you rent out or use to generate income."
          selected={data.currentUse === 'investment'} onClick={() => set({ currentUse: 'investment' })} />
      </div>
      <Helper items={[
        { t: 'Primary residence', d: 'This is your main home, where you live most of the year.' },
        { t: 'Second home', d: 'You use it personally (like a vacation home), but live somewhere else most of the year.' },
        { t: 'Investment property', d: 'You rent it out or use it to generate income.' },
      ]} />
      <NavFooter onBack={back} onNext={next} nextLabel={nextLabel} nextDisabled={!data.currentUse} />
    </>;
  }

  /* ---- Page 7: Property Address ---- */
  else if (step === 'address') {
    const ad = data.addr;
    const setA = patch => set({ addr: { ...ad, ...patch } });
    const t = data.touched;
    const errStreet = t && !ad.street.trim() ? 'Required' : '';
    const errCity = t && !ad.city.trim() ? 'Required' : '';
    const errState = t && !ad.state.trim() ? 'Required' : '';
    const errZip = t && !/^\d{5}$/.test(rfDigits(ad.zip)) ? 'Enter a 5-digit ZIP' : '';
    const valid = ad.street.trim() && ad.city.trim() && ad.state.trim() && /^\d{5}$/.test(rfDigits(ad.zip));
    const onNext = () => { if (!valid) { set({ touched: true }); return; } next(); };
    body = <>
      <StepHead title="What is the address of the property you're refinancing?"
        sub="This is the property tied to the loan you'd like to refinance." />
      <Field label="Street address" value={ad.street} onChange={v => setA({ street: v })} placeholder="123 Main Street" error={errStreet} />
      <Field label="Apartment / unit number" optional value={ad.unit} onChange={v => setA({ unit: v })} placeholder="Unit 4B" />
      <ZipField value={ad.zip} onChange={v => setA({ zip: rfDigits(v).slice(0, 5) })} onFill={applyZipFill} error={errZip} />
      <div className="field-row">
        <Field label="City" value={ad.city} onChange={v => setA({ city: v })} placeholder="San Mateo" error={errCity} />
        <Field label="State" value={ad.state} onChange={v => setA({ state: v.toUpperCase().slice(0, 2) })} placeholder="CA" error={errState} />
      </div>
      <NavFooter onBack={back} onNext={onNext} nextLabel={nextLabel} />
    </>;
  }

  /* ---- Page 8: Estimated Property Value ---- */
  else if (step === 'value') {
    const t = data.touched;
    const errVal = t && !rfNum(data.value) ? 'Enter an estimated property value' : '';
    const errBalance = t && !rfNum(data.currentBalance) ? 'Enter your current mortgage balance' : '';
    const valid = rfNum(data.value) > 0 && rfNum(data.currentBalance) > 0;
    const onNext = () => { if (!valid) { set({ touched: true }); return; } next(); };
    body = <>
      <StepHead title="What is the estimated value and current mortgage balance?"
        sub="These numbers let us calculate refinance loan amount, equity, and LTV. Estimates are fine for now." />
      <Field label="Estimated property value" prefix="$" inputMode="numeric"
        value={data.value} onChange={v => set({ value: rfMoney(v) })} placeholder="400,000" error={errVal} />
      <Field label="Current mortgage balance" prefix="$" inputMode="numeric"
        value={data.currentBalance} onChange={v => set({ currentBalance: rfMoney(v) })} placeholder="300,000" error={errBalance} />
      <Field label="Current monthly mortgage payment" optional prefix="$" inputMode="numeric"
        value={data.currentPayment} onChange={v => set({ currentPayment: rfMoney(v) })} placeholder="2,200" />
      <div className="field-row">
        <Field label="Current interest rate" optional suffix="%" inputMode="decimal" value={data.currentRate} onChange={v => set({ currentRate: v.replace(/[^\d.]/g, '').slice(0, 5) })} placeholder="6.75" />
        <Field label="Current servicer/lender" optional value={data.currentServicer} onChange={v => set({ currentServicer: v })} placeholder="Servicer name" />
      </div>
      <div style={{ marginTop: 6 }}>
        <HelpLink q="How do I estimate my property's value?"
          a="Use a recent appraisal, a trusted home-value estimate, or comparable nearby sales. Your best estimate is fine for now. We'll confirm the value later in the process." />
      </div>
      <NavFooter onBack={back} onNext={onNext} nextLabel={nextLabel} />
    </>;
  }

  /* ---- Page 9: Future Property Use ---- */
  else if (step === 'future-use') {
    body = <>
      <StepHead title="How will you use this property after refinancing?" />
      <div className="opt-list">
        <Opt icon={I.home(24)} title="Primary Residence" sub="A home you plan to live in most of the year."
          selected={data.futureUse === 'primary'} onClick={() => set({ futureUse: 'primary' })} />
        <Opt icon={I.building(22)} title="Second Home" sub="A home you plan to use personally, but not as your main residence."
          selected={data.futureUse === 'second'} onClick={() => set({ futureUse: 'second' })} />
        <Opt icon={I.invest(22)} title="Investment Property" sub="A property you plan to rent out or use to generate income."
          selected={data.futureUse === 'investment'} onClick={() => set({ futureUse: 'investment' })} />
      </div>
      <Helper items={[
        { t: 'Primary residence', d: 'This will be your main home, where you live most of the year.' },
        { t: 'Second home', d: "You'll use it personally, but live somewhere else most of the year." },
        { t: 'Investment property', d: 'You intend to rent it out or use it to generate income.' },
      ]} />
      <NavFooter onBack={back} onNext={next} nextLabel={nextLabel} nextDisabled={!data.futureUse} />
    </>;
  }

  /* ---- Page 10: Property Type ---- */
  else if (step === 'type') {
    body = <>
      <StepHead title="What type of property is it?" />
      <div className="opt-list">
        <Opt icon={I.home(24)} title="Single-Family Home" selected={data.ptype === 'single'} onClick={() => set({ ptype: 'single' })} />
        <Opt icon={I.condo(22)} title="Condo" selected={data.ptype === 'condo'} onClick={() => set({ ptype: 'condo' })} />
        <Opt icon={I.units(22)} title="Multi-Family Home" sub="2 to 4 units" selected={data.ptype === 'multi'} onClick={() => set({ ptype: 'multi' })} />
        <Opt icon={I.factory(22)} title="Manufactured Home" selected={data.ptype === 'manufactured'} onClick={() => set({ ptype: 'manufactured' })} />
        <Opt icon={I.coop(22)} title="Co-op" selected={data.ptype === 'coop'} onClick={() => set({ ptype: 'coop' })} />
      </div>
      <Helper items={[
        { t: 'Single-family home', d: 'A standalone home for one household.' },
        { t: 'Condo', d: 'A unit in a building or community where some areas may be shared.' },
        { t: 'Multi-family home', d: 'A property with 2 to 4 separate living units.' },
        { t: 'Manufactured home', d: 'A factory-built home placed on land or in a community.' },
        { t: 'Co-op', d: 'You own shares in a building or association rather than owning the unit directly.' },
      ]} />
      <NavFooter onBack={back} onNext={next} nextLabel={nextLabel} nextDisabled={!data.ptype} />
    </>;
  }

  /* ---- Page 11: Refinance Details Review ---- */
  else if (step === 'review') {
    const ad = data.addr;
    const addrVal = `${ad.street}${ad.unit ? ', ' + ad.unit : ''}\n${[ad.city, ad.state].filter(Boolean).join(', ')} ${ad.zip}`;
    const goalVal = data.mainGoal === 'cash-out'
      ? `Take Cash Out\nRequested: $${data.cashOut || '0'}`
      : (RF_MAINGOAL[data.mainGoal] || '—');
    const sections = [
      { key: 'main-goal', label: 'Primary Refinance Goal', q: 'What is the primary goal for your refinance?', value: goalVal },
      { key: 'current-use', label: 'Current Property Use', q: 'How do you currently use the property?', value: RF_USE[data.currentUse] || '—' },
      { key: 'address', label: 'Property Address', q: 'What is the address of your property?', value: addrVal },
      { key: 'value', label: 'Estimated Value & Mortgage', q: 'Property value and current mortgage', value: `$${data.value || '0'} value\n$${data.currentBalance || '0'} current balance${data.currentPayment ? `\n$${data.currentPayment}/mo current payment` : ''}${data.currentRate ? `\n${data.currentRate}% current rate` : ''}` },
      { key: 'future-use', label: 'Future Property Use', q: 'How will you use this property after refinancing?', value: RF_USE[data.futureUse] || '—' },
      { key: 'type', label: 'Property Type', q: 'What type of property is it?', value: RF_PTYPE[data.ptype] || '—' },
    ];
    body = <>
      <StepHead title="Review your refinance details"
        sub="Make sure everything looks right. You can edit any answer before we continue." />
      <div className="summary">
        {sections.map(s => (
          <div className="sum-card" key={s.key}>
            <div className="sum-head">
              <div style={{ flex: 1 }}>
                <div className="sum-label">{s.label}</div>
                <div className="sum-q">{s.q}</div>
                <div className="sum-value" style={{ whiteSpace: 'pre-line' }}>{s.value}</div>
              </div>
              <button className="sum-edit" onClick={() => edit(s.key)}>{I.pencil(13)}Edit</button>
            </div>
          </div>
        ))}
      </div>
      <NavFooter onBack={back} onNext={next} nextLabel="Confirm and Continue" />
    </>;
  }

  /* ---- Page 12: Subject Property Information ---- */
  else if (step === 'property-info') {
    const t = data.touched;
    const setHoa = on => set({ noHoa: on, hoa: on ? '' : data.hoa });
    body = <>
      <StepHead title="Enter your property information"
        sub="Tell us about your property taxes, homeowners insurance, and HOA dues." />
      <div className="sum-card" style={{ marginBottom: 18, padding: '6px 18px' }}>
        <CheckRow checked={data.taxIncluded} onToggle={() => set({ taxIncluded: !data.taxIncluded })}>
          My taxes and insurance are included in my mortgage payment.
        </CheckRow>
      </div>
      <Field label="Estimated annual property taxes" prefix="$" inputMode="numeric"
        value={data.taxes} onChange={v => set({ taxes: rfMoney(v) })} placeholder="5,000" />
      <Field label="Estimated annual homeowners insurance" prefix="$" inputMode="numeric"
        value={data.insurance} onChange={v => set({ insurance: rfMoney(v) })} placeholder="1,500" />
      <Field label="Monthly HOA dues" prefix="$" inputMode="numeric"
        value={data.noHoa ? '0' : data.hoa} onChange={v => set({ hoa: rfMoney(v) })} placeholder="250" />
      <CheckRow checked={data.noHoa} onToggle={() => setHoa(!data.noHoa)}>
        This property does not have HOA dues.
      </CheckRow>
      <p className="step-sub" style={{ fontSize: 13.5, marginTop: 16 }}>
        If you're not sure of the exact amounts, enter your best estimate. You can update these later.
      </p>
      <NavFooter onBack={back}
        onNext={() => onContinue && onContinue()}
        nextLabel="Next" />
    </>;
  }

  const rfQSteps = ['main-goal', 'current-use', 'address', 'value', 'future-use', 'type'];
  const rfQIdx = rfQSteps.indexOf(step);

  return (
    <main className="flow">
      <div className="flow-col">
        <div className="step" key={step}>
          {rfQIdx >= 0 && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
              <div style={{ flex: 1, height: 3, borderRadius: 2, background: 'var(--line)' }}>
                <div style={{ height: '100%', borderRadius: 2, background: 'var(--sage)', width: `${(rfQIdx / (rfQSteps.length - 1)) * 100}%`, transition: 'width .35s' }} />
              </div>
              <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.06em', color: 'var(--muted)', whiteSpace: 'nowrap', fontFamily: 'monospace' }}>
                {rfQIdx + 1} / {rfQSteps.length}
              </span>
            </div>
          )}
          <div className="step-anim" key={step}>{body}</div>
        </div>
      </div>
    </main>
  );
}

window.RefinanceFlow = RefinanceFlow;
