// screen-budget-goals.jsx — Budget & Tabungan/Goals

// ─── BUDGET ──────────────────────────────────────────────────────
function ScreenBudget({ theme, accent, scenario, auth }) {
  const [realBudgets, setRealBudgets] = React.useState(null);
  const familyId = auth && auth.family && auth.family.id;
  React.useEffect(function() {
    if (!familyId || !window.sbGetBudgets) return;
    sbGetBudgets(familyId).then(function(r){ if(!r.error) setRealBudgets(r.data||[]); });
  }, [familyId]);

  const isAuth = !!(auth && auth.family);

  // Normalize budget shape: real data (budget_usage view) vs dummy
  function normBudget(b) {
    if (b.amount_limit !== undefined) {
      // Real data from budget_usage view
      return {
        id:    b.budget_id,
        cat:   (b.category_name||'').toLowerCase().replace(/\s+/g,'_') || 'lainnya_ex',
        catName: b.category_name || 'Lainnya',
        catColor: b.category_color || '#6366f1',
        limit: b.amount_limit,
        used:  b.used_amount || 0,
        pct:   b.used_pct || 0,
        isReal: true,
      };
    }
    return Object.assign({}, b, {catName: (CATEGORIES[b.cat]||{}).label||b.cat, catColor:(CATEGORIES[b.cat]||{}).color||'#6366f1', isReal:false});
  }

  const budgets = (isAuth ? (realBudgets||[]) : scenario.budgets).map(normBudget);
  const totalLimit = budgets.reduce((a, b) => a + b.limit, 0);
  const totalUsed  = budgets.reduce((a, b) => a + b.used, 0);
  const remaining  = totalLimit - totalUsed;
  const pct = totalLimit > 0 ? Math.round((totalUsed / totalLimit) * 100) : 0;

  const [showAdd, setShowAdd] = React.useState(false);
  const [addCat, setAddCat] = React.useState('');
  const [addLimit, setAddLimit] = React.useState('');
  const [saving, setSaving] = React.useState(false);

  async function handleAddBudget() {
    if (!addCat || !addLimit) return;
    setSaving(true);
    var amount = parseInt(addLimit.replace(/\D/g,''), 10);
    if (window.sbAddBudget && auth && auth.family) {
      await sbAddBudget(auth.family.id, addCat, amount, 80);
      if (window.sbGetBudgets) {
        var r = await sbGetBudgets(auth.family.id);
        if (!r.error) setRealBudgets(r.data||[]);
      }
    }
    setShowAdd(false); setAddCat(''); setAddLimit(''); setSaving(false);
  }

  return (
    <div style={{ background: theme.bg, paddingBottom: 100 }}>
      {/* Header */}
      <div style={{ padding: '56px 20px 16px',
                    display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 28, fontWeight: 800,
                       letterSpacing: '-0.025em', color: theme.fg1 }}>Budget</h1>
          <div style={{ fontSize: 12, color: theme.fg3, fontWeight: 500, marginTop: 2 }}>
            Mei 2026 · {budgets.length} kategori
          </div>
        </div>
        <button style={iconBtn2(theme)} onClick={() => setShowAdd(true)}>
          <Icon name="plus" size={18} color={theme.fg1} stroke={2} />
        </button>
      </div>

      {/* Summary card */}
      <div style={{ padding: '0 20px 20px' }}>
        <Card theme={theme} padding={20}>
          <div style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
            marginBottom: 14,
          }}>
            <div>
              <div style={{ fontSize: 12, color: theme.fg3, fontWeight: 600,
                            letterSpacing: '0.02em', marginBottom: 2 }}>
                Sisa budget bulan ini
              </div>
              <div style={{
                fontSize: 28, fontWeight: 800, color: theme.fg1,
                letterSpacing: '-0.025em', fontVariantNumeric: 'tabular-nums',
              }}>{fmtRp(remaining)}</div>
              <div style={{ fontSize: 12, color: theme.fg2, fontWeight: 500, marginTop: 2 }}>
                dari {fmtRp(totalLimit, { short: true })} budget total
              </div>
            </div>
            <div style={{
              padding: '6px 12px', borderRadius: 999,
              background: pct >= 90 ? theme.dangerSoft
                : pct >= 75 ? theme.warningSoft : theme.accent.tint,
              color: pct >= 90 ? theme.danger
                : pct >= 75 ? theme.warning : theme.accent[600],
              fontSize: 13, fontWeight: 700,
              fontVariantNumeric: 'tabular-nums',
            }}>{pct}%</div>
          </div>
          {/* Segmented progress: each segment is a category */}
          <div style={{ display: 'flex', gap: 2, height: 8, borderRadius: 4, overflow: 'hidden' }}>
            {budgets.map((b, i) => {
              const c = b.isReal ? {color: b.catColor, label: b.catName} : (CATEGORIES[b.cat]||{color:'#6366f1',label:b.cat});
              const w = (b.limit / totalLimit) * 100;
              const usedPct = Math.min(1, b.used / b.limit);
              return (
                <div key={b.cat} style={{
                  width: w + '%', height: '100%',
                  background: theme.surfaceAlt, position: 'relative',
                }}>
                  <div style={{
                    height: '100%', width: (usedPct * 100) + '%',
                    background: c.color, opacity: 0.85,
                  }} />
                </div>
              );
            })}
          </div>
          <div style={{
            marginTop: 10, paddingTop: 10,
            borderTop: `0.5px dashed ${theme.border}`,
            display: 'flex', justifyContent: 'space-around',
            fontSize: 11, fontWeight: 500, color: theme.fg2,
          }}>
            <StatPair label="Terpakai" value={fmtRp(totalUsed, { short: true })} theme={theme} />
            <div style={{ width: 1, background: theme.border }} />
            <StatPair label="14 hari sisa" value="14 hari" theme={theme} />
            <div style={{ width: 1, background: theme.border }} />
            <StatPair label="Per hari" value={fmtRp(remaining / 14, { short: true }) + '/hari'} theme={theme} />
          </div>
        </Card>
      </div>

      {/* Per-category list */}
      <SectionHeader title="Per kategori" action="Atur" theme={theme} />
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {budgets.length === 0 ? (
          <div style={{textAlign:'center',padding:'40px 0',color:theme.fg4}}>
            <div style={{fontSize:40,marginBottom:12}}>🎯</div>
            <div style={{fontSize:14,fontWeight:600}}>Belum ada budget</div>
            <div style={{fontSize:12,marginTop:4}}>Tap + untuk atur budget per kategori</div>
          </div>
        ) : budgets.map((b) => {
          const c = b.isReal ? {color: b.catColor, label: b.catName} : (CATEGORIES[b.cat]||{color:'#6366f1',label:b.cat});
          const pct = (b.used / b.limit) * 100;
          const isOver = pct > 100;
          const left = b.limit - b.used;
          return (
            <Card key={b.cat} theme={theme} padding={14}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
                <CatDisc cat={c} size={40} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: theme.fg1,
                                letterSpacing: '-0.005em' }}>{c.label}</div>
                  <div style={{ fontSize: 11, color: theme.fg3, fontWeight: 500, marginTop: 1 }}>
                    {isOver
                      ? <span style={{ color: theme.danger, fontWeight: 700 }}>Over Rp {Math.abs(left).toLocaleString('id-ID')}</span>
                      : <>Sisa <strong style={{ color: theme.fg2 }}>{fmtRp(left, { short: true })}</strong></>}
                  </div>
                </div>
                <div style={{
                  fontSize: 14, fontWeight: 800, color: theme.fg1,
                  fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.01em',
                  textAlign: 'right',
                }}>
                  <div>{fmtRp(b.used, { short: true })}</div>
                  <div style={{ fontSize: 11, color: theme.fg3, fontWeight: 500 }}>
                    / {fmtRp(b.limit, { short: true })}
                  </div>
                </div>
              </div>
              <ProgressBar value={b.used} max={b.limit} theme={theme} height={6} />
            </Card>
          );
        }) }
        )}
      </div>

      {/* Add Budget Modal */}
      {showAdd && (
        <div style={{position:'fixed',inset:0,zIndex:200,background:'rgba(0,0,0,0.5)',display:'flex',alignItems:'flex-end',justifyContent:'center'}}
          onClick={e => { if(e.target===e.currentTarget) setShowAdd(false); }}>
          <div style={{background:theme.surface,borderRadius:'24px 24px 0 0',padding:'24px 20px 48px',width:'100%',maxWidth:480}}>
            <div style={{width:40,height:4,background:theme.border,borderRadius:99,margin:'0 auto 20px'}}/>
            <div style={{fontSize:18,fontWeight:800,color:theme.fg1,marginBottom:16}}>Set Budget</div>
            <div style={{marginBottom:12}}>
              <div style={{fontSize:12,fontWeight:600,color:theme.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Kategori</div>
              <select value={addCat} onChange={e=>setAddCat(e.target.value)}
                style={{width:'100%',height:48,borderRadius:12,border:'1.5px solid '+theme.border,background:theme.bg,color:theme.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}>
                <option value="">-- Pilih kategori --</option>
                {Object.entries(CATEGORIES).filter(function([k,v]){return v.kind==='expense';}).map(function([k,v]){
                  return <option key={k} value={k}>{v.label}</option>;
                })}
              </select>
            </div>
            <div style={{marginBottom:16}}>
              <div style={{fontSize:12,fontWeight:600,color:theme.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Batas per Bulan</div>
              <div style={{display:'flex',alignItems:'center',gap:8,background:theme.bg,border:'1.5px solid '+theme.border,borderRadius:12,padding:'0 14px'}}>
                <span style={{color:theme.fg3,fontSize:13}}>Rp</span>
                <input type="text" inputMode="numeric" placeholder="500.000" value={addLimit}
                  onChange={e=>setAddLimit(parseInt(e.target.value.replace(/\D/g,'')||'0').toLocaleString('id-ID'))}
                  style={{flex:1,height:48,border:0,outline:'none',background:'transparent',fontSize:16,fontWeight:700,color:theme.fg1,fontFamily:'inherit'}}/>
              </div>
            </div>
            <button onClick={handleAddBudget} disabled={!addCat||!addLimit||saving}
              style={{width:'100%',height:50,borderRadius:14,border:0,cursor:'pointer',
                background:addCat&&addLimit&&!saving?'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')'+'':'#ccc',
                color:'#fff',fontSize:15,fontWeight:700}}>
              {saving ? 'Menyimpan...' : '✓ Simpan Budget'}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function StatPair({ label, value, theme }) {
  return (
    <div style={{ flex: 1, textAlign: 'center' }}>
      <div style={{ fontSize: 10, color: theme.fg3, fontWeight: 500, marginBottom: 2,
                    textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
      <div style={{ fontSize: 12, fontWeight: 700, color: theme.fg1,
                    fontVariantNumeric: 'tabular-nums' }}>{value}</div>
    </div>
  );
}

// ─── GOALS / TABUNGAN ────────────────────────────────────────────
function ScreenGoals({ theme, accent, scenario, auth }) {
  const [realGoals, setRealGoals] = React.useState(null);
  const familyId = auth && auth.family && auth.family.id;
  React.useEffect(function() {
    if (!familyId || !window.sbGetGoals) return;
    sbGetGoals(familyId).then(function(r){ if(!r.error) setRealGoals(r.data||[]); });
  }, [familyId]);

  const isAuth = !!(auth && auth.family);
  const [showAddGoal, setShowAddGoal] = React.useState(false);
  const [goalName, setGoalName] = React.useState('');
  const [goalEmoji, setGoalEmoji] = React.useState('🎯');
  const [goalTarget, setGoalTarget] = React.useState('');
  const [goalDate, setGoalDate] = React.useState('');
  const [savingGoal, setSavingGoal] = React.useState(false);

  async function handleAddGoal() {
    if (!goalName || !goalTarget) return;
    setSavingGoal(true);
    var amount = parseInt(goalTarget.replace(/\D/g,''), 10);
    if (window.sbAddGoal && auth && auth.family && auth.user) {
      await sbAddGoal(auth.family.id, auth.user.id, {
        name: goalName, emoji: goalEmoji,
        target: amount, due: goalDate || null,
      });
      var r = await sbGetGoals(auth.family.id);
      if (!r.error) setRealGoals(r.data||[]);
    }
    setShowAddGoal(false); setGoalName(''); setGoalTarget(''); setGoalDate('');
    setSavingGoal(false);
  }

  // Normalize goal shape: Supabase vs dummy
  function normGoal(g) {
    if (g.target_amount !== undefined) {
      return {
        id:       g.id,
        name:     g.name,
        emoji:    g.icon || '🎯',
        target:   g.target_amount,
        saved:    g.current_amount || 0,
        due:      g.target_date || new Date(Date.now() + 365*24*3600*1000).toISOString(),
        contribs: [],
        isReal:   true,
      };
    }
    return g;
  }

  const goals = (isAuth ? (realGoals||[]) : scenario.goals).map(normGoal);
  const totalSaved  = goals.reduce((a, g) => a + g.saved, 0);
  const totalTarget = goals.reduce((a, g) => a + g.target, 0);

  return (
    <div style={{ background: theme.bg, paddingBottom: 100 }}>
      {/* Header */}
      <div style={{ padding: '56px 20px 16px',
                    display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
        <div>
          <h1 style={{ margin: 0, fontSize: 28, fontWeight: 800,
                       letterSpacing: '-0.025em', color: theme.fg1 }}>Tabungan</h1>
          <div style={{ fontSize: 12, color: theme.fg3, fontWeight: 500, marginTop: 2 }}>
            {goals.length} tujuan keluarga
          </div>
        </div>
        <button style={iconBtn2(theme)} onClick={() => setShowAddGoal(true)}>
          <Icon name="plus" size={18} color={theme.fg1} stroke={2} />
        </button>
      </div>

      {/* Summary hero */}
      <div style={{ padding: '0 20px 22px' }}>
        <div style={{
          position: 'relative', overflow: 'hidden',
          background: `linear-gradient(135deg, ${accent.grad[0]}, ${accent.grad[1]})`,
          color: '#fff', borderRadius: 22, padding: 20,
          boxShadow: `0 10px 32px ${accent[500]}55`,
        }}>
          <div style={{
            position: 'absolute', right: -30, top: -30,
            width: 140, height: 140, borderRadius: '50%',
            background: 'rgba(255,255,255,0.10)',
          }} />
          <div style={{ position: 'relative', zIndex: 1 }}>
            <div style={{ fontSize: 12, opacity: 0.85, fontWeight: 600,
                          letterSpacing: '0.04em', textTransform: 'uppercase' }}>
              Total terkumpul
            </div>
            <div style={{
              fontSize: 30, fontWeight: 800, letterSpacing: '-0.025em',
              marginTop: 4, fontVariantNumeric: 'tabular-nums',
            }}>{fmtRp(totalSaved)}</div>
            <div style={{ fontSize: 13, opacity: 0.85, fontWeight: 500, marginTop: 2 }}>
              dari target {fmtRp(totalTarget, { short: true })}
            </div>
            <div style={{ height: 6, background: 'rgba(255,255,255,0.2)', borderRadius: 4,
                          marginTop: 14, overflow: 'hidden' }}>
              <div style={{
                width: `${totalTarget > 0 ? (totalSaved / totalTarget) * 100 : 0}%`, height: '100%',
                background: '#fff', borderRadius: 4,
              }} />
            </div>
          </div>
        </div>
      </div>

      {/* Goals list */}
      <div style={{ padding: '0 20px', display: 'flex', flexDirection: 'column', gap: 14 }}>
        {goals.length === 0 ? (
          <div style={{textAlign:'center',padding:'40px 0',color:theme.fg4}}>
            <div style={{fontSize:40,marginBottom:12}}>🐷</div>
            <div style={{fontSize:14,fontWeight:600}}>Belum ada goals tabungan</div>
            <div style={{fontSize:12,marginTop:4}}>Tap + untuk tambah goals pertama</div>
          </div>
        ) : goals.map((g) => (
          <GoalCard key={g.id} goal={g} scenario={scenario} theme={theme} accent={accent} />
        ))}
        ) }
      </div>

      {/* Add Goal Modal */}
      {showAddGoal && (
        <div style={{position:'fixed',inset:0,zIndex:200,background:'rgba(0,0,0,0.5)',display:'flex',alignItems:'flex-end',justifyContent:'center'}}
          onClick={e => { if(e.target===e.currentTarget) setShowAddGoal(false); }}>
          <div style={{background:theme.surface,borderRadius:'24px 24px 0 0',padding:'24px 20px 48px',width:'100%',maxWidth:480}}>
            <div style={{width:40,height:4,background:theme.border,borderRadius:99,margin:'0 auto 20px'}}/>
            <div style={{fontSize:18,fontWeight:800,color:theme.fg1,marginBottom:16}}>Tambah Goal</div>
            <div style={{display:'flex',gap:8,flexWrap:'wrap',marginBottom:12}}>
              {['🎯','🏠','🚗','✈️','🎓','💍','📱','💻','🏖️','💰','🐷','🎸'].map(function(e){
                return <button key={e} onClick={()=>setGoalEmoji(e)}
                  style={{width:40,height:40,borderRadius:10,fontSize:20,border:'2px solid '+(goalEmoji===e?accent[500]:theme.border),background:goalEmoji===e?accent.tint:'transparent',cursor:'pointer'}}>{e}</button>;
              })}
            </div>
            <div style={{marginBottom:12}}>
              <div style={{fontSize:12,fontWeight:600,color:theme.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Nama Goal</div>
              <input type="text" placeholder="Misal: DP Rumah, Liburan Bali..." value={goalName}
                onChange={e=>setGoalName(e.target.value)} autoFocus
                style={{width:'100%',height:48,borderRadius:12,border:'1.5px solid '+theme.border,background:theme.bg,color:theme.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}/>
            </div>
            <div style={{marginBottom:12}}>
              <div style={{fontSize:12,fontWeight:600,color:theme.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Target Dana</div>
              <div style={{display:'flex',alignItems:'center',gap:8,background:theme.bg,border:'1.5px solid '+theme.border,borderRadius:12,padding:'0 14px'}}>
                <span style={{color:theme.fg3,fontSize:13}}>Rp</span>
                <input type="text" inputMode="numeric" placeholder="10.000.000" value={goalTarget}
                  onChange={e=>setGoalTarget(parseInt(e.target.value.replace(/\D/g,'')||'0').toLocaleString('id-ID'))}
                  style={{flex:1,height:48,border:0,outline:'none',background:'transparent',fontSize:16,fontWeight:700,color:theme.fg1,fontFamily:'inherit'}}/>
              </div>
            </div>
            <div style={{marginBottom:16}}>
              <div style={{fontSize:12,fontWeight:600,color:theme.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Target Tanggal (opsional)</div>
              <input type="date" value={goalDate} onChange={e=>setGoalDate(e.target.value)}
                style={{width:'100%',height:48,borderRadius:12,border:'1.5px solid '+theme.border,background:theme.bg,color:theme.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}/>
            </div>
            <button onClick={handleAddGoal} disabled={!goalName||!goalTarget||savingGoal}
              style={{width:'100%',height:50,borderRadius:14,border:0,cursor:'pointer',
                background:goalName&&goalTarget&&!savingGoal?'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')':'#ccc',
                color:'#fff',fontSize:15,fontWeight:700}}>
              {savingGoal ? 'Menyimpan...' : goalEmoji+' Buat Goal'}
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function GoalCard({ goal, scenario, theme, accent }) {
  const pct = Math.min(100, (goal.saved / goal.target) * 100);
  const remaining = goal.target - goal.saved;
  const due = new Date(goal.due);
  const daysLeft = Math.max(0, Math.round((due - new Date()) / 86400000));
  const monthsLeft = Math.round(daysLeft / 30);
  const monthly = monthsLeft > 0 ? remaining / monthsLeft : 0;

  const contribMembers = (goal.contribs||[]).map((c) =>
    scenario.members.find((m) => m.id === c.m)
  ).filter(Boolean);

  return (
    <Card theme={theme} padding={18}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, marginBottom: 14 }}>
        <div style={{
          width: 56, height: 56, borderRadius: 18,
          background: theme.surfaceAlt,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 32, lineHeight: 1, flexShrink: 0,
        }}>{goal.emoji}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{
            fontSize: 16, fontWeight: 700, color: theme.fg1,
            letterSpacing: '-0.01em',
          }}>{goal.name}</div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 6,
            fontSize: 11, color: theme.fg3, fontWeight: 500, marginTop: 4,
          }}>
            <Icon name="calendar" size={12} stroke={1.85} />
            <span>{monthsLeft > 0 ? `${monthsLeft} bulan lagi` : 'Sudah jatuh tempo'}</span>
            <span>·</span>
            <span>{fmtDate(goal.due)} {due.getFullYear()}</span>
          </div>
        </div>
      </div>

      {/* Amount + progress */}
      <div style={{
        display: 'flex', justifyContent: 'space-between', alignItems: 'baseline',
        marginBottom: 8,
      }}>
        <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
          <span style={{
            fontSize: 20, fontWeight: 800, color: theme.fg1,
            letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums',
          }}>{fmtRp(goal.saved, { short: true })}</span>
          <span style={{ fontSize: 12, color: theme.fg3, fontWeight: 500 }}>
            / {fmtRp(goal.target, { short: true })}
          </span>
        </div>
        <Badge theme={theme} color={pct >= 90 ? 'success' : 'accent'}>
          {Math.round(pct)}%
        </Badge>
      </div>
      <ProgressBar value={goal.saved} max={goal.target} theme={theme} height={8}
                   color={accent[500]} />

      {/* Footer: contributors + monthly need */}
      <div style={{
        marginTop: 12, paddingTop: 12,
        borderTop: `0.5px dashed ${theme.border}`,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <AvatarStack members={contribMembers} size={22} ringColor={theme.surface} />
          <span style={{ fontSize: 11, color: theme.fg2, fontWeight: 600 }}>
            {contribMembers.length} kontributor
          </span>
        </div>
        {monthsLeft > 0 && (
          <div style={{
            fontSize: 11, color: theme.fg3, fontWeight: 500,
            display: 'flex', alignItems: 'center', gap: 4,
          }}>
            <Icon name="zap" size={12} color={accent[600]} stroke={2} />
            <span style={{ color: theme.fg2, fontWeight: 700 }}>
              {fmtRp(monthly, { short: true })}/bln
            </span>
          </div>
        )}
      </div>
    </Card>
  );
}

Object.assign(window, { ScreenBudget, ScreenGoals });
