// Add goal — bottom sheet flow (template → details → confirm)

function AddGoalModal({ theme, accent, open, onClose }) {
  // step:
  //   pick    → template picker
  //   payoff  → liability picker (only for payoff_debt template)
  //   form    → target amount + date + monthly contribution
  //   review  → confirm + Himma's required-monthly suggestion
  const [step, setStep] = React.useState('pick');
  const [template, setTemplate] = React.useState(null);
  const [liab, setLiab] = React.useState(null);
  const [form, setForm] = React.useState({ amount: '', months: '', monthly: '' });

  React.useEffect(() => {
    if (!open) {
      setTimeout(() => {
        setStep('pick'); setTemplate(null); setLiab(null);
        setForm({ amount: '', months: '', monthly: '' });
      }, 300);
    }
  }, [open]);

  const pickTemplate = (t) => {
    setTemplate(t);
    if (t.id === 'payoff_debt') {
      setStep('payoff');
    } else {
      // Seed defaults from template
      setForm({
        amount: t.defaultAmount ? String(t.defaultAmount) : '',
        months: t.defaultMonths ? String(t.defaultMonths) : '',
        monthly: t.defaultAmount && t.defaultMonths
          ? String(Math.round(t.defaultAmount / t.defaultMonths))
          : '',
      });
      setStep('form');
    }
  };

  const pickLiability = (l) => {
    setLiab(l);
    setForm({
      amount: String(l.balance),
      months: '36',
      monthly: String(Math.round(l.balance / 36)),
    });
    setStep('form');
  };

  const goReview = () => setStep('review');

  if (!open) return null;

  // Build flat liability options for the payoff picker
  const allLiabilities = [
    ...LIABILITIES.loans.map(l => ({ id: l.id, name: l.lender, sub: `${LOAN_KIND_LABELS[l.kind]} · ${l.apr.toFixed(1)}% APR`, balance: l.balance })),
    ...LIABILITIES.credit_cards.map(c => ({ id: c.id, name: c.issuer, sub: `Credit card · ${c.apr.toFixed(0)}% APR`, balance: c.balance })),
    ...LIABILITIES.mortgages.map(m => ({ id: m.id, name: m.lender, sub: `Mortgage · ${m.apr.toFixed(2)}% APR`, balance: m.balance })),
  ];

  // For review step
  const amount = Number(form.amount) || 0;
  const months = Number(form.months) || 12;
  const monthly = Number(form.monthly) || 0;
  const requiredMonthly = amount / months;
  const onPace = monthly >= requiredMonthly;

  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 }}>Set a goal</div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>
              Pick a template — Himma will suggest a savings rate.
            </div>

            <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {GOAL_TEMPLATES.map(t => {
                const Icon = Ico[t.icon] || Ico.target;
                return (
                  <button key={t.id} onClick={() => pickTemplate(t)} style={{
                    background: theme.surface2, border: `0.5px solid ${theme.line}`, borderRadius: 14,
                    padding: '14px 12px', display:'flex', flexDirection:'column', alignItems:'flex-start', gap: 8,
                    cursor: 'pointer', textAlign: 'left', color: theme.text,
                  }}>
                    <div style={{ width: 32, height: 32, borderRadius: 10, background: theme.surface3, color: accent, display:'flex', alignItems:'center', justifyContent:'center' }}>
                      <Icon size={15}/>
                    </div>
                    <div style={{ fontSize: 12.5, fontWeight: 500, lineHeight: 1.2 }}>{t.label}</div>
                    <div style={{ fontFamily: FONTS.mono, fontSize: 9.5, color: theme.textMute, lineHeight: 1.3 }}>{t.sub}</div>
                  </button>
                );
              })}
            </div>
          </>
        )}

        {step === 'payoff' && (
          <>
            <BackBtn theme={theme} onClick={() => setStep('pick')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>Pick a debt to pay off</div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>
              Driving these to zero compounds — high-APR first usually wins.
            </div>

            <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {allLiabilities.map(l => (
                <button key={l.id} onClick={() => pickLiability(l)} style={{
                  background: theme.surface2, border: `0.5px solid ${theme.line}`, borderRadius: 12,
                  padding: '12px 14px', display:'flex', alignItems:'center', gap: 12,
                  cursor: 'pointer', textAlign: 'left', color: theme.text,
                }}>
                  <div style={{
                    width: 34, height: 34, borderRadius: 9, background: theme.surface3,
                    display:'flex', alignItems:'center', justifyContent:'center',
                    fontFamily: FONTS.display, fontSize: 12, color: theme.text, flexShrink: 0,
                  }}>{l.name.split(' ').map(w => w[0]).join('').slice(0, 2).toUpperCase()}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{l.name}</div>
                    <div style={{ fontFamily: FONTS.mono, fontSize: 10.5, color: theme.textMute, marginTop: 2 }}>{l.sub}</div>
                  </div>
                  <div style={{ fontFamily: FONTS.mono, fontSize: 13, color: theme.text, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>
                    <Dh/> {fmtAED(l.balance, {compact: true})}
                  </div>
                </button>
              ))}
            </div>
          </>
        )}

        {step === 'form' && template && (
          <>
            <BackBtn theme={theme} onClick={() => setStep(template.id === 'payoff_debt' ? 'payoff' : 'pick')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>{template.label}</div>
            <div style={{ fontSize: 12.5, color: theme.textDim, marginTop: 4, fontFamily: FONTS.ui }}>
              {liab ? <>{liab.name} · current balance <Dh/> {fmtAED(liab.balance, {compact: true})}</> : dhText(template.sub)}
            </div>

            <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 12 }}>
              <Field label={template.kind === 'payoff' ? 'Pay-off target' : 'Target amount'}
                prefix={<Dh/>} theme={theme} value={form.amount}
                onChange={v => setForm({ ...form, amount: v })} placeholder="0"/>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <Field label="Timeline" suffix="months" theme={theme}
                  value={form.months} onChange={v => setForm({ ...form, months: v })} placeholder="12"/>
                <Field label="Monthly contribution" prefix={<Dh/>} theme={theme}
                  value={form.monthly} onChange={v => setForm({ ...form, monthly: v })} placeholder="0"/>
              </div>
            </div>

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

        {step === 'review' && template && (
          <>
            <BackBtn theme={theme} onClick={() => setStep('form')}/>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 10 }}>Review</div>

            <div style={{ marginTop: 16 }}>
              <Card theme={theme} style={{ padding: 16, background: `linear-gradient(155deg, ${theme.surface2}, ${theme.surface})` }}>
                <SectionLabel theme={theme}>Goal</SectionLabel>
                <div style={{ fontFamily: FONTS.display, fontSize: 19, color: theme.text, letterSpacing: -0.3, marginTop: 4 }}>{template.label}</div>
                <div style={{ fontFamily: FONTS.mono, fontSize: 11, color: theme.textMute, marginTop: 6 }}>
                  <Dh/> {fmtAED(amount)} in {months} months
                </div>
              </Card>
            </div>

            <div style={{ marginTop: 12 }}>
              <Card theme={theme} style={{ padding: 16 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                  <Ico.sparkles size={12} stroke={accent}/>
                  <SectionLabel theme={theme}>Himma suggests</SectionLabel>
                </div>
                <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, letterSpacing: -0.4 }}>
                  <Dh/> {fmtAED(requiredMonthly, {decimals: 0})}/mo
                </div>
                <div style={{ fontFamily: FONTS.mono, fontSize: 11, color: theme.textDim, marginTop: 6 }}>
                  to hit <Dh/> {fmtAED(amount)} in {months} months
                </div>
                <div style={{ marginTop: 10, padding: '10px 12px', background: theme.surface2, borderRadius: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{
                    width: 8, height: 8, borderRadius: 4,
                    background: onPace ? theme.positive : theme.warning,
                    flexShrink: 0,
                  }}/>
                  <span style={{ fontFamily: FONTS.mono, fontSize: 10.5, color: theme.textDim, letterSpacing: 0.2 }}>
                    {onPace
                      ? <>Your <Dh/> {fmtAED(monthly)}/mo plan stays on pace.</>
                      : <>Your <Dh/> {fmtAED(monthly)}/mo plan is short by <Dh/> {fmtAED(requiredMonthly - monthly)}/mo.</>}
                  </span>
                </div>
              </Card>
            </div>

            <button onClick={onClose} style={{
              marginTop: 18, width: '100%',
              background: accent, color: theme.bg, border: 'none',
              padding: '14px', borderRadius: 14,
              fontFamily: FONTS.ui, fontSize: 14, fontWeight: 600, cursor: 'pointer',
            }}>Create goal</button>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AddGoalModal });
