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

const ACCOUNT_TYPES = ['Checking', 'Savings', 'Retirement', 'Stock', 'Mutual Fund', 'Money Market', 'Bonds', 'Certificate of Deposit', 'Trust Account', 'Cash Value of Life Insurance', 'Stock Options', 'Bridge Loan Proceeds', 'Individual Development Account'];
const GIFT_SOURCES = ['Relative', 'Unmarried Partner', 'Parent', 'Unrelated Friend', 'Other'];
const OTHER_ASSET_TYPES = ['Cash on Hand', 'Proceeds from the Sale of Real Estate on or Before Closing', 'Proceeds from the Sale of Non-Real Estate Asset', 'Proceeds from Secured Loan', 'Proceeds from Unsecured Loan', 'Other'];

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

const AST_DEFAULT = {
  type: null,                 // financial | gift | other
  // financial
  method: null, verified: false,
  institution: '', acctType: '', balance: '',
  // gift / grant
  giftKind: null,             // cash | grant
  giftSource: '', giftSourceOther: '', giftValue: '',
  // other
  otherType: '', otherDesc: '', otherValue: '',
  touched: false,
};

const ASSET_TYPES = [
  { value: 'financial', title: 'Financial Account', sub: 'Checking, savings, retirement, investment, money market, and similar accounts.', icon: () => I.building(22) },
  { value: 'gift', title: 'Gift or Grant', sub: 'Cash gifts or grant funds that may be used for the loan.', icon: () => I.cash(22) },
  { value: 'other', title: 'Other Asset', sub: 'Cash on hand, proceeds from a sale, loan proceeds, or other assets.', icon: () => I.invest(22) },
];

/* hub summary */
function assetSummary(a) {
  if (a.type === 'financial') return { title: a.acctType || 'Financial Account', detail: `${a.institution || 'Institution'} · $${a.balance || '0'}`, verified: a.verified };
  if (a.type === 'gift') {
    if (a.giftKind === 'grant') return { title: 'Grant', detail: `$${a.giftValue || '0'}` };
    const src = a.giftSource === 'Other' ? a.giftSourceOther : a.giftSource;
    return { title: 'Cash Gift', detail: `${src || 'Source'} · $${a.giftValue || '0'}` };
  }
  if (a.type === 'other') {
    const ot = a.otherType === 'Other' ? a.otherDesc : a.otherType;
    return { title: ot || 'Other Asset', detail: `$${a.otherValue || '0'}` };
  }
  return { title: 'Asset', detail: '' };
}

function astValid(step, d) {
  switch (step) {
    case 'type': return !!d.type;
    case 'fin-method': return !!d.method;
    case 'fin-institution': return d.institution.trim();
    case 'fin-type': return !!d.acctType;
    case 'fin-balance': return astNum(d.balance) > 0;
    case 'gift-kind': return !!d.giftKind;
    case 'gift-source': return d.giftSource && (d.giftSource !== 'Other' || d.giftSourceOther.trim());
    case 'gift-value': return astNum(d.giftValue) > 0;
    case 'other-type': return d.otherType && (d.otherType !== 'Other' || d.otherDesc.trim());
    case 'other-value': return astNum(d.otherValue) > 0;
    default: return true;
  }
}

function astChain(d) {
  if (d.type === 'financial') {
    return d.method === 'verify'
      ? ['type', 'fin-method', 'fin-verify']
      : ['type', 'fin-method', 'fin-institution', 'fin-type', 'fin-balance'];
  }
  if (d.type === 'gift') {
    return d.giftKind === 'cash'
      ? ['type', 'gift-kind', 'gift-source', 'gift-value']
      : ['type', 'gift-kind', 'gift-value'];
  }
  if (d.type === 'other') return ['type', 'other-type', 'other-value'];
  return ['type'];
}

/* ===================================================================== */
function AssetFlow({ borrowerName, initial, onCancel, onSave, onProgress }) {
  const [data, setData] = useAST(initial ? { ...AST_DEFAULT, ...initial, touched: false } : AST_DEFAULT);
  const [step, setStep] = useAST('type');
  const set = patch => setData(d => ({ ...d, ...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 (!astValid(step, data)) { set({ touched: true }); return; }
    const chain = astChain(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();
    const chain = astChain(data);
    const i = chain.indexOf(step);
    if (i <= 0) return goTo('type');
    goTo(chain[i - 1]);
  }

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

  const eyebrow = 'ADD ASSET';
  let body = null;

  if (step === 'type') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`What type of asset would you like to add for ${who}?`} sub="You can add more than one asset for each borrower." />
      <div className="opt-list">
        {ASSET_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" />
    </>;
  }

  /* ===== FINANCIAL ACCOUNT ===== */
  else if (step === 'fin-method') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`How would you like to add ${whoP} financial account?`} />
      <div className="opt-list">
        <button className={'opt opt-feature' + (data.method === 'verify' ? ' sel' : '')} onClick={() => set({ method: 'verify' })}>
          <span className="opt-icon">{I.bolt(22)}</span>
          <span className="opt-main">
            <span className="opt-title">Verify through my financial institution <span className="opt-badge">Coming soon</span></span>
            <span className="opt-sub">Connected account verification is not available yet. Your loan team verifies assets with statements after you apply.</span>
          </span>
          <span className="opt-radio">{I.check(13)}</span>
        </button>
        <Opt icon={I.pencil(20)} title="Enter financial account manually" sub="Add bank, account type, and balance details yourself."
          selected={data.method === 'manual'} onClick={() => set({ method: 'manual' })} />
      </div>
      <NavFooter onBack={back} onNext={next} nextLabel="Next" nextDisabled={!data.method} />
    </>;
  }
  else if (step === 'fin-verify') {
    // No fake verification: connected account verification is not wired yet,
    // so this step is an honest notice that routes into manual entry. It must
    // never save a fabricated institution or balance, or set verified without
    // a real vendor.
    body = <>
      <StepHead eyebrow={eyebrow} title="Account verification is coming soon" sub="Connected account verification is not available on this application yet. Enter your account details manually and your loan team will verify them with statements 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(15)} Nothing is connected or shared without your action. Balances you enter are marked as stated until your loan team verifies them.</div>
        <button className="btn btn-primary btn-block" onClick={() => { set({ method: 'manual' }); goTo('fin-institution'); }}>
          Enter account 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 === 'fin-institution') {
    body = <>
      <StepHead eyebrow={eyebrow} title="Which bank or institution is this account with?" />
      <Field label="Bank or institution name" value={data.institution} onChange={v => set({ institution: v })} placeholder="Example: Chase, Bank of America, Fidelity" error={t && !data.institution.trim() ? 'Required' : ''} />
      <NavFooter onBack={back} onNext={next} nextLabel="Next" />
    </>;
  }
  else if (step === 'fin-type') {
    body = <>
      <StepHead eyebrow={eyebrow} title="What type of account is this?" />
      <Select label="Account type" value={data.acctType} onChange={v => set({ acctType: v })} options={ACCOUNT_TYPES} placeholder="Select account type" error={t && !data.acctType ? 'Required' : ''} />
      <NavFooter onBack={back} onNext={next} nextLabel="Next" nextDisabled={!data.acctType} />
    </>;
  }
  else if (step === 'fin-balance') {
    body = <>
      <StepHead eyebrow={eyebrow} title="What is the balance of this account?" sub="Enter your best estimate. You can update this later if needed." />
      <Field label="Account balance" prefix="$" inputMode="numeric" value={data.balance} onChange={v => set({ balance: astMoney(v) })} placeholder="25,000" error={t && !astNum(data.balance) ? 'Required' : ''} />
      <NavFooter onBack={back} onNext={next} nextLabel="Confirm and Continue" />
    </>;
  }

  /* ===== GIFT OR GRANT ===== */
  else if (step === 'gift-kind') {
    body = <>
      <StepHead eyebrow={eyebrow} title="What type of gift or grant is this?" />
      <div className="opt-list two-up">
        <Opt icon={I.cash(22)} title="Cash Gift" twoUp selected={data.giftKind === 'cash'} onClick={() => set({ giftKind: 'cash' })} />
        <Opt icon={I.seedling(22)} title="Grant" twoUp selected={data.giftKind === 'grant'} onClick={() => set({ giftKind: 'grant' })} />
      </div>
      <NavFooter onBack={back} onNext={next} nextLabel="Next" nextDisabled={!data.giftKind} />
    </>;
  }
  else if (step === 'gift-source') {
    body = <>
      <StepHead eyebrow={eyebrow} title="Who is providing the cash gift?" />
      <div className="opt-list">
        {GIFT_SOURCES.map(s => <Opt key={s} title={s} selected={data.giftSource === s} onClick={() => set({ giftSource: s })} />)}
      </div>
      {data.giftSource === 'Other' && <div className="step" style={{ marginTop: 14 }}>
        <Field label="Gift source description" value={data.giftSourceOther} onChange={v => set({ giftSourceOther: v })} placeholder="Describe the gift source" error={t && !data.giftSourceOther.trim() ? 'Required' : ''} />
      </div>}
      <NavFooter onBack={back} onNext={next} nextLabel="Next" nextDisabled={!data.giftSource} />
    </>;
  }
  else if (step === 'gift-value') {
    body = <>
      <StepHead eyebrow={eyebrow} title={`What is the cash or market value of this ${data.giftKind === 'grant' ? 'grant' : 'gift'}?`} />
      <Field label="Cash or market value" prefix="$" inputMode="numeric" value={data.giftValue} onChange={v => set({ giftValue: astMoney(v) })} placeholder="10,000" error={t && !astNum(data.giftValue) ? 'Required' : ''} />
      <NavFooter onBack={back} onNext={next} nextLabel="Confirm and Continue" />
    </>;
  }

  /* ===== OTHER ASSET ===== */
  else if (step === 'other-type') {
    body = <>
      <StepHead eyebrow={eyebrow} title="Is this an asset or cash on hand?" />
      <Select label="Asset source" value={data.otherType} onChange={v => set({ otherType: v })} options={OTHER_ASSET_TYPES} placeholder="Select asset source" error={t && !data.otherType ? 'Required' : ''} />
      {data.otherType === 'Other' && <div className="step" style={{ marginTop: 4 }}>
        <Field label="Other asset description" value={data.otherDesc} onChange={v => set({ otherDesc: v })} placeholder="Describe this asset" error={t && !data.otherDesc.trim() ? 'Required' : ''} />
      </div>}
      <NavFooter onBack={back} onNext={next} nextLabel="Next" nextDisabled={!data.otherType} />
    </>;
  }
  else if (step === 'other-value') {
    body = <>
      <StepHead eyebrow={eyebrow} title="What is the value of this asset?" sub="Enter the amount you expect to use or have available." />
      <Field label="Asset value" prefix="$" inputMode="numeric" value={data.otherValue} onChange={v => set({ otherValue: astMoney(v) })} placeholder="5,000" error={t && !astNum(data.otherValue) ? '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.AssetFlow = AssetFlow;
window.assetSummary = assetSummary;
