// ─────────────────────────────────────────────────────────────
// Section 3 - Income & Cashflow
// ─────────────────────────────────────────────────────────────

function SectionIncome({ data, set }) {
  const d = data.income || {};
  // Functional setState so multiple updates in a single handler can't race
  // (same pattern as SectionPersonal / SectionAssets).
  const update = (patch) => set(prev => {
    const prevIncome = prev.income || {};
    return { ...prev, income: { ...prevIncome, ...patch } };
  });

  // Partner-income card only shows when the client has confirmed they're
  // getting advice as a couple. (Mirrors the partner-tab gate in Personal.)
  const primary = data?.personal?.primary || {};
  const partnerP = data?.personal?.partner || {};
  const isCouple = ['Married','De facto'].includes(primary.relStatus);
  const showPartnerIncome = isCouple && primary.coupleAdvice === true;
  // First names for card titles (client asked for names, not "primary"/"partner").
  const primaryFirst = (primary.preferredName || primary.firstName || '').trim();
  const partnerFirst = (partnerP.preferredName || partnerP.firstName || '').trim();

  // Investment-property flag - if the client added any property with use
  // "Investment" in Assets, rental income becomes mandatory here.
  const hasInvestmentProperty = (data?.assets?.properties || [])
    .some(p => p && p.use === 'Investment');

  // Renting flag - if the client picked "Renting" in Personal (Living
  // situation), monthly rent is mandatory here. We surface it as a
  // standalone field at the top of the section because the itemised
  // exRent below is hidden when expense mode is Quick / Surplus, and
  // we still need the number.
  const isRenting = primary.living === 'Renting';

  // Expense mode: 'quick' | 'surplus' | 'detail'. Default to 'quick' so
  // historical drafts (which only knew about 'quick'/'detail') don't lose
  // their bucket choice.
  const expMode = d.expMode === 'detail' ? 'detail'
                : d.expMode === 'surplus' ? 'surplus'
                : d.expMode === 'unknown' ? 'unknown'
                : 'quick';

  const FREQ_OPTS = ['Weekly','Fortnightly','Monthly','Quarterly','Annual'];

  return (
    <div className="section-body">
      {/* Standalone rent question - only shown for renters (per their
          Personal-section answer). Renders ABOVE the employment card
          so it's the first thing they see when they hit this section,
          and isn't hidden inside the Quick/Surplus expense modes. */}
      {isRenting && (
        <div className="card">
          <div className="card-title">Your rent</div>
          <Field label="How much do you pay in rent? ($ per month)" required name="i.rentMonthly"
            hint="You told us you're renting in the Personal section - this helps us model your cashflow accurately.">
            <MoneyInput value={d.rentMonthly || ''}
              onChange={e => update({ rentMonthly: e.target.value })}
              placeholder="e.g. 2,400" />
          </Field>
        </div>
      )}

      <div className="card">
        <div className="card-title">{`Employment income - ${primaryFirst || 'primary'}`}</div>
        <Field label="Employer name" hint="Pulled from your Personal details - update it there if it's changed.">
          <Input value={primary.employer || ''} readOnly disabled
            placeholder="Add your employer in the Personal section" />
        </Field>
        <div className="grid-2">
          <Field label="What do you earn annually from your primary income (Base salary per annum)" required name="i.baseSalary">
            <MoneyInput value={d.baseSalary || ''} onChange={e => update({ baseSalary: e.target.value })} />
          </Field>
          <Field label="On what frequency are you paid" required name="i.payFreq">
            <Select value={d.payFreq || ''} onChange={e => update({ payFreq: e.target.value })}>
              <option value="">Select…</option>
              <option>Weekly</option><option>Fortnightly</option><option>Monthly</option>
            </Select>
          </Field>
          <Field label="Net take home per period ($)">
            <MoneyInput value={d.netPay || ''} onChange={e => update({ netPay: e.target.value })} />
          </Field>
          <Field label="Super guarantee rate" required name="i.sgRate"
            hint="Default = the legislated rate your employer is required to pay. Pick Other only if you've negotiated a higher rate (e.g. EBA-uplifted, salary-packaged, public-service top-up).">
            <Select value={d.sgRate || ''} onChange={e => update({ sgRate: e.target.value, sgRateOther: e.target.value === 'Other' ? (d.sgRateOther || '') : '' })}>
              <option value="">Select…</option>
              <option>Default</option><option>Other</option>
            </Select>
            {d.sgRate === 'Other' && (
              <Field label="Specify SG rate" required name="i.sgRateOther">
                <Input value={d.sgRateOther || ''}
                  onChange={e => update({ sgRateOther: e.target.value })}
                  placeholder="Specify rate - e.g. 15%" />
              </Field>
            )}
          </Field>
        </div>

        <hr className="divider" />
        <div className="grid-2">
          <Field label="Overtime / allowances ($ p.a.)">
            <MoneyInput value={d.overtime || ''} onChange={e => update({ overtime: e.target.value })} />
          </Field>
          <Field label="Bonus / commission ($ typical)">
            <MoneyInput value={d.bonus || ''} onChange={e => update({ bonus: e.target.value })} />
          </Field>
          {Number(String(d.bonus || '').replace(/[^0-9.]/g, '')) > 0 && (
            <Field label="How likely is this bonus on an annual basis?" required span={2} name="i.bonusLikelihood"
              hint="Roughly how reliable is this bonus year to year? e.g. guaranteed, very likely, varies with performance, one-off.">
              <Textarea rows={2} value={d.bonusLikelihood || ''} onChange={e => update({ bonusLikelihood: e.target.value })}
                placeholder="e.g. Paid every year for the last 5 years, typically 10-15% of salary." />
            </Field>
          )}
          <Field label="Do you have any salary packaging such as Novated leasing?" required name="i.salPkgYn"
            hint="Novated lease, meal entertainment card, FBT-exempt benefits, etc.">
            <YesNo value={d.salPkgYn}
              onChange={v => update({ salPkgYn: v, ...(v === false ? { salPkg: '' } : {}) })} />
          </Field>
          {d.salPkgYn === true && (
            <Field label="Please describe your salary packaging" required name="i.salPkg" span={2}>
              <Textarea rows={2} value={d.salPkg || ''} onChange={e => update({ salPkg: e.target.value })}
                placeholder="e.g. $15,900 FBT-exempt + $2,650 meal/entertainment + novated lease on a 2024 Toyota RAV4" />
            </Field>
          )}
          <Field label="Car allowance ($ p.a.)">
            <MoneyInput value={d.carAllow || ''} onChange={e => update({ carAllow: e.target.value })} />
          </Field>
          <Field label="How much sick leave do you have?" required name="i.sickLeave"
            hint="Your current sick / personal leave balance.">
            <Input value={d.sickLeave || ''} onChange={e => update({ sickLeave: e.target.value })}
              placeholder="e.g. 10 days, 76 hours" />
          </Field>
          <Field label="How much annual leave do you have?" required name="i.annualLeave"
            hint="Your current annual / holiday leave balance.">
            <Input value={d.annualLeave || ''} onChange={e => update({ annualLeave: e.target.value })}
              placeholder="e.g. 20 days, 4 weeks" />
          </Field>
        </div>

        <hr className="divider" />
        <Field label="Do you have a secondary income?" required name="i.secondaryYn"
          hint="A second job, business, or other regular employment income - separate from your primary income above.">
          <YesNo value={d.secondaryYn}
            onChange={v => update({ secondaryYn: v, ...(v === false ? { secondaryIncome: '', secondaryHow: '' } : {}) })} />
        </Field>
        {d.secondaryYn === true && (
          <div className="grid-2">
            <Field label="What do you earn annually from your secondary income (Base salary per annum)" required name="i.secondaryIncome">
              <MoneyInput value={d.secondaryIncome || ''} onChange={e => update({ secondaryIncome: e.target.value })} />
            </Field>
            <Field label="How is this income earned?" required span={2} name="i.secondaryHow"
              hint="Briefly describe the source - e.g. second job as a barista, freelance design, rental of a room, small side business.">
              <Textarea rows={2} value={d.secondaryHow || ''} onChange={e => update({ secondaryHow: e.target.value })} />
            </Field>
          </div>
        )}
      </div>

      <div className="card">
        <div className="card-title">Private health</div>
        <Field label="Do you have private hospital cover?" required name="i.privateHealth"
          hint="Private hospital cover affects the Medicare Levy Surcharge and your tax position.">
          <YesNo value={d.privateHealth} onChange={v => update({ privateHealth: v })} />
        </Field>
        {showPartnerIncome && (
          <Field label={partnerFirst ? `Does ${partnerFirst} have private hospital cover?` : 'Does your partner have private hospital cover?'}
            required name="i.pPrivateHealth"
            hint="Private hospital cover is assessed per person for the Medicare Levy Surcharge.">
            <YesNo value={d.pPrivateHealth} onChange={v => update({ pPrivateHealth: v })} />
          </Field>
        )}
      </div>

      {showPartnerIncome && (
        <div className="card">
          <div className="card-title">{`Employment income - ${partnerFirst || 'partner'}`}</div>
          {/* Homemaker opt-out. Lets the client skip the four required
              partner-employment fields when the partner isn't in paid
              work. Validator reads `d.partnerHomemaker` to drop those
              required entries. */}
          <label className="invite-toggle" style={{ marginBottom: 14 }}>
            <input type="checkbox" checked={d.partnerHomemaker === true}
              onChange={e => update({
                partnerHomemaker: e.target.checked,
                // Clear the fields if they tick - so we don't carry stale
                // numbers into the submission. Untick to re-enter.
                ...(e.target.checked ? { pBase: '', pFreq: '', pNet: '', pSg: '', pSgOther: '', pOvertime: '', pBonus: '', pBonusLikelihood: '', pSalPkgYn: null, pSalPkg: '', pCarAllow: '', pSecondaryYn: null, pSecondaryIncome: '', pSecondaryHow: '' } : {}),
              })} />
            <span>My partner is a homemaker.</span>
            <span className="invite-toggle-hint">Tick this box if your partner isn't in paid work - we'll skip the employment income fields below.</span>
          </label>
          {!d.partnerHomemaker && (
            <>
            <Field label="Employer name" hint="Pulled from the Personal section - update it there if it's changed.">
              <Input value={partnerP.employer || ''} readOnly disabled
                placeholder="Add your partner's employer in the Personal section" />
            </Field>
            <div className="grid-2">
              <Field label="Base salary ($ gross p.a.)" required name="i.pBase">
                <MoneyInput value={d.pBase || ''} onChange={e => update({ pBase: e.target.value })} />
              </Field>
              <Field label="Pay frequency" required name="i.pFreq">
                <Select value={d.pFreq || ''} onChange={e => update({ pFreq: e.target.value })}>
                  <option value="">Select…</option>
                  <option>Weekly</option><option>Fortnightly</option><option>Monthly</option>
                </Select>
              </Field>
              <Field label="Net take home per period ($)">
                <MoneyInput value={d.pNet || ''} onChange={e => update({ pNet: e.target.value })} />
              </Field>
              <Field label="SG rate" required name="i.pSg"
                hint="Default = the legislated SG rate. Pick Other only if your partner's been negotiated a higher rate.">
                <Select value={d.pSg || ''} onChange={e => update({ pSg: e.target.value, pSgOther: e.target.value === 'Other' ? (d.pSgOther || '') : '' })}>
                  <option value="">Select…</option>
                  <option>Default</option><option>Other</option>
                </Select>
                {d.pSg === 'Other' && (
                  <Field label="Specify partner SG rate" required name="i.pSgOther">
                    <Input value={d.pSgOther || ''}
                      onChange={e => update({ pSgOther: e.target.value })}
                      placeholder="Specify rate - e.g. 15%" />
                  </Field>
                )}
              </Field>
              <Field label="Overtime / allowances ($ p.a.)">
                <MoneyInput value={d.pOvertime || ''} onChange={e => update({ pOvertime: e.target.value })} />
              </Field>
              <Field label="Bonus / commission ($ typical)">
                <MoneyInput value={d.pBonus || ''} onChange={e => update({ pBonus: e.target.value })} />
              </Field>
              {Number(String(d.pBonus || '').replace(/[^0-9.]/g, '')) > 0 && (
                <Field label="How likely is this bonus on an annual basis?" required span={2} name="i.pBonusLikelihood"
                  hint="Roughly how reliable is this bonus year to year? e.g. guaranteed, very likely, varies with performance, one-off.">
                  <Textarea rows={2} value={d.pBonusLikelihood || ''} onChange={e => update({ pBonusLikelihood: e.target.value })}
                    placeholder="e.g. Paid every year, typically 10-15% of salary." />
                </Field>
              )}
              <Field label="Does your partner have any salary packaging such as novated leasing?" required name="i.pSalPkgYn"
                hint="Novated lease, meal entertainment card, FBT-exempt benefits, etc.">
                <YesNo value={d.pSalPkgYn}
                  onChange={v => update({ pSalPkgYn: v, ...(v === false ? { pSalPkg: '' } : {}) })} />
              </Field>
              {d.pSalPkgYn === true && (
                <Field label="Please describe the salary packaging" required name="i.pSalPkg" span={2}>
                  <Textarea rows={2} value={d.pSalPkg || ''} onChange={e => update({ pSalPkg: e.target.value })}
                    placeholder="e.g. $15,900 FBT-exempt + novated lease" />
                </Field>
              )}
              <Field label="Car allowance ($ p.a.)">
                <MoneyInput value={d.pCarAllow || ''} onChange={e => update({ pCarAllow: e.target.value })} />
              </Field>
              <Field label="How much sick leave does your partner have?" required name="i.pSickLeave"
                hint="Their current sick / personal leave balance.">
                <Input value={d.pSickLeave || ''} onChange={e => update({ pSickLeave: e.target.value })}
                  placeholder="e.g. 10 days, 76 hours" />
              </Field>
              <Field label="How much annual leave does your partner have?" required name="i.pAnnualLeave"
                hint="Their current annual / holiday leave balance.">
                <Input value={d.pAnnualLeave || ''} onChange={e => update({ pAnnualLeave: e.target.value })}
                  placeholder="e.g. 20 days, 4 weeks" />
              </Field>
            </div>
            <hr className="divider" />
            <Field label="Does your partner have a secondary income?" required name="i.pSecondaryYn"
              hint="A second job, business, or other regular employment income - separate from the primary income above.">
              <YesNo value={d.pSecondaryYn}
                onChange={v => update({ pSecondaryYn: v, ...(v === false ? { pSecondaryIncome: '', pSecondaryHow: '' } : {}) })} />
            </Field>
            {d.pSecondaryYn === true && (
              <div className="grid-2">
                <Field label="What does your partner earn annually from their secondary income (Base salary per annum)" required name="i.pSecondaryIncome">
                  <MoneyInput value={d.pSecondaryIncome || ''} onChange={e => update({ pSecondaryIncome: e.target.value })} />
                </Field>
                <Field label="How is this income earned?" required span={2} name="i.pSecondaryHow"
                  hint="Briefly describe the source - e.g. second job, freelance work, rental of a room, small side business.">
                  <Textarea rows={2} value={d.pSecondaryHow || ''} onChange={e => update({ pSecondaryHow: e.target.value })} />
                </Field>
              </div>
            )}
            </>
          )}
        </div>
      )}

      <div className="card">
        <div className="card-title">Investment & other income</div>
        <div className="grid-2">
          <Field label="Rental income ($ gross p.a.)"
            required={hasInvestmentProperty}
            name={hasInvestmentProperty ? 'i.rental' : undefined}
            hint={hasInvestmentProperty
              ? 'Required - you flagged at least one investment property in the Assets section.'
              : null}>
            <MoneyInput value={d.rental || ''} onChange={e => update({ rental: e.target.value })} />
          </Field>
          <Field label="Dividends ($ p.a.)">
            <MoneyInput value={d.dividends || ''} onChange={e => update({ dividends: e.target.value })} />
          </Field>
          <Field label="Trust distributions ($ p.a.)">
            <MoneyInput value={d.trustDist || ''} onChange={e => update({ trustDist: e.target.value })} />
          </Field>
          <Field label="Foreign income ($ p.a.)">
            <MoneyInput value={d.foreign || ''} onChange={e => update({ foreign: e.target.value })} />
          </Field>
          <Field label="Government / Centrelink ($ p.a.)">
            <MoneyInput value={d.gov || ''} onChange={e => update({ gov: e.target.value })} />
          </Field>
          <Field label="Child support received ($ p.a.)">
            <MoneyInput value={d.childSupport || ''} onChange={e => update({ childSupport: e.target.value })} />
          </Field>
          <Field label="Other - describe" span={2}>
            <Input value={d.otherDesc || ''} onChange={e => update({ otherDesc: e.target.value })}
              placeholder="e.g. side business, royalties" />
          </Field>
        </div>
      </div>

      <div className="card">
        <div className="card-title">Super contributions</div>
        <div className="grid-2">
          <Field label="Voluntary contributions ($ p.a.)">
            <MoneyInput value={d.volContrib || ''} onChange={e => update({ volContrib: e.target.value })} />
          </Field>
          <Field label="Type">
            <Select value={d.contribType || ''} onChange={e => update({ contribType: e.target.value })}>
              <option value="">Select…</option>
              <option>Concessional (pre-tax) / Tax Deductible</option><option>Non-concessional (after-tax)</option><option>Both</option>
            </Select>
          </Field>
          <Field label="Partner contributions ($ p.a.)">
            <MoneyInput value={d.spouseContrib || ''} onChange={e => update({ spouseContrib: e.target.value })} />
          </Field>
        </div>
      </div>

      <div className="card">
        <div className="card-title">How you spend</div>
        <div className="exp-tabs">
          <button type="button" className={cx('exp-tab', expMode === 'quick' && 'on')}
            onClick={() => update({ expMode: 'quick' })}>Quick total</button>
          <button type="button" className={cx('exp-tab', expMode === 'surplus' && 'on')}
            onClick={() => update({ expMode: 'surplus' })}>State my surplus</button>
          <button type="button" className={cx('exp-tab', expMode === 'detail' && 'on')}
            onClick={() => update({ expMode: 'detail' })}>Itemised spending</button>
          <button type="button" className={cx('exp-tab', expMode === 'unknown' && 'on')}
            onClick={() => update({ expMode: 'unknown' })}>I don't know</button>
        </div>

        {expMode === 'quick' && (
          <div className="grid-2" style={{ marginTop: 6 }}>
            <Field label="Total spending ($)" required name="i.quickAmount"
              hint="Your usual total outgoings - pick the frequency that feels natural.">
              <MoneyInput value={d.quickAmount || ''} onChange={e => update({ quickAmount: e.target.value })} />
            </Field>
            <Field label="Frequency" required name="i.quickFreq">
              <Select value={d.quickFreq || ''} onChange={e => update({ quickFreq: e.target.value })}>
                <option value="">Select…</option>
                {FREQ_OPTS.map(f => <option key={f}>{f}</option>)}
              </Select>
            </Field>
          </div>
        )}

        {expMode === 'surplus' && (
          <div className="grid-2" style={{ marginTop: 6 }}>
            <Field label="Surplus / leftover after expenses ($)" required name="i.surplusAmount"
              hint="What's typically left over once everything's paid.">
              <MoneyInput value={d.surplusAmount || ''} onChange={e => update({ surplusAmount: e.target.value })} />
            </Field>
            <Field label="Frequency" required name="i.surplusFreq">
              <Select value={d.surplusFreq || ''} onChange={e => update({ surplusFreq: e.target.value })}>
                <option value="">Select…</option>
                {FREQ_OPTS.map(f => <option key={f}>{f}</option>)}
              </Select>
            </Field>
          </div>
        )}

        {expMode === 'detail' && (
          <div className="grid-2" style={{ marginTop: 6 }}>
            {[
              ['Rent / mortgage','exRent'],['Groceries','exGroc'],['Utilities','exUtil'],
              ['Transport','exTrans'],['Insurance premiums','exIns'],['School fees','exSchool'],
              ['Childcare','exChild'],['Entertainment','exEnt'],['Health / medical','exHealth'],
              ['Subscriptions','exSubs'],['Clothing','exCloth'],['Other','exOther'],
            ].map(([lbl, key]) => (
              <Field key={key} label={`${lbl} ($)`}>
                <MoneyInput value={d[key] || ''} onChange={e => update({ [key]: e.target.value })} />
              </Field>
            ))}
          </div>
        )}

        {expMode === 'unknown' && (
          <div style={{ marginTop: 10 }}>
            <p className="goals-sub" style={{ marginBottom: 10 }}>
              No problem. Tick the box below to confirm, and your adviser will help you build a spending picture together.
            </p>
            <label className="invite-toggle">
              <input type="checkbox" checked={d.spendNotTracked === true}
                onChange={e => update({ spendNotTracked: e.target.checked })} />
              <span>I do not currently keep track of our spending.<span className="req">*</span></span>
            </label>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { SectionIncome });
