/* global React, BrainMark, I, StepHead, Field, Select, Opt, CheckRow, NavFooter, Helper */
const { useState: useINC, useEffect: useINCE } = React;

/* ---- constants ---- */
const FREQ_FULL = ['Weekly', 'Bi-Weekly', 'Semi-Monthly', 'Monthly', 'Quarterly', 'Semi-Annually', 'Annually'];
const FREQ_OT = ['Weekly', 'Bi-Weekly', 'Semi-Monthly', 'Monthly', 'Annually'];
const SALARY_FREQ = ['Annually', 'Monthly'];
const RET_FREQ = ['Monthly', 'Annually'];
const STRUCTURE = ['Sole Proprietorship / Single-Member LLC', 'Partnership', 'S-Corporation', 'Corporation'];
const OTHER_TYPES = ['Alimony', 'Automobile Allowance', 'Child Support', 'Disability', 'Foster Care', 'Interest and Dividends', 'Miscellaneous Income', 'Public Assistance', 'Separate Maintenance', 'Trust', 'Tip Income', 'VA Compensation', 'Other'];

const incDigits = s => (s || '').replace(/[^\d]/g, '');
const incMoney = s => { const d = incDigits(s); return d ? Number(d).toLocaleString('en-US') : ''; };
const incNum = s => Number(incDigits(s)) || 0;

const INC_DEFAULT = {
  type: null,
  // employment
  method: null, verified: false,
  employer: '', position: '', startDate: '', prevEmployment: false, military: false,
  payType: '', salaryAmt: '', salaryFreq: 'Annually', hourlyRate: '', hoursWeek: '',
  overtime: { on: false, amt: '', hours: '', freq: 'Monthly' },
  bonus: { on: false, amt: '', freq: 'Annually' },
  commission: { on: false, amt: '', freq: 'Annually' },
  otherEmp: { on: false, amt: '', freq: 'Monthly', desc: '' },
  relatedParty: null, profYears: '', profMonths: '0',
  // self-employment
  bizName: '', bizStart: '', structure: '', ownership: null, incomeAfterExp: '', incomeFreq: 'Annually',
  // retirement
  retType: '', retAmount: '', retFreq: 'Monthly',
  // other
  otherType: '', monthlyAmt: '', otherDesc: '',
  touched: false,
};

/* income type cards */
const INCOME_TYPES = [
  { value: 'employment', title: 'Employment Income', sub: 'A job, employer, salary, hourly pay, overtime, bonus, or commission.', icon: () => I.building(22) },
  { value: 'self', title: 'Self-Employment Income', sub: 'A business, independent work, ownership, or contract work.', icon: () => I.invest(22) },
  { value: 'retirement', title: 'Retirement Income', sub: 'Social Security, pension, or retirement accounts.', icon: () => I.seedling(22) },
  { value: 'other', title: 'Other Income', sub: 'Support, disability, VA compensation, tips, or public assistance.', icon: () => I.cash(22) },
];

/* ---- summary label for the hub ---- */
function incomeSummary(s) {
  if (s.type === 'employment') {
    const pay = s.payType === 'salary' ? 'Salary' : s.payType === 'hourly' ? 'Hourly' : 'Other';
    return { title: 'Employment Income', detail: `${s.employer || 'Employer'} · ${pay}`, verified: s.verified };
  }
  if (s.type === 'self') return { title: 'Self-Employment Income', detail: `${s.bizName || 'Business'} · ${s.incomeFreq}` };
  if (s.type === 'retirement') return { title: 'Retirement Income', detail: `${s.retType || '—'} · ${s.retFreq}` };
  if (s.type === 'other') return { title: 'Other Income', detail: `${s.otherType || '—'} · Monthly` };
  return { title: 'Income', detail: '' };
}

/* ---- validity per step ---- */
function incValid(step, d) {
  switch (step) {
    case 'type': return !!d.type;
    case 'emp-method': return !!d.method;
    case 'emp-employer': return d.employer.trim() && d.position.trim() && d.startDate;
    case 'emp-details':
      if (!d.payType) return false;
      if (d.payType === 'salary' && !incNum(d.salaryAmt)) return false;
      if (d.payType === 'hourly' && (!incNum(d.hourlyRate) || !incNum(d.hoursWeek))) return false;
      if (d.overtime.on && !incNum(d.overtime.amt)) return false;
      if (d.bonus.on && !incNum(d.bonus.amt)) return false;
      if (d.commission.on && !incNum(d.commission.amt)) return false;
      if (d.otherEmp.on && !incNum(d.otherEmp.amt)) return false;
      return true;
    case 'emp-additional': return d.relatedParty && d.profYears !== '' && d.profMonths !== '';
    case 'self-biz': return d.bizName.trim() && d.bizStart;
    case 'self-duration': return d.profYears !== '' && d.profMonths !== '';
    case 'self-structure': return !!d.structure;
    case 'self-ownership': return !!d.ownership;
    case 'self-income': return incNum(d.incomeAfterExp) > 0;
    case 'ret-details': return d.retType && incNum(d.retAmount) > 0;
    case 'other-type': return !!d.otherType;
    case 'other-amount': return incNum(d.monthlyAmt) > 0 && (d.otherType !== 'Other' || d.otherDesc.trim());
    default: return true;
  }
}

/* ---- step chains per branch (last step = Confirm and Continue) ---- */
function chainFor(d) {
  if (d.type === 'employment') {
    return d.method === 'argyle'
      ? ['type', 'emp-method', 'emp-argyle']
      : ['type', 'emp-method', 'emp-employer', 'emp-details', 'emp-additional'];
  }
  if (d.type === 'self') return ['type', 'self-biz', 'self-duration', 'self-structure', 'self-ownership', 'self-income'];
  if (d.type === 'retirement') return ['type', 'ret-details'];
  if (d.type === 'other') return ['type', 'other-type', 'other-amount'];
  return ['type'];
}

const MONTHS_INC = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'];

/* ===================================================================== */
function IncomeFlow({ borrowerName, initial, onCancel, onSave, onProgress }) {
  const [data, setData] = useINC(initial ? { ...INC_DEFAULT, ...initial, touched: false } : INC_DEFAULT);
  const [step, setStep] = useINC('type');

  const set = patch => setData(d => ({ ...d, ...patch }));
  const setSub = (key, patch) => setData(d => ({ ...d, [key]: { ...d[key], ...patch } }));
  const t = data.touched;
  const who = borrowerName || 'this borrower';
  const whoP = borrowerName ? `${borrowerName}'s` : "this borrower's";

  const flowTop = () => { const el = document.querySelector('.flow'); if (el) el.scrollTop = 0; };
  function goTo(key) { setData(d => ({ ...d, touched: false })); setStep(key); flowTop(); }

  function next() {
    if (!incValid(step, data)) { set({ touched: true }); return; }
    const chain = chainFor(data);
    const i = chain.indexOf(step);
    if (i === chain.length - 1) { onSave({ ...data, id: data.id || Math.random().toString(36).slice(2) }); return; }
    goTo(chain[i + 1]);
  }
  function back() {
    if (step === 'type') return onCancel();
    if (step === 'emp-employer' && data.method === 'argyle') return goTo('emp-method'); // safety
    const chain = chainFor(data);
    const i = chain.indexOf(step);
    if (i <= 0) return goTo('type');
    goTo(chain[i - 1]);
  }

  // progress
  const chain = chainFor(data);
  const di = Math.max(0, chain.indexOf(step));
  const fill = Math.round((di / Math.max(1, chain.length - 1)) * 100);
  useINCE(() => { onProgress && onProgress({ fill, stepTitle: 'inc-' + step }); }, [step, fill]);

  const eyebrow = 'ADD INCOME';
  const isLast = step === chainFor(data)[chainFor(data).length - 1];
  const nextLabel = isLast ? 'Confirm and Continue' : 'Next';

  let body = null;

  /* ---- income type ---- */
  if (step === 'type') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`What type of income does ${who} receive?`} sub="You can add more than one income source for each borrower." />
      <div className="opt-list">
        {INCOME_TYPES.map(o => (
          <Opt key={o.value} icon={o.icon()} title={o.title} sub={o.sub}
            selected={data.type === o.value} onClick={() => set({ type: o.value })} />
        ))}
      </div>
      <NavFooter onBack={back} onNext={next} nextLabel="Next" nextDisabled={!data.type} backLabel="Cancel" />
    </>;
  }

  /* ===== EMPLOYMENT ===== */
  else if (step === 'emp-method') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`How would you like to add ${whoP} employment income?`} />
      <div className="opt-list">
        <button className={'opt opt-feature' + (data.method === 'argyle' ? ' sel' : '')} onClick={() => set({ method: 'argyle' })}>
          <span className="opt-icon">{I.bolt ? I.bolt(22) : I.refresh(22)}</span>
          <span className="opt-main">
            <span className="opt-title">Verify through my payroll provider <span className="opt-badge">Coming soon</span></span>
            <span className="opt-sub">Connected payroll verification is not available yet. Your loan team verifies income with documents after you apply.</span>
          </span>
          <span className="opt-radio">{I.check(13)}</span>
        </button>
        <Opt icon={I.pencil(20)} title="Enter employment income manually" sub="Add employer and income details yourself."
          selected={data.method === 'manual'} onClick={() => set({ method: 'manual' })} />
      </div>
      <NavFooter onBack={back} onNext={next} nextLabel="Next" nextDisabled={!data.method} />
    </>;
  }

  else if (step === 'emp-argyle') {
    // No fake verification: connected payroll verification is not wired yet,
    // so this step is an honest notice that routes into manual entry. It must
    // never save a fabricated employer or set verified without a real vendor.
    body = <>
      <StepHead eyebrow={eyebrow} title="Payroll verification is coming soon" sub="Connected payroll verification is not available on this application yet. Enter your employment income manually and your loan team will verify it with documents after you apply." />
      <div className="argyle-card">
        <div className="argyle-logos">
          <span className="ava"><BrainMark size={26} /></span>
          <span className="argyle-link-dots"><i /><i /><i /></span>
          <span className="argyle-provider">{I.building(24)}</span>
        </div>
        <div className="argyle-trust">{I.lock ? I.lock(15) : null} Nothing is connected or shared without your action. Income you enter is marked as stated until your loan team verifies it.</div>
        <button className="btn btn-primary btn-block" onClick={() => { set({ method: 'manual' }); goTo('emp-employer'); }}>
          Enter income manually
        </button>
      </div>
      <div className="step-nav">
        <button className="btn btn-secondary btn-block" onClick={back}>{I.back(16)}Back</button>
      </div>
    </>;
  }

  else if (step === 'emp-employer') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`Tell us about ${whoP} employer`} />
      <Field label="Business / employer name" value={data.employer} onChange={v => set({ employer: v })} placeholder="Company Name" error={t && !data.employer.trim() ? 'Required' : ''} />
      <Field label="Position or title" value={data.position} onChange={v => set({ position: v })} placeholder="Senior Analyst" error={t && !data.position.trim() ? 'Required' : ''} />
      <Field label="Start date" type="date" value={data.startDate} onChange={v => set({ startDate: v })} error={t && !data.startDate ? 'Required' : ''} />
      <div className="bi-inline-check">
        <CheckRow checked={data.prevEmployment} onToggle={() => set({ prevEmployment: !data.prevEmployment })}>This is previous employment</CheckRow>
      </div>
      <div className="bi-inline-check">
        <CheckRow checked={data.military} onToggle={() => set({ military: !data.military })}>This is military service</CheckRow>
      </div>
      {data.prevEmployment && <p className="bi-helper-text">Heads up: if this is previous employment, you may still need to add a current or more recent income source before finishing.</p>}
      <NavFooter onBack={back} onNext={next} nextLabel="Next" />
    </>;
  }

  else if (step === 'emp-details') {
    const Comp = ({ id, label }) => {
      const c = data[id];
      const freqOpts = id === 'overtime' ? FREQ_OT : FREQ_FULL;
      return (
        <div className={'inc-toggle' + (c.on ? ' on' : '')}>
          <CheckRow checked={c.on} onToggle={() => setSub(id, { on: !c.on })}>{label}</CheckRow>
          {c.on && <div className="inc-toggle-body">
            <Field label={`${label.replace('Add ', '').replace(' income', '')} amount`.replace(/^\w/, m => m.toUpperCase())} prefix="$" inputMode="numeric"
              value={c.amt} onChange={v => setSub(id, { amt: incMoney(v) })} placeholder="0" error={t && c.on && !incNum(c.amt) ? 'Required' : ''} />
            {id === 'overtime' && <Field label="Overtime hours per week" optional inputMode="numeric" value={c.hours} onChange={v => setSub(id, { hours: incDigits(v).slice(0, 3) })} placeholder="0" />}
            <Select label="How often is this received?" value={c.freq} onChange={v => setSub(id, { freq: v })} options={freqOpts} />
            {id === 'otherEmp' && <Field label="Description" optional value={c.desc} onChange={v => setSub(id, { desc: v })} placeholder="e.g. shift differential" />}
          </div>}
        </div>
      );
    };
    body = <>
      <StepHead eyebrow={eyebrow} title={`Provide details about ${whoP} income`} />
      <p className="bi-q">How is {who} paid?</p>
      <div className="opt-list two-up" style={{ marginBottom: 18 }}>
        <Opt title="Salary" twoUp selected={data.payType === 'salary'} onClick={() => set({ payType: 'salary' })} />
        <Opt title="Hourly" twoUp selected={data.payType === 'hourly'} onClick={() => set({ payType: 'hourly' })} />
        <Opt title="N/A" twoUp selected={data.payType === 'na'} onClick={() => set({ payType: 'na' })} />
      </div>
      {t && !data.payType && <div className="field-err" style={{ marginTop: -8, marginBottom: 12 }}>Please choose how this borrower is paid</div>}

      {data.payType === 'salary' && <div className="step">
        <Field label="Salary amount" prefix="$" inputMode="numeric" value={data.salaryAmt} onChange={v => set({ salaryAmt: incMoney(v) })} placeholder="80,000" error={t && !incNum(data.salaryAmt) ? 'Required' : ''} />
        <Select label="How often is this amount paid?" value={data.salaryFreq} onChange={v => set({ salaryFreq: v })} options={SALARY_FREQ} />
      </div>}
      {data.payType === 'hourly' && <div className="step">
        <Field label="Hourly rate" prefix="$" inputMode="numeric" value={data.hourlyRate} onChange={v => set({ hourlyRate: incMoney(v) })} placeholder="32" error={t && !incNum(data.hourlyRate) ? 'Required' : ''} />
        <Field label="Hours worked per week" inputMode="numeric" value={data.hoursWeek} onChange={v => set({ hoursWeek: incDigits(v).slice(0, 3) })} placeholder="40" error={t && !incNum(data.hoursWeek) ? 'Required' : ''} />
      </div>}

      <p className="bi-q" style={{ marginTop: 8 }}>Add any additional income that applies</p>
      <Comp id="overtime" label="Add overtime income" />
      <Comp id="bonus" label="Add bonus income" />
      <Comp id="commission" label="Add commission income" />
      <Comp id="otherEmp" label="Add other employment income" />
      <NavFooter onBack={back} onNext={next} nextLabel="Next" />
    </>;
  }

  else if (step === 'emp-additional') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`A few more details about ${whoP} employment`} />
      <p className="bi-q">Is this employer a family member or party related to this transaction?</p>
      <p className="bi-helper-text" style={{ marginTop: -4 }}>This could include the property seller, real estate agent, lender, or another party involved in the transaction.</p>
      <div className="bi-yesno">
        <Opt icon={I.yes(20)} title="Yes" twoUp selected={data.relatedParty === 'yes'} onClick={() => set({ relatedParty: 'yes' })} />
        <Opt icon={I.no(18)} title="No" twoUp selected={data.relatedParty === 'no'} onClick={() => set({ relatedParty: 'no' })} />
      </div>
      {t && !data.relatedParty && <div className="field-err" style={{ marginTop: -8, marginBottom: 12 }}>Please select an option</div>}
      <p className="bi-q" style={{ marginTop: 10 }}>How long has {who} been in this profession?</p>
      <div className="field-row">
        <Field label="Years" inputMode="numeric" value={data.profYears} onChange={v => set({ profYears: incDigits(v).slice(0, 2) })} placeholder="0" error={t && data.profYears === '' ? 'Required' : ''} />
        <Select label="Months" value={data.profMonths} onChange={v => set({ profMonths: v })} options={MONTHS_INC} placeholder="0" error={t && data.profMonths === '' ? 'Required' : ''} />
      </div>
      <NavFooter onBack={back} onNext={next} nextLabel="Confirm and Continue" />
    </>;
  }

  /* ===== SELF-EMPLOYMENT ===== */
  else if (step === 'self-biz') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`Tell us about ${whoP} business`} />
      <Field label="Business name" value={data.bizName} onChange={v => set({ bizName: v })} placeholder="Haddad Consulting" error={t && !data.bizName.trim() ? 'Required' : ''} />
      <Field label="Start date" type="date" value={data.bizStart} onChange={v => set({ bizStart: v })} error={t && !data.bizStart ? 'Required' : ''} />
      <div className="bi-inline-check">
        <CheckRow checked={data.prevEmployment} onToggle={() => set({ prevEmployment: !data.prevEmployment })}>This is previous employment</CheckRow>
      </div>
      {data.prevEmployment && <p className="bi-helper-text">Heads up: if this is previous employment, you may still need to add a current or more recent income source.</p>}
      <NavFooter onBack={back} onNext={next} nextLabel="Next" />
    </>;
  }
  else if (step === 'self-duration') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`How long has ${who} been in this profession?`} />
      <div className="field-row">
        <Field label="Years" inputMode="numeric" value={data.profYears} onChange={v => set({ profYears: incDigits(v).slice(0, 2) })} placeholder="0" error={t && data.profYears === '' ? 'Required' : ''} />
        <Select label="Months" value={data.profMonths} onChange={v => set({ profMonths: v })} options={MONTHS_INC} placeholder="0" error={t && data.profMonths === '' ? 'Required' : ''} />
      </div>
      <NavFooter onBack={back} onNext={next} nextLabel="Next" />
    </>;
  }
  else if (step === 'self-structure') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`How is ${whoP} business structured?`} />
      <div className="opt-list">
        {STRUCTURE.map(s => <Opt key={s} title={s} selected={data.structure === s} onClick={() => set({ structure: s })} />)}
      </div>
      <NavFooter onBack={back} onNext={next} nextLabel="Next" nextDisabled={!data.structure} />
    </>;
  }
  else if (step === 'self-ownership') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`How much of the business does ${who} own?`} />
      <div className="opt-list two-up">
        <Opt title="Greater than 20%" twoUp selected={data.ownership === 'gt20'} onClick={() => set({ ownership: 'gt20' })} />
        <Opt title="Less than 20%" twoUp selected={data.ownership === 'lt20'} onClick={() => set({ ownership: 'lt20' })} />
      </div>
      <NavFooter onBack={back} onNext={next} nextLabel="Next" nextDisabled={!data.ownership} />
    </>;
  }
  else if (step === 'self-income') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`Approximately how much does ${whoP} business make after expenses?`} sub="Enter your best estimate. This can be updated later if needed." />
      <Field label="Income after expenses" prefix="$" inputMode="numeric" value={data.incomeAfterExp} onChange={v => set({ incomeAfterExp: incMoney(v) })} placeholder="120,000" error={t && !incNum(data.incomeAfterExp) ? 'Required' : ''} />
      <Select label="How often is this amount earned?" value={data.incomeFreq} onChange={v => set({ incomeFreq: v })} options={FREQ_FULL} />
      <NavFooter onBack={back} onNext={next} nextLabel="Confirm and Continue" />
    </>;
  }

  /* ===== RETIREMENT ===== */
  else if (step === 'ret-details') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`What type of retirement income does ${who} receive?`} />
      <div className="opt-list">
        {['Social Security', 'Pension', 'Retirement Accounts'].map(r =>
          <Opt key={r} title={r} selected={data.retType === r} onClick={() => set({ retType: r })} />)}
      </div>
      {data.retType && <div className="step" style={{ marginTop: 18 }}>
        <Field label="Amount received" prefix="$" inputMode="numeric" value={data.retAmount} onChange={v => set({ retAmount: incMoney(v) })} placeholder="2,000" error={t && !incNum(data.retAmount) ? 'Required' : ''} />
        <Select label="How often is this amount received?" value={data.retFreq} onChange={v => set({ retFreq: v })} options={RET_FREQ} />
      </div>}
      <NavFooter onBack={back} onNext={next} nextLabel="Confirm and Continue" nextDisabled={!data.retType} />
    </>;
  }

  /* ===== OTHER ===== */
  else if (step === 'other-type') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`What type of other income does ${who} receive?`} />
      <Select label="Other income type" value={data.otherType} onChange={v => set({ otherType: v })} options={OTHER_TYPES} placeholder="Select income type" error={t && !data.otherType ? 'Required' : ''} />
      <NavFooter onBack={back} onNext={next} nextLabel="Next" nextDisabled={!data.otherType} />
    </>;
  }
  else if (step === 'other-amount') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`How much does ${who} receive each month?`} />
      <Field label="Monthly amount" prefix="$" inputMode="numeric" value={data.monthlyAmt} onChange={v => set({ monthlyAmt: incMoney(v) })} placeholder="500" error={t && !incNum(data.monthlyAmt) ? 'Required' : ''} />
      {data.otherType === 'Other' && <Field label="Description" value={data.otherDesc} onChange={v => set({ otherDesc: v })} placeholder="Describe this income" error={t && !data.otherDesc.trim() ? 'Required' : ''} />}
      <NavFooter onBack={back} onNext={next} nextLabel="Confirm and Continue" />
    </>;
  }

  return (
    <main className="flow">
      <div className="flow-col">
        <div className="step" key={step}>
          {chain.length > 1 && (
            <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: `${(di / (chain.length - 1)) * 100}%`, transition: 'width .35s' }} />
              </div>
              <span style={{ fontSize: 11, fontWeight: 600, letterSpacing: '.06em', color: 'var(--muted)', whiteSpace: 'nowrap', fontFamily: 'monospace' }}>
                {di + 1} / {chain.length}
              </span>
            </div>
          )}
          <div className="step-anim" key={step}>{body}</div>
        </div>
      </div>
    </main>
  );
}

window.IncomeFlow = IncomeFlow;
window.incomeSummary = incomeSummary;
