// Add liability — bottom sheet flow (mirrors add_asset.jsx)

const LIABILITY_LENDERS_UAE = [
  'Emirates NBD', 'Mashreq', 'ADCB', 'FAB',
  'HSBC', 'Dubai Islamic Bank', 'ADIB', 'RAKBANK',
];

const LOAN_KIND_OPTIONS = [
  { key: 'personal', label: 'Personal loan',   icon: 'wallet',    sub: 'Unsecured cash loan' },
  { key: 'car',      label: 'Car loan',        icon: 'car',       sub: 'Auto financing' },
  { key: 'student',  label: 'Student loan',    icon: 'briefcase', sub: 'Education debt' },
];

function AddLiabilityModal({ theme, accent, open, onClose }) {
  // step:
  //   pick           → kind picker (loan / card / mortgage / line of credit)
  //   loan-kind      → personal / car / student
  //   provider       → lender grid (bank tiles)
  //   manual         → manual entry form
  const [step, setStep] = React.useState('pick');
  const [kind, setKind] = React.useState(null);          // 'loan' | 'card' | 'mortgage' | 'loc'
  const [loanKind, setLoanKind] = React.useState(null);  // 'personal' | 'car' | 'student'
  const [form, setForm] = React.useState({ balance: '', apr: '', monthly: '', payoff: '' });

  React.useEffect(() => {
    if (!open) {
      setTimeout(() => {
        setStep('pick'); setKind(null); setLoanKind(null);
        setForm({ balance: '', apr: '', monthly: '', payoff: '' });
      }, 300);
    }
  }, [open]);

  const kinds = [
    { key: 'loan',     label: 'Loan',            icon: 'wallet',   sub: 'Personal · Car · Student' },
    { key: 'card',     label: 'Credit card',     icon: 'wallet',   sub: 'Revolving balance' },
    { key: 'mortgage', label: 'Mortgage',        icon: 'building', sub: 'Linked to a property' },
    { key: 'loc',      label: 'Line of credit',  icon: 'chart',    sub: 'Manual entry' },
  ];

  const pickKind = (k) => {
    setKind(k.key);
    if (k.key === 'loan')      setStep('loan-kind');
    else if (k.key === 'loc')  setStep('manual');
    else                       setStep('provider');
  };

  if (!open) return null;

  const titleByKind = {
    loan:     loanKind ? `Choose ${LOAN_KIND_OPTIONS.find(o => o.key === loanKind)?.label.toLowerCase()} lender` : 'Choose lender',
    card:     'Choose card issuer',
    mortgage: 'Choose mortgage lender',
    loc:      'Add line of credit',
  };

  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 100,
      display: 'flex', alignItems: 'flex-end',
      background: 'rgba(0,0,0,0.55)',
      animation: 'himma-fade 200ms',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxHeight: '88%',
        background: theme.surface,
        borderRadius: '24px 24px 0 0',
        borderTop: `0.5px solid ${theme.line2}`,
        padding: '10px 20px 34px',
        animation: 'himma-slide 260ms cubic-bezier(.2,.8,.25,1)',
        overflow: 'auto',
      }}>
        <div style={{ display:'flex', justifyContent:'center', paddingBottom: 14 }}>
          <div style={{ width: 40, height: 4, borderRadius: 2, background: theme.line2 }}/>
        </div>

        {step === 'pick' && (
          <>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, letterSpacing: -0.4 }}>Add a liability</div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>
              Track what you owe so net worth stays honest.
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 18 }}>
              {kinds.map(k => {
                const Icon = Ico[k.icon];
                return (
                  <button key={k.key} onClick={() => pickKind(k)}
                    style={{
                      background: theme.surface2,
                      border: `0.5px solid ${theme.line}`,
                      borderRadius: 14, padding: '14px 14px',
                      display: 'flex', alignItems: 'center', gap: 12,
                      cursor: 'pointer', textAlign: 'left', color: theme.text,
                    }}>
                    <div style={{ width: 36, height: 36, borderRadius: 10, background: theme.surface3, color: accent, display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0 }}>
                      <Icon size={17}/>
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 500 }}>{k.label}</div>
                      <div style={{ fontSize: 11, fontFamily: FONTS.mono, color: theme.textMute, marginTop: 2 }}>{k.sub}</div>
                    </div>
                    <Ico.chevR size={14} stroke={theme.textMute}/>
                  </button>
                );
              })}
            </div>
          </>
        )}

        {step === 'loan-kind' && (
          <>
            <BackBtn theme={theme} onClick={() => setStep('pick')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>What kind of loan?</div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>
              Each type tracks a bit differently — interest, payoff date, and recommended payoff strategies vary.
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 18 }}>
              {LOAN_KIND_OPTIONS.map(o => {
                const Icon = Ico[o.icon];
                return (
                  <button key={o.key} onClick={() => { setLoanKind(o.key); setStep('provider'); }}
                    style={{
                      background: theme.surface2, border: `0.5px solid ${theme.line}`,
                      borderRadius: 14, padding: '14px 14px',
                      display: 'flex', alignItems: 'center', gap: 12,
                      cursor: 'pointer', textAlign: 'left', color: theme.text,
                    }}>
                    <div style={{ width: 36, height: 36, borderRadius: 10, background: theme.surface3, color: accent, display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0 }}>
                      <Icon size={17}/>
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13.5, fontWeight: 500 }}>{o.label}</div>
                      <div style={{ fontSize: 11, fontFamily: FONTS.mono, color: theme.textMute, marginTop: 2 }}>{o.sub}</div>
                    </div>
                    <Ico.chevR size={14} stroke={theme.textMute}/>
                  </button>
                );
              })}
            </div>
          </>
        )}

        {step === 'provider' && (
          <>
            <BackBtn theme={theme} onClick={() => setStep(kind === 'loan' ? 'loan-kind' : 'pick')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>{titleByKind[kind]}</div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>
              Connect to import balance and rate — or add manually below.
            </div>

            <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {LIABILITY_LENDERS_UAE.map(p => (
                <ProviderTile key={p} theme={theme} name={p} onClick={onClose}/>
              ))}
            </div>

            <button
              onClick={() => setStep('manual')}
              style={{
                marginTop: 14, width: '100%',
                background: 'transparent',
                border: `0.5px dashed ${theme.line2}`,
                borderRadius: 12, padding: '12px',
                color: theme.text, cursor: 'pointer',
                fontFamily: FONTS.ui, fontSize: 12.5, fontWeight: 500,
              }}>+ Add manually</button>

            <SecureBadge theme={theme} accent={accent}/>
          </>
        )}

        {step === 'manual' && (
          <>
            <BackBtn theme={theme} onClick={() => setStep(kind === 'loc' ? 'pick' : 'provider')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>
              Add manually
            </div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>
              Useful for family loans, employer loans, or anything not linkable.
            </div>

            <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
              <Field label="Outstanding balance" prefix={<Dh/>} theme={theme}
                value={form.balance} onChange={v => setForm({ ...form, balance: v })} placeholder="0"/>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <Field label="APR" suffix="%" theme={theme}
                  value={form.apr} onChange={v => setForm({ ...form, apr: v })} placeholder="0.0"/>
                <Field label="Monthly payment" prefix={<Dh/>} theme={theme}
                  value={form.monthly} onChange={v => setForm({ ...form, monthly: v })} placeholder="0"/>
              </div>
              <Field label="Payoff date (approx.)" theme={theme}
                value={form.payoff} onChange={v => setForm({ ...form, payoff: v })} placeholder="Mar 2030"/>
            </div>

            <button
              onClick={onClose}
              disabled={!form.balance}
              style={{
                marginTop: 22, width: '100%',
                background: !form.balance ? theme.surface3 : accent,
                color: !form.balance ? theme.textMute : theme.bg,
                border: 'none', padding: '14px', borderRadius: 14,
                fontFamily: FONTS.ui, fontSize: 14, fontWeight: 600,
                cursor: !form.balance ? 'not-allowed' : 'pointer',
              }}>Save liability</button>

            <div style={{ marginTop: 14, padding: '10px 12px', background: theme.surface2, borderRadius: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
              <Ico.lock size={14} stroke={accent}/>
              <span style={{ fontFamily: FONTS.mono, fontSize: 10.5, color: theme.textDim, letterSpacing: 0.2 }}>
                Stored only on your device. Update anytime.
              </span>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

function Field({ label, value, onChange, placeholder, prefix, suffix, theme }) {
  return (
    <div>
      <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute, textTransform: 'uppercase', letterSpacing: 1, marginBottom: 6 }}>{label}</div>
      <div style={{
        display: 'flex', alignItems: 'center', gap: 8,
        background: theme.surface2,
        border: `0.5px solid ${theme.line2}`, borderRadius: 12,
        padding: '12px 14px',
      }}>
        {prefix && <span style={{ fontFamily: FONTS.mono, fontSize: 11, color: theme.textMute }}>{prefix}</span>}
        <input
          value={value}
          onChange={e => onChange(e.target.value)}
          placeholder={placeholder}
          style={{
            flex: 1, background: 'transparent', border: 'none', outline: 'none',
            color: theme.text, fontSize: 13.5, fontFamily: FONTS.mono,
            letterSpacing: 0.3, minWidth: 0,
          }}
        />
        {suffix && <span style={{ fontFamily: FONTS.mono, fontSize: 11, color: theme.textMute }}>{suffix}</span>}
      </div>
    </div>
  );
}

Object.assign(window, { AddLiabilityModal });
