// DebtLift settlement calculator — shared by the marketing site hero and the
// dedicated calculator page (affiliate-trackable). Exposes window.SettlementCalculator.
// Flow: lender-by-lender entry → auto monthly total → 3 plans → contact → CRM lead.
const CALC_IC = ({ d, size = 16 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" dangerouslySetInnerHTML={{ __html: d }} />
);
const CALC_ICONS = {
  zap: '<path d="M13 2 4 14h6l-1 8 9-12h-6l1-8z"/>',
  check: '<path d="M20 6 9 17l-5-5"/>',
  x: '<path d="M18 6 6 18M6 6l12 12"/>',
};

const calcFmt = n => '$' + Math.round(n).toLocaleString('en-US');

const DL_PLANS = [
  { key: 'weekly', label: 'Weekly', reduction: 40, perYear: 52, per: '/wk' },
  { key: 'biweekly', label: 'Bi-Weekly', reduction: 50, perYear: 26, per: '/2wk', badge: 'Most Popular', badgeBg: 'var(--inst-navy)' },
  { key: 'monthly', label: 'Monthly', reduction: 60, perYear: 12, per: '/mo', badge: 'Best Value', badgeBg: 'var(--inst-pos)' },
];

// daily payments hit ~21 business days/mo; weekly ~4.33 weeks/mo
const MONTHLY_MULT = { daily: 21, weekly: 4.33 };

function SettlementCalculator({ refPartner }) {
  const [step, setStep] = React.useState(1);
  const [debt, setDebt] = React.useState(120000);
  const [rows, setRows] = React.useState([
    { lender: '', amount: '', freq: 'daily' },
    { lender: '', amount: '', freq: 'daily' },
  ]);
  const [plan, setPlan] = React.useState(null);
  const [biz, setBiz] = React.useState('');
  const [name, setName] = React.useState('');
  const [phone, setPhone] = React.useState('');
  const n = v => { const x = parseFloat(v); return isNaN(x) ? 0 : x; };

  const monthly = rows.reduce((s, r) => s + n(r.amount) * MONTHLY_MULT[r.freq], 0);
  const filled = rows.filter(r => n(r.amount) > 0);
  const positions = filled.length;

  const setRow = (i, patch) => setRows(p => p.map((r, x) => x === i ? { ...r, ...patch } : r));
  const addRow = () => setRows(p => [...p, { lender: '', amount: '', freq: 'daily' }]);
  const delRow = i => setRows(p => p.length > 1 ? p.filter((_, x) => x !== i) : p);

  const posLabel = positions === 1 ? '1 position' : positions + ' positions';

  return (
    <div className="inst-card" style={{ width: '100%', maxWidth: 760, flexShrink: 0 }}>
      <div className="inst-section-bar">
        <span>Settlement calculator</span>
        {refPartner ? <span className="right">via {refPartner}</span> : null}
      </div>

      {step === 1 ? (
        <div className="inst-card-body" style={{ display: 'grid', gap: 14, maxWidth: 520, margin: '0 auto', width: '100%' }}>
          <div className="inst-field"><label>Total MCA debt (all balances)</label><input className="inst-input" type="text" inputMode="numeric" value={debt ? debt.toLocaleString('en-US') : ''} onChange={e => setDebt(n(e.target.value.replace(/[^0-9]/g, '')))} /></div>

          <div className="inst-field" style={{ marginBottom: -6 }}><label>Your lenders & payments</label></div>
          <div style={{ display: 'grid', gap: 8 }}>
            {rows.map((r, i) => (
              <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 92px 92px 26px', gap: 6, alignItems: 'center' }}>
                <input className="inst-input" placeholder={'Lender ' + (i + 1)} value={r.lender} onChange={e => setRow(i, { lender: e.target.value })} />
                <input className="inst-input" type="text" inputMode="numeric" placeholder="$ pmt" value={r.amount ? Number(r.amount).toLocaleString('en-US') : ''} onChange={e => setRow(i, { amount: e.target.value.replace(/[^0-9]/g, '') })} />
                <select className="inst-input" value={r.freq} onChange={e => setRow(i, { freq: e.target.value })}>
                  <option value="daily">Daily</option>
                  <option value="weekly">Weekly</option>
                </select>
                <button onClick={() => delRow(i)} title="Remove" style={{ background: 'none', border: 'none', color: 'var(--inst-ink-3)', cursor: 'pointer', padding: 2, display: 'flex' }}><CALC_IC d={CALC_ICONS.x} size={14} /></button>
              </div>
            ))}
          </div>
          <a className="inst-link" style={{ fontSize: 12 }} onClick={addRow}>+ Add another lender</a>

          <div style={{ background: 'var(--brand-50)', border: '1px solid #c8d9f2', borderRadius: 6, padding: '12px 14px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.5px', textTransform: 'uppercase', color: 'var(--inst-ink-3)' }}>You're paying</span>
            <span className="inst-amount" style={{ fontSize: 24 }}>{calcFmt(monthly)}<span style={{ fontSize: 12, fontWeight: 600, color: 'var(--inst-ink-3)' }}>/mo</span></span>
          </div>

          <button className="inst-btn primary" style={{ width: '100%', padding: '11px 18px' }} onClick={() => setStep(2)} disabled={!monthly}>See my payment options ›</button>
          <div style={{ fontSize: 11, color: 'var(--inst-ink-3)', textAlign: 'center' }}>Estimates based on typical negotiated outcomes. No credit impact.</div>
        </div>
      ) : null}

      {step === 2 ? (
        <div className="inst-card-body">
          <div style={{ fontSize: 13, color: 'var(--inst-ink-2)', marginBottom: 14 }}>Three ways to lower your <b>{calcFmt(monthly)}/mo</b> across {posLabel} — pick the plan that fits your cash flow:</div>
          <div className="inst-grid-3" style={{ gap: 12 }}>
            {DL_PLANS.map(p => {
              const newMonthly = monthly * (1 - p.reduction / 100);
              const perPayment = newMonthly * 12 / p.perYear;
              const monthlySavings = monthly - newMonthly;
              return (
                <div key={p.key} style={{
                  position: 'relative', border: '1px solid ' + (p.badge ? p.badgeBg : 'var(--inst-rule)'),
                  borderWidth: p.badge ? 2 : 1, borderRadius: 6, padding: '20px 14px 14px', textAlign: 'center',
                  display: 'flex', flexDirection: 'column', gap: 4,
                }}>
                  {p.badge ? (
                    <span style={{
                      position: 'absolute', top: -10, left: '50%', transform: 'translateX(-50%)',
                      background: p.badgeBg, color: '#fff', fontSize: 10, fontWeight: 800,
                      letterSpacing: '.6px', textTransform: 'uppercase', padding: '3px 10px', borderRadius: 3, whiteSpace: 'nowrap',
                    }}>{p.badge}</span>
                  ) : null}
                  <div style={{ fontSize: 13, fontWeight: 800, color: 'var(--inst-ink)' }}>{p.label}</div>
                  <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: '.4px', textTransform: 'uppercase', color: 'var(--inst-link)' }}>{p.reduction}% payment reduction</div>
                  <div className="inst-amount" style={{ fontSize: 24, textAlign: 'center', marginTop: 6 }}>{calcFmt(perPayment)}<span style={{ fontSize: 12, fontWeight: 600, color: 'var(--inst-ink-3)' }}>{p.per}</span></div>
                  <div style={{ fontSize: 12, color: 'var(--inst-pos)', fontWeight: 700 }}>Save {calcFmt(monthlySavings)}/mo</div>
                  <div style={{ flex: 1 }}></div>
                  <button className={'inst-btn ' + (p.badge ? 'primary' : 'outline')} style={{ width: '100%', marginTop: 10 }} onClick={() => { setPlan(p); setStep(3); }}>Choose {p.label}</button>
                </div>
              );
            })}
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14 }}>
            <button className="inst-btn outline sm" onClick={() => setStep(1)}>‹ Back</button>
            <span style={{ fontSize: 11, color: 'var(--inst-ink-3)' }}>Payments shown after DebtLift negotiates your {calcFmt(debt)} across {posLabel}.</span>
          </div>
        </div>
      ) : null}

      {step === 3 ? (
        <div className="inst-card-body" style={{ display: 'grid', gap: 14, maxWidth: 520, margin: '0 auto', width: '100%' }}>
          <div style={{ fontSize: 13, color: 'var(--inst-ink-2)' }}>Where should we send your <b>{plan ? plan.label : ''} plan</b> ({plan ? plan.reduction : ''}% payment reduction) for <b>{calcFmt(debt)}</b> across <b>{posLabel}</b>?</div>
          <div className="inst-field"><label>Business name</label><input className="inst-input" value={biz} onChange={e => setBiz(e.target.value)} /></div>
          <div className="inst-field"><label>Your name</label><input className="inst-input" value={name} onChange={e => setName(e.target.value)} /></div>
          <div className="inst-field"><label>Phone</label><input className="inst-input" value={phone} onChange={e => setPhone(e.target.value)} /></div>
          <div style={{ display: 'flex', gap: 10 }}>
            <button className="inst-btn outline" onClick={() => setStep(2)}>‹ Back</button>
            <button className="inst-btn primary" style={{ flex: 1 }} onClick={() => {
              setStep(4);
              try {
                fetch('/api/leads', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({
                  brand: 'DebtLift', biz, owner: name, phone, amount: debt,
                  ref: new URLSearchParams(window.location.search).get('ref') || undefined,
                  intake: { type: 'DebtLift Calculator', totalDebt: debt, positions, monthlyPayments: Math.round(monthly), plan: plan ? plan.label : '' },
                }) }).catch(() => {});
              } catch (e) {}
            }} disabled={!biz && !name}>Send my plan</button>
          </div>
        </div>
      ) : null}

      {step === 4 ? (
        <div className="inst-card-body" style={{ textAlign: 'center', padding: '28px 20px', maxWidth: 560, margin: '0 auto' }}>
          <div style={{ width: 44, height: 44, borderRadius: '50%', background: 'var(--inst-pos)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}><CALC_IC d={CALC_ICONS.check} size={22} /></div>
          <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--inst-ink)' }}>Your case is in review</div>
          <div style={{ fontSize: 13, color: 'var(--inst-ink-2)', marginTop: 8, lineHeight: 1.6 }}>A settlement specialist will call {name ? name.split(' ')[0] : 'you'} today about your <b>{plan ? plan.label : ''} plan</b> — {plan ? plan.reduction : ''}% payment reduction on {calcFmt(debt)} across {posLabel}.</div>
          <div className="inst-notice" style={{ marginTop: 16, textAlign: 'left' }}>
            <span className="bulb"><CALC_IC d={CALC_ICONS.zap} size={15} /></span>
            <span style={{ fontSize: 12 }}>
              This submission just created a <b>New lead</b> in the <a className="inst-link" href="../admin/">CRM lead funnel</a> — with each lender, payment and your chosen plan attached.
              {refPartner ? <span> Source: <b>{refPartner}</b> (referral link) — this lead and its commission are attributed to them automatically.</span> : <span> Source: DebtLift Calculator.</span>}
            </span>
          </div>
        </div>
      ) : null}
    </div>
  );
}

window.SettlementCalculator = SettlementCalculator;
