// 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' },
];

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

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

  const kinds = [
    { key: 'mortgage', label: 'Mortgage',            icon: 'building', sub: 'Linked to a property' },
    { key: 'loan',     label: 'Loan',                icon: 'wallet',   sub: 'Personal · Car' },
    { key: 'card',     label: 'Credit card',         icon: 'wallet',   sub: 'Revolving balance' },
    { key: 'custom',   label: 'Custom / manual entry', icon: 'chart',  sub: 'Anything not listed above' },
  ];

  const pickKind = (k) => {
    setKind(k.key);
    setForm({});
    if (k.key === 'loan')         setStep('loan-kind');
    else if (k.key === 'custom')  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',
    custom:   'Add manually',
  };
  const manualTitle = {
    mortgage: 'Mortgage details',
    loan: loanKind ? `Add ${LOAN_KIND_OPTIONS.find(o => o.key === loanKind)?.label.toLowerCase()} manually` : 'Add loan manually',
    card: 'Add credit card manually',
    custom: 'Add manually',
  };
  const providerBackStep = kind === 'loan' ? 'loan-kind' : 'pick';
  const set = (key, value) =>
    setForm((f) =>
      typeof key === 'object' ? { ...f, ...key } : { ...f, [key]: value },
    );

  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={{ 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>
                    <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={{ 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>
                    <Ico.chevR size={14} stroke={theme.textMute}/>
                  </button>
                );
              })}
            </div>
          </>
        )}

        {step === 'provider' && (
          <>
            <BackBtn theme={theme} onClick={() => setStep(providerBackStep)}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>{titleByKind[kind]}</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 === 'custom' ? 'pick' : 'provider')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>
              {manualTitle[kind] || 'Add manually'}
            </div>

            {kind === 'mortgage' && (
              <ManualMortgageLiabilityForm
                theme={theme}
                accent={accent}
                form={form}
                set={set}
              />
            )}

            {kind === 'loan' && (
              <ManualLoanLiabilityForm
                theme={theme}
                form={form}
                set={set}
                loanKind={loanKind}
              />
            )}

            {kind === 'card' && (
              <ManualCardLiabilityForm theme={theme} form={form} set={set}/>
            )}

            {kind === 'custom' && (
              <ManualCustomLiabilityForm theme={theme} form={form} set={set}/>
            )}

            <button
              onClick={onClose}
              disabled={!canSaveManualLiability(kind, form)}
              style={{
                marginTop: 22, width: '100%',
                background: !canSaveManualLiability(kind, form) ? theme.surface3 : accent,
                color: !canSaveManualLiability(kind, form) ? theme.textMute : theme.bg,
                border: 'none', padding: '14px', borderRadius: 14,
                fontFamily: FONTS.ui, fontSize: 14, fontWeight: 600,
                cursor: !canSaveManualLiability(kind, form) ? '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 cleanMoney(v) {
  return String(v).replace(/[^0-9]/g, '');
}

function cleanRate(v) {
  return String(v).replace(/[^0-9.]/g, '');
}

function mortgageRateType(form) {
  return normalizeMortgageRateType(form.rateType);
}

function hasMortgageRate(form) {
  return hasMortgageRateInputs(form);
}

function canSaveManualLiability(kind, form) {
  if (kind === 'mortgage') {
    return canSaveMortgageForm(form, true);
  }
  if (kind === 'loan') {
    return form.lender && form.balance && form.apr && form.monthlyPayment;
  }
  if (kind === 'card') {
    return form.issuer && form.balance && form.limit && form.apr;
  }
  return form.name && form.balance;
}

function ManualMortgageLiabilityForm({ theme, accent, form, set }) {
  const rateType = mortgageRateType(form);
  const setFixedApr = (value) => {
    const fixedApr = cleanMortgageRate(value);
    set({ fixedApr, apr: fixedApr });
  };
  const setCurrentApr = (value) => {
    const currentApr = cleanMortgageRate(value);
    set({ currentApr, dynamicApr: '', apr: currentApr });
  };

  return (
    <div style={{ marginTop: 4 }}>
      <MortgageFormGroup theme={theme} title="Core Details">
        <FormField theme={theme} label="Linked Property">
          <input
            value={form.property || ''}
            onChange={e => set('property', e.target.value)}
            placeholder="JVC Studio"
            style={inputStyle(theme)}
          />
        </FormField>
        <FormField theme={theme} label="Lender">
          <input
            value={form.lender || ''}
            onChange={e => set('lender', e.target.value)}
            placeholder="Mashreq"
            style={inputStyle(theme)}
          />
        </FormField>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <FormField theme={theme} label="Original Amount">
            <input
              value={form.originalAmount || ''}
              onChange={e => set('originalAmount', cleanMortgageMoney(e.target.value))}
              placeholder="480000"
              inputMode="numeric"
              style={inputStyle(theme)}
            />
          </FormField>
          <FormField theme={theme} label="Start Date">
            <input
              type="date"
              value={form.startDate || ''}
              onChange={e => set({ startDate: e.target.value, originationDate: e.target.value })}
              style={inputStyle(theme)}
            />
          </FormField>
        </div>
        <FormField theme={theme} label="Term (Years)">
          <input
            value={form.termYears || ''}
            onChange={e => {
              const termYears = cleanMortgageYears(e.target.value);
              set({ termYears, term: termYears ? `${termYears} years` : '' });
            }}
            placeholder="25"
            inputMode="numeric"
            style={inputStyle(theme)}
          />
        </FormField>
      </MortgageFormGroup>

      <MortgageFormGroup theme={theme} title="Rate Structure">
        <MortgageRateTypeFields
          theme={theme}
          accent={accent}
          fields={form}
          rateType={rateType}
          onRateTypeChange={v => set(getMortgageRateTypePatch(form, v))}
          onFixedPeriodYearsChange={v => set('fixedPeriodYears', v)}
          onFixedAprChange={setFixedApr}
          onCurrentAprChange={setCurrentApr}
        />
      </MortgageFormGroup>

      <MortgageFormGroup theme={theme} title="Current Status">
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <FormField theme={theme} label="Outstanding Balance (AED)">
            <input
              value={form.balance || ''}
              onChange={e => set('balance', cleanMortgageMoney(e.target.value))}
              placeholder="460000"
              inputMode="numeric"
              style={inputStyle(theme)}
            />
          </FormField>
          <FormField theme={theme} label="Monthly Payment (AED)">
            <input
              value={form.monthlyPayment || ''}
              onChange={e => set('monthlyPayment', cleanMortgageMoney(e.target.value))}
              placeholder="2840"
              inputMode="numeric"
              style={inputStyle(theme)}
            />
          </FormField>
        </div>
      </MortgageFormGroup>

      <MortgageFormGroup theme={theme} title="Payment Day">
        <FormField theme={theme} label="Payment Day">
          <input
            value={form.paymentDay || ''}
            onChange={e => set('paymentDay', e.target.value)}
            placeholder="1st"
            style={inputStyle(theme)}
          />
        </FormField>
      </MortgageFormGroup>
    </div>
  );
}

function ManualLoanLiabilityForm({ theme, form, set, loanKind }) {
  return (
    <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <Field label="Lender" theme={theme}
        value={form.lender || ''} onChange={v => set('lender', v)} placeholder={loanKind === 'car' ? 'ADCB Auto Finance' : 'Mashreq Personal Loan'}/>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="Outstanding balance" prefix={<Dh/>} theme={theme}
          value={form.balance || ''} onChange={v => set('balance', cleanMoney(v))} placeholder="18400"/>
        <Field label="Original amount" prefix={<Dh/>} theme={theme}
          value={form.originalAmount || ''} onChange={v => set('originalAmount', cleanMoney(v))} placeholder="35000"/>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="APR" suffix="%" theme={theme}
          value={form.apr || ''} onChange={v => set('apr', cleanRate(v))} placeholder="6.80"/>
        <Field label="Monthly payment" prefix={<Dh/>} theme={theme}
          value={form.monthlyPayment || ''} onChange={v => set('monthlyPayment', cleanMoney(v))} placeholder="920"/>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="Term" theme={theme}
          value={form.term || ''} onChange={v => set('term', v)} placeholder="4 years"/>
        <Field label="Payoff date" theme={theme}
          value={form.payoffDate || ''} onChange={v => set('payoffDate', v)} placeholder="Nov 2027"/>
      </div>
    </div>
  );
}

function ManualCardLiabilityForm({ theme, form, set }) {
  return (
    <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="Issuer" theme={theme}
          value={form.issuer || ''} onChange={v => set('issuer', v)} placeholder="Emirates NBD"/>
        <Field label="Card digits" theme={theme}
          value={form.last || ''} onChange={v => set('last', v)} placeholder="•• 4821"/>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="Outstanding balance" prefix={<Dh/>} theme={theme}
          value={form.balance || ''} onChange={v => set('balance', cleanMoney(v))} placeholder="4420"/>
        <Field label="Credit limit" prefix={<Dh/>} theme={theme}
          value={form.limit || ''} onChange={v => set('limit', cleanMoney(v))} placeholder="30000"/>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="APR" suffix="%" theme={theme}
          value={form.apr || ''} onChange={v => set('apr', cleanRate(v))} placeholder="36.00"/>
        <Field label="Min payment" prefix={<Dh/>} theme={theme}
          value={form.minPayment || ''} onChange={v => set('minPayment', cleanMoney(v))} placeholder="220"/>
      </div>
      <Field label="Payment due date" theme={theme}
        value={form.statementDate || ''} onChange={v => set('statementDate', v)} placeholder="5th"/>
    </div>
  );
}

function ManualCustomLiabilityForm({ theme, form, set }) {
  return (
    <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <Field label="Name" theme={theme}
        value={form.name || ''} onChange={v => set('name', v)} placeholder="Family loan"/>
      <Field label="Outstanding balance" prefix={<Dh/>} theme={theme}
        value={form.balance || ''} onChange={v => set('balance', cleanMoney(v))} placeholder="0"/>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="APR" suffix="%" theme={theme}
          value={form.apr || ''} onChange={v => set('apr', cleanRate(v))} placeholder="0.0"/>
        <Field label="Monthly payment" prefix={<Dh/>} theme={theme}
          value={form.monthlyPayment || ''} onChange={v => set('monthlyPayment', cleanMoney(v))} placeholder="0"/>
      </div>
      <Field label="Payoff date" theme={theme}
        value={form.payoffDate || ''} onChange={v => set('payoffDate', v)} placeholder="Mar 2030"/>
    </div>
  );
}

function LiabilitySegmentedRow({ theme, accent, value, options, onChange }) {
  return (
    <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
      {options.map((o) => {
        const active = o === value;
        return (
          <button
            key={o}
            onClick={() => onChange(o)}
            style={{
              background: active ? theme.text : theme.surface2,
              color: active ? theme.bg : theme.text,
              border: `0.5px solid ${active ? theme.text : theme.line2}`,
              borderRadius: 999,
              padding: '7px 12px',
              fontFamily: FONTS.ui,
              fontSize: 12,
              fontWeight: 500,
              cursor: 'pointer',
              whiteSpace: 'nowrap',
            }}
          >
            {o}
          </button>
        );
      })}
    </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 });
