// screen-settings.jsx

// ─── ACCOUNTS (Kekayaan Bersih) ───────────────────────────────────
function ScreenAccounts({ theme, accent, auth }) {
  var T = theme;
  var _s1 = React.useState(null), accounts = _s1[0], setAccounts = _s1[1];
  var _s2 = React.useState(false), showAdd = _s2[0], setShowAdd = _s2[1];
  var _s3 = React.useState(null), editAcc = _s3[0], setEditAcc = _s3[1];
  var _s4 = React.useState(null), wealth = _s4[0], setWealth = _s4[1];
  var _s5 = React.useState(null), monthFlow = _s5[0], setMonthFlow = _s5[1];
  var _s6 = React.useState(null), updateValAcc = _s6[0], setUpdateValAcc = _s6[1];
  var familyId = auth && auth.family && auth.family.id;

  React.useEffect(function() {
    if (!familyId || !window.SB) return;
    loadAll();
  }, [familyId]);

  async function loadAll() {
    // Load accounts dengan available balance view
    var r = await window.SB.from('account_available').select('*')
      .eq('family_id', familyId).order('type').order('name');
    if (!r.error) setAccounts(r.data || []);
    else {
      // Fallback ke tabel biasa kalau view belum ada
      var r2 = await window.SB.from('accounts').select('*')
        .eq('family_id', familyId).order('type').order('name');
      if (!r2.error) setAccounts((r2.data||[]).map(function(a){
        return Object.assign({}, a, {available_balance: a.balance, locked_in_goals: 0, unrealized_pnl: a.cost_basis > 0 ? a.balance - a.cost_basis : 0});
      }));
    }
    // Monthly cash flow dari transaksi
    var now = new Date();
    var start = now.getFullYear() + '-' + String(now.getMonth()+1).padStart(2,'0') + '-01';
    var rf = await window.SB.from('transactions').select('type,amount')
      .eq('family_id', familyId).gte('date', start);
    if (!rf.error) {
      var inc = (rf.data||[]).filter(function(t){return t.type==='income';}).reduce(function(s,t){return s+t.amount;},0);
      var exp = (rf.data||[]).filter(function(t){return t.type==='expense';}).reduce(function(s,t){return s+t.amount;},0);
      setMonthFlow({income:inc, expense:exp, net:inc-exp});
    }
  }

  var TYPE_INFO = {
    bank:       {label:'Rekening Bank',  icon:'🏦', color:'#3b82f6'},
    cash:       {label:'Uang Tunai',     icon:'💵', color:'#10b981'},
    investment: {label:'Investasi',      icon:'📈', color:'#8b5cf6'},
    ewallet:    {label:'E-Wallet',       icon:'📱', color:'#f59e0b'},
    credit:     {label:'Kartu Kredit',   icon:'💳', color:'#ef4444'},
  };

  var kas       = (accounts||[]).filter(function(a){return a.type==='bank'||a.type==='cash'||a.type==='ewallet';});
  var nonCredit = (accounts||[]).filter(function(a){return a.type!=='credit';});
  // grandTotal = kas (fisik total) + investasi - hutang KK
  var hutangKKtotal = (accounts||[]).filter(function(a){return a.type==='credit';}).reduce(function(s,a){return s+a.balance;},0);
  var grandTotal   = nonCredit.reduce(function(s,a){return s+a.balance;},0) - hutangKKtotal;
  // totalLocked = total pocket goals (hanya dari kas)
  var totalLocked  = kas.reduce(function(s,a){return s+(a.locked_in_goals||0);},0);
  // totalAvail = saldo kas yg bebas (saldo fisik - pocket), bukan termasuk investasi
  var totalKas     = kas.reduce(function(s,a){return s+a.balance;},0);
  // available_balance dari view = balance - locked_in_goals (sudah benar)
  var totalAvail   = kas.reduce(function(s,a){return s+(a.available_balance!==undefined ? a.available_balance : a.balance-( a.locked_in_goals||0));},0);
  var totalInvest  = (accounts||[]).filter(function(a){return a.type==='investment';}).reduce(function(s,a){return s+a.balance;},0);
  var totalPnl     = (accounts||[]).filter(function(a){return a.type==='investment'&&a.cost_basis>0;}).reduce(function(s,a){return s+a.unrealized_pnl;},0);

  var grouped = {};
  (accounts||[]).forEach(function(a){
    if(!grouped[a.type]) grouped[a.type]=[];
    grouped[a.type].push(a);
  });

  return (
    <div style={{background:T.bg, minHeight:'100%', paddingBottom:100}}>
      <div style={{padding:'56px 20px 16px', display:'flex', justifyContent:'space-between', alignItems:'flex-end'}}>
        <div>
          <h1 style={{margin:0, fontSize:28, fontWeight:800, color:T.fg1, letterSpacing:'-0.025em'}}>Kekayaan Bersih</h1>
          <div style={{fontSize:12, color:T.fg3, marginTop:2}}>Rekening, cash &amp; investasi</div>
        </div>
        <button onClick={function(){setEditAcc(null);setShowAdd(true);}}
          style={{width:36,height:36,borderRadius:12,border:0,cursor:'pointer',
            background:'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')',
            display:'flex',alignItems:'center',justifyContent:'center',fontSize:22,color:'#fff'}}>+</button>
      </div>

      {/* Net worth hero card */}
      <div style={{padding:'0 20px 16px'}}>
        <div style={{background:'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')',
          borderRadius:22, padding:20, color:'#fff', boxShadow:'0 10px 32px '+accent[500]+'44'}}>
          <div style={{fontSize:11,opacity:0.8,fontWeight:600,letterSpacing:'0.06em',textTransform:'uppercase',marginBottom:4}}>
            Total Kekayaan Bersih
          </div>
          <div style={{fontSize:34,fontWeight:800,letterSpacing:'-0.025em'}}>{fmtRp(grandTotal)}</div>

          {/* Breakdown row */}
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr',gap:12,marginTop:16}}>
            {[
              {label:'Bebas',     val:totalAvail,  sub:'diluar pocket'},
              {label:'Di Pocket', val:totalLocked, sub:'ada di rekening'},
              {label:'Investasi', val:totalInvest, sub:totalPnl !== 0 ? (totalPnl>0?'+':'')+fmtRp(totalPnl,{short:true})+' P&L' : 'portofolio'},
            ].map(function(item){
              return (
                <div key={item.label} style={{background:'rgba(255,255,255,0.15)',borderRadius:12,padding:'10px 12px'}}>
                  <div style={{fontSize:10,opacity:0.8,marginBottom:3}}>{item.label}</div>
                  <div style={{fontSize:14,fontWeight:800}}>{fmtRp(item.val,{short:true})}</div>
                  <div style={{fontSize:10,opacity:0.7,marginTop:2}}>{item.sub}</div>
                </div>
              );
            })}
          </div>

          {/* Monthly flow */}
          {monthFlow && (
            <div style={{marginTop:14,paddingTop:14,borderTop:'1px solid rgba(255,255,255,0.2)',
              display:'flex',gap:20}}>
              <div>
                <div style={{fontSize:10,opacity:0.75}}>Masuk bulan ini</div>
                <div style={{fontSize:13,fontWeight:700}}>+{fmtRp(monthFlow.income,{short:true})}</div>
              </div>
              <div>
                <div style={{fontSize:10,opacity:0.75}}>Keluar bulan ini</div>
                <div style={{fontSize:13,fontWeight:700}}>-{fmtRp(monthFlow.expense,{short:true})}</div>
              </div>
              <div>
                <div style={{fontSize:10,opacity:0.75}}>Net</div>
                <div style={{fontSize:13,fontWeight:700,color:monthFlow.net>=0?'#a7f3d0':'#fca5a5'}}>
                  {monthFlow.net>=0?'+':''}{fmtRp(monthFlow.net,{short:true})}
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Account list by type */}
      {accounts===null ? (
        <div style={{textAlign:'center',padding:'40px 0',color:T.fg4}}>
          <div style={{fontSize:14}}>Memuat...</div>
        </div>
      ) : Object.keys(grouped).length===0 ? (
        <div style={{textAlign:'center',padding:'40px 20px',color:T.fg4}}>
          <div style={{fontSize:40,marginBottom:12}}>🏦</div>
          <div style={{fontSize:15,fontWeight:700,color:T.fg2,marginBottom:4}}>Belum ada rekening</div>
          <div style={{fontSize:13}}>Tap + untuk tambah bank, investasi, atau e-wallet</div>
        </div>
      ) : (
        Object.keys(TYPE_INFO).filter(function(t){return grouped[t];}).map(function(type){
          var info = TYPE_INFO[type];
          var typeTotal = (grouped[type]||[]).reduce(function(s,a){return s+a.balance;},0);
          return (
            <div key={type} style={{padding:'0 20px',marginBottom:20}}>
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:8}}>
                <div style={{fontSize:12,fontWeight:700,color:T.fg3,textTransform:'uppercase',letterSpacing:'0.06em'}}>
                  {info.icon} {info.label}
                </div>
                <div style={{fontSize:12,fontWeight:700,color:T.fg2}}>{fmtRp(typeTotal,{short:true})}</div>
              </div>
              <div style={{display:'flex',flexDirection:'column',gap:8}}>
                {(grouped[type]||[]).map(function(acc){
                  var pnl = acc.unrealized_pnl || 0;
                  var locked = acc.locked_in_goals || 0;
                  var avail = acc.available_balance !== undefined ? acc.available_balance : acc.balance;
                  return (
                    <div key={acc.id} style={{display:'flex',alignItems:'center',gap:12,background:T.surface,
                        border:'1px solid '+T.border,borderRadius:16,padding:'12px 16px',
                        cursor:'pointer',textAlign:'left',width:'100%'}}
                      onClick={function(){setEditAcc(acc);setShowAdd(true);}}>
                      <div style={{width:44,height:44,borderRadius:14,flexShrink:0,
                        background:acc.color+'20',display:'flex',alignItems:'center',justifyContent:'center',fontSize:22}}>
                        {acc.icon}
                      </div>
                      <div style={{flex:1,minWidth:0}}>
                        <div style={{fontSize:14,fontWeight:700,color:T.fg1}}>{acc.name}</div>
                        {acc.institution && <div style={{fontSize:11,color:T.fg4}}>{acc.institution}</div>}
                        {/* Available vs locked */}
                        {locked > 0 && (
                          <div style={{display:'flex',gap:8,marginTop:4}}>
                            <span style={{fontSize:10,color:'#10b981',fontWeight:600}}>✓ {fmtRp(avail,{short:true})} bebas</span>
                            <span style={{fontSize:10,color:'#8b5cf6',fontWeight:600}}>🔒 {fmtRp(locked,{short:true})} pocket</span>
                          </div>
                        )}
                        {/* Investment P&L */}
                        {type === 'investment' && acc.cost_basis > 0 && (
                          <div style={{fontSize:10,marginTop:4,fontWeight:600,color:pnl>=0?'#10b981':'#ef4444'}}>
                            {'Modal '+fmtRp(acc.cost_basis,{short:true})+' · P&L '+(pnl>=0?'+':'')+fmtRp(pnl,{short:true})}
                          </div>
                        )}
                        {type === 'investment' && (
                          <button onClick={function(e){e.stopPropagation();setUpdateValAcc(acc);}}
                            style={{
                              marginTop:7, appearance:'none', cursor:'pointer', fontFamily:'inherit',
                              background:'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')',
                              color:'#fff', border:0, borderRadius:10,
                              fontSize:11, fontWeight:700, padding:'5px 12px',
                              boxShadow:'0 2px 8px '+accent[500]+'44',
                              display:'inline-flex', alignItems:'center', gap:5,
                            }}>
                            <span>📊</span> Update Nilai
                          </button>
                        )}
                        <div style={{fontSize:10,color:T.fg4,marginTop:2}}>
                          Update: {new Date(acc.last_updated).toLocaleDateString('id-ID')}
                        </div>
                      </div>
                      <div style={{textAlign:'right',flexShrink:0}}>
                        <div style={{fontSize:16,fontWeight:800,color:type==='credit'?'#ef4444':T.fg1}}>
                          {type==='credit'?'-':''}{fmtRp(acc.balance,{short:true})}
                        </div>
                        {type !== 'credit' && locked > 0 && (
                          <div style={{fontSize:11,color:T.fg3,marginTop:2}}>
                            {fmtRp(avail,{short:true})} tersedia
                          </div>
                        )}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>
          );
        })
      )}

      {showAdd && (
        <AccountModal theme={T} accent={accent} auth={auth} account={editAcc}
          onClose={function(){setShowAdd(false);setEditAcc(null);}} onSaved={loadAll} />
      )}
      {updateValAcc && (
        <UpdateValModal theme={T} accent={accent} account={updateValAcc}
          onClose={function(){setUpdateValAcc(null);}}
          onSave={function(){setUpdateValAcc(null);loadAll();}} />
      )}
    </div>
  );
}

// ─── ACCOUNT MODAL ────────────────────────────────────────────────
function AccountModal({ theme, accent, auth, account, onClose, onSaved }) {
  var T = theme, isEdit = !!account;
  var _s1=React.useState(account&&account.name||''), name=_s1[0], setName=_s1[1];
  var _s2=React.useState(account&&account.type||'bank'), type=_s2[0], setType=_s2[1];
  var _s3=React.useState(account&&account.institution||''), inst=_s3[0], setInst=_s3[1];
  var _s4=React.useState(account?account.balance.toLocaleString('id-ID'):''), balance=_s4[0], setBalance=_s4[1];
  var _s5=React.useState(account&&account.cost_basis?account.cost_basis.toLocaleString('id-ID'):''), costBasis=_s5[0], setCostBasis=_s5[1];
  var _s6=React.useState(account&&account.icon||'🏦'), icon=_s6[0], setIcon=_s6[1];
  var _s7=React.useState(account&&account.color||'#10b981'), color=_s7[0], setColor=_s7[1];
  var _s8=React.useState(account&&account.notes||''), notes=_s8[0], setNotes=_s8[1];
  var _s9=React.useState(false), saving=_s9[0], setSaving=_s9[1];
  var _s10=React.useState(false), deleting=_s10[0], setDeleting=_s10[1];

  var TYPE_ICONS={bank:'🏦',cash:'💵',investment:'📈',ewallet:'📱',credit:'💳'};
  var TYPE_LABELS={bank:'Bank',cash:'Tunai',investment:'Investasi',ewallet:'E-Wallet',credit:'Kredit'};
  var COLORS=['#10b981','#3b82f6','#8b5cf6','#f59e0b','#ef4444','#0d9488','#ec4899','#6366f1'];
  var ICONS=['🏦','💵','📈','📱','💳','🏧','💰','🏛️','💼','📊','🪙','💎'];

  React.useEffect(function(){
    if (!isEdit) setIcon(TYPE_ICONS[type]||'🏦');
  }, [type]);

  async function handleSave() {
    if (!name.trim()||!window.SB) return;
    setSaving(true);
    var amt   = parseInt(balance.replace(/\D/g,''),10)||0;
    var basis = parseInt(costBasis.replace(/\D/g,''),10)||0;
    var payload = {
      family_id:   auth.family.id,
      created_by:  auth.user.id,
      name:        name.trim(),
      type:        type,
      institution: inst||null,
      balance:     amt,
      cost_basis:  type==='investment' ? basis : 0,
      credit_limit: type==='credit' ? (parseInt(creditLimit.replace(/\D/g,''),10)||0) : 0,
      icon:        icon,
      color:       color,
      notes:       notes||null,
      last_updated: new Date().toISOString().split('T')[0],
    };
    var r = isEdit
      ? await window.SB.from('accounts').update(payload).eq('id',account.id)
      : await window.SB.from('accounts').insert(payload);
    setSaving(false);
    if (r.error) { alert('Error: '+r.error.message); return; }
    onSaved(); onClose();
  }

  async function handleDelete() {
    if (!confirm('Hapus akun ini? Goals yang terhubung akan di-unlink.')) return;
    setDeleting(true);
    await window.SB.from('accounts').delete().eq('id',account.id);
    setDeleting(false); onSaved(); onClose();
  }

  var balanceLabel = type==='credit' ? 'Tagihan Saat Ini (outstanding)' : type==='investment' ? 'Nilai Sekarang (current value)' : 'Saldo Saat Ini';

  return (
    <div style={{position:'fixed',inset:0,zIndex:300,background:'rgba(0,0,0,0.55)',display:'flex',alignItems:'flex-end',justifyContent:'center'}}
      onClick={function(e){if(e.target===e.currentTarget)onClose();}}>
      <div style={{background:T.surface,borderRadius:'24px 24px 0 0',padding:'24px 20px 48px',width:'100%',maxWidth:480,maxHeight:'92vh',overflowY:'auto'}}>
        <div style={{width:40,height:4,background:T.border,borderRadius:99,margin:'0 auto 20px'}}/>
        <div style={{fontSize:18,fontWeight:800,color:T.fg1,marginBottom:16}}>
          {isEdit?'Edit Akun':'Tambah Akun'}
        </div>

        {/* Type selector */}
        <div style={{marginBottom:14}}>
          <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:8,textTransform:'uppercase',letterSpacing:'0.05em'}}>Tipe</div>
          <div style={{display:'flex',gap:6,flexWrap:'wrap'}}>
            {Object.keys(TYPE_LABELS).map(function(t){
              return <button key={t} onClick={function(){setType(t);}}
                style={{height:36,borderRadius:10,border:'1.5px solid '+(type===t?accent[500]:T.border),
                  background:type===t?accent.tint:'transparent',color:type===t?accent[600]:T.fg2,
                  fontWeight:600,fontSize:12,cursor:'pointer',padding:'0 12px',fontFamily:'inherit'}}>
                {TYPE_ICONS[t]} {TYPE_LABELS[t]}
              </button>;
            })}
          </div>
        </div>

        {/* Investment info box */}
        {type==='investment' && (
          <div style={{background:accent.tint,borderRadius:12,padding:'10px 14px',marginBottom:14,border:'1px solid '+accent[100]}}>
            <div style={{fontSize:12,color:accent[700],lineHeight:1.5}}>
              <strong>Cara pakai:</strong> Isi "Modal" = total uang yang pernah kamu masukkan.
              Isi "Nilai sekarang" = harga pasar terkini. App hitung P&L otomatis.
              Update "Nilai sekarang" secara berkala (saham: bulanan, kripto: mingguan).
            </div>
          </div>
        )}

        {/* Icon + Color */}
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginBottom:14}}>
          <div>
            <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Icon</div>
            <div style={{display:'flex',flexWrap:'wrap',gap:4}}>
              {ICONS.map(function(ic){
                return <button key={ic} onClick={function(){setIcon(ic);}}
                  style={{width:36,height:36,borderRadius:8,fontSize:18,
                    border:'2px solid '+(icon===ic?accent[500]:T.border),
                    background:icon===ic?accent.tint:'transparent',cursor:'pointer'}}>{ic}</button>;
              })}
            </div>
          </div>
          <div>
            <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Warna</div>
            <div style={{display:'flex',flexWrap:'wrap',gap:6}}>
              {COLORS.map(function(col){
                return <button key={col} onClick={function(){setColor(col);}}
                  style={{width:30,height:30,borderRadius:8,background:col,
                    border:'3px solid '+(color===col?T.fg1:'transparent'),cursor:'pointer'}}/>;
              })}
            </div>
          </div>
        </div>

        {/* Nama */}
        <div style={{marginBottom:12}}>
          <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Nama Akun</div>
          <input type="text" placeholder="Misal: BCA Tabungan, BBRI, Bitcoin" value={name}
            onChange={function(e){setName(e.target.value);}} autoFocus
            style={{width:'100%',height:48,borderRadius:12,border:'1.5px solid '+T.border,
              background:T.bg,color:T.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}/>
        </div>

        {/* Institusi */}
        <div style={{marginBottom:12}}>
          <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Bank / Institusi (opsional)</div>
          <input type="text" placeholder="Misal: Bank BCA, Tokopedia, Binance" value={inst}
            onChange={function(e){setInst(e.target.value);}}
            style={{width:'100%',height:48,borderRadius:12,border:'1.5px solid '+T.border,
              background:T.bg,color:T.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}/>
        </div>

        {/* Modal investasi */}
        {type==='investment' && (
          <div style={{marginBottom:12}}>
            <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>
              Modal (cost basis) — total uang yang dimasukkan
            </div>
            <div style={{display:'flex',alignItems:'center',gap:8,background:T.bg,border:'1.5px solid '+T.border,borderRadius:12,padding:'0 14px'}}>
              <span style={{color:T.fg3,fontSize:13}}>Rp</span>
              <input type="text" inputMode="numeric" placeholder="0" value={costBasis}
                onChange={function(e){setCostBasis(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:T.fg1,fontFamily:'inherit'}}/>
            </div>
          </div>
        )}

        {/* Saldo / current value */}
        <div style={{marginBottom:12}}>
          <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>
            {balanceLabel}
          </div>
          <div style={{display:'flex',alignItems:'center',gap:8,background:T.bg,border:'1.5px solid '+T.border,borderRadius:12,padding:'0 14px'}}>
            <span style={{color:T.fg3,fontSize:13}}>Rp</span>
            <input type="text" inputMode="numeric" placeholder="0" value={balance}
              onChange={function(e){setBalance(parseInt(e.target.value.replace(/\D/g,'')||'0').toLocaleString('id-ID'));}}
              style={{flex:1,height:50,border:0,outline:'none',background:'transparent',
                fontSize:18,fontWeight:800,color:T.fg1,fontFamily:'inherit'}}/>
          </div>
          {/* Live P&L preview for investment */}
          {(function(){
            if (type!=='investment'||!costBasis||!balance) return null;
            var cb = parseInt(costBasis.replace(/\D/g,''),10)||0;
            var cur = parseInt(balance.replace(/\D/g,''),10)||0;
            if (cb===0) return null;
            var pnl = cur - cb;
            var pct = cb > 0 ? ((pnl/cb)*100).toFixed(1) : 0;
            return (
              <div style={{marginTop:6,fontSize:12,fontWeight:700,
                color:pnl>=0?'#10b981':'#ef4444',textAlign:'right'}}>
                {'P&L: '+(pnl>=0?'+':'')+fmtRp(pnl,{short:true})+' ('+(pnl>=0?'+':'')+pct+'%)'}
              </div>
            );
          })()}
        </div>

        {/* Notes */}
        {type==='credit' && (
          <div style={{marginBottom:12}}>
            <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Limit Kartu Kredit</div>
            <div style={{display:'flex',alignItems:'center',gap:8,background:T.bg,border:'1.5px solid '+T.border,borderRadius:12,padding:'0 14px'}}>
              <span style={{color:T.fg3,fontSize:13}}>Rp</span>
              <input type="text" inputMode="numeric" placeholder="50.000.000" value={creditLimit}
                onChange={function(e){setCreditLimit(parseInt(e.target.value.replace(/\D/g,'')||'0').toLocaleString('id-ID'));}}
                style={{flex:1,height:46,border:0,outline:'none',background:'transparent',fontSize:16,fontWeight:700,color:T.fg1,fontFamily:'inherit'}}/>
            </div>
            {creditLimit && balance && (function(){
              var lim = parseInt(creditLimit.replace(/\D/g,''),10)||0;
              var used = parseInt(balance.replace(/\D/g,''),10)||0;
              var avail = lim - used;
              var pct = lim > 0 ? Math.round((used/lim)*100) : 0;
              return (
                <div style={{marginTop:8,padding:'8px 12px',background:pct>80?'rgba(239,68,68,0.06)':'rgba(16,185,129,0.06)',borderRadius:10}}>
                  <div style={{display:'flex',justifyContent:'space-between',fontSize:12,marginBottom:6}}>
                    <span style={{color:T.fg3}}>Terpakai</span>
                    <span style={{fontWeight:700,color:pct>80?'#ef4444':'#10b981'}}>{pct}%</span>
                  </div>
                  <div style={{height:6,background:T.surfaceAlt,borderRadius:3,overflow:'hidden'}}>
                    <div style={{height:'100%',width:pct+'%',borderRadius:3,background:pct>80?'#ef4444':pct>60?'#f59e0b':'#10b981'}}/>
                  </div>
                  <div style={{display:'flex',justifyContent:'space-between',fontSize:11,marginTop:6,color:T.fg3}}>
                    <span>Tagihan: {fmtRp(used,{short:true})}</span>
                    <span style={{color:'#10b981',fontWeight:600}}>Tersedia: {fmtRp(avail,{short:true})}</span>
                  </div>
                </div>
              );
            })()}
          </div>
        )}
        <div style={{marginBottom:16}}>
          <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Catatan (opsional)</div>
          <input type="text" placeholder="Misal: Rekening gaji, Portofolio saham IHSG..." value={notes}
            onChange={function(e){setNotes(e.target.value);}}
            style={{width:'100%',height:44,borderRadius:12,border:'1.5px solid '+T.border,
              background:T.bg,color:T.fg1,fontSize:13,padding:'0 14px',fontFamily:'inherit',outline:'none'}}/>
        </div>

        <div style={{display:'flex',gap:10}}>
          {isEdit && (
            <button onClick={handleDelete} disabled={deleting}
              style={{flex:1,height:50,borderRadius:14,border:'1px solid #fecaca',
                background:'rgba(239,68,68,0.05)',color:'#ef4444',fontSize:14,fontWeight:700,
                cursor:'pointer',fontFamily:'inherit'}}>
              {deleting?'...':'Hapus'}
            </button>
          )}
          <button onClick={handleSave} disabled={!name.trim()||saving}
            style={{flex:2,height:50,borderRadius:14,border:0,cursor:'pointer',fontFamily:'inherit',
              background:name.trim()&&!saving?'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')':'#ccc',
              color:'#fff',fontSize:15,fontWeight:700}}>
            {saving?'Menyimpan...':(isEdit?'Perbarui':'+ Tambah Akun')}
          </button>
        </div>
      </div>
    </div>
  );
}

// ─── GOALS (updated — dengan account link) ────────────────────────
function ScreenGoals({ theme, accent, scenario, auth }) {
  var T = theme;
  var _s1 = React.useState(null), realGoals = _s1[0], setRealGoals = _s1[1];
  var _s2 = React.useState(null), accounts  = _s2[0], setAccounts  = _s2[1];
  var _s3 = React.useState(false), showAddGoal = _s3[0], setShowAddGoal = _s3[1];
  var _s4 = React.useState(''), goalName = _s4[0], setGoalName = _s4[1];
  var _s5 = React.useState('🎯'), goalEmoji = _s5[0], setGoalEmoji = _s5[1];
  var _s6 = React.useState(''), goalTarget = _s6[0], setGoalTarget = _s6[1];
  var _s7 = React.useState(''), goalDate = _s7[0], setGoalDate = _s7[1];
  var _s8 = React.useState(''), goalAccountId = _s8[0], setGoalAccountId = _s8[1];
  var _s9  = React.useState(''),       monthlyAuto = _s9[0],  setMonthlyAuto = _s9[1];
  var _s13 = React.useState('monthly'), autoFreq    = _s13[0], setAutoFreq    = _s13[1];
  var _s14 = React.useState([]),        autoDays    = _s14[0], setAutoDays    = _s14[1];
  var _s10 = React.useState(false), savingGoal = _s10[0], setSavingGoal = _s10[1];
  var _s11 = React.useState(null), topupGoal = _s11[0], setTopupGoal = _s11[1];
  var _s12 = React.useState(''),  topupAmt  = _s12[0], setTopupAmt  = _s12[1];
  var _s15 = React.useState(null), editGoal  = _s15[0], setEditGoal  = _s15[1];
  var _s16 = React.useState(null), withdrawGoal = _s16[0], setWithdrawGoal = _s16[1];
  var _s17 = React.useState(''),  withdrawAmt  = _s17[0], setWithdrawAmt  = _s17[1];
  var familyId = auth && auth.family && auth.family.id;
  var isAuth = !!(auth && auth.family);

  React.useEffect(function() {
    if (!familyId || !window.SB) return;
    sbGetGoals(familyId).then(function(r){ if(!r.error) setRealGoals(r.data||[]); });
    window.SB.from('accounts').select('id,name,icon,type').eq('family_id',familyId)
      .order('name').then(function(r){ if(!r.error) setAccounts(r.data||[]); });
  }, [familyId]);

  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,contribs:[],isReal:true,
        account_id:g.account_id,monthly_auto:g.monthly_auto||0};
    }
    return g;
  }

  var goals = (isAuth ? (realGoals||[]) : scenario.goals).map(normGoal);
  var totalSaved  = goals.reduce(function(a,g){return a+g.saved;},0);
  var totalTarget = goals.reduce(function(a,g){return a+g.target;},0);

  async function handleAddGoal() {
    if (!goalName||!goalTarget) return;
    setSavingGoal(true);
    var amount = parseInt(goalTarget.replace(/\D/g,''),10);
    var monthly = parseInt(monthlyAuto.replace(/\D/g,''),10)||0;
    if (window.sbAddGoal && auth && auth.family && auth.user) {
      var r = await window.SB.from('savings_goals').insert({
        family_id:     auth.family.id,
        created_by:    auth.user.id,
        name:          goalName,
        icon:          goalEmoji,
        target_amount: amount,
        current_amount:0,
        target_date:   goalDate||null,
        account_id:    goalAccountId||null,
        monthly_auto:  monthly,
      }).select().single();
      if (!r.error) {
        var fresh = await sbGetGoals(auth.family.id);
        if (!fresh.error) setRealGoals(fresh.data||[]);
      }
    }
    setShowAddGoal(false); setGoalName(''); setGoalTarget('');
    setGoalDate(''); setGoalAccountId(''); setMonthlyAuto(''); setAutoFreq('monthly'); setAutoDays([]);
    setSavingGoal(false);
  }

  async function handleWithdraw() {
    if (!withdrawGoal || !withdrawAmt) return;
    var amt = parseInt(withdrawAmt.replace(/\D/g,''), 10);
    if (amt <= 0 || amt > withdrawGoal.saved) return;
    await window.SB.from('savings_goals').update({current_amount: withdrawGoal.saved - amt}).eq('id', withdrawGoal.id);
    var fresh = await sbGetGoals(familyId);
    if (!fresh.error) setRealGoals(fresh.data||[]);
    setWithdrawGoal(null); setWithdrawAmt('');
  }

  async function handleEditGoal(g, updates) {
    await window.SB.from('savings_goals').update(updates).eq('id', g.id);
    var fresh = await sbGetGoals(familyId);
    if (!fresh.error) setRealGoals(fresh.data||[]);
    setEditGoal(null);
  }

  async function handleDeleteGoal(g) {
    if (!confirm('Hapus goal "'+g.name+'"?')) return;
    await window.SB.from('savings_goals').delete().eq('id', g.id);
    var fresh = await sbGetGoals(familyId);
    if (!fresh.error) setRealGoals(fresh.data||[]);
  }

  async function handleTopup() {
    if (!topupGoal||!topupAmt) return;
    var amt = parseInt(topupAmt.replace(/\D/g,''),10);
    if (amt <= 0) return;
    await window.SB.from('savings_goals').update({current_amount: topupGoal.saved + amt}).eq('id',topupGoal.id);
    var fresh = await sbGetGoals(familyId);
    if (!fresh.error) setRealGoals(fresh.data||[]);
    setTopupGoal(null); setTopupAmt('');
  }

  var spinner = <div style={{width:18,height:18,border:'2.5px solid rgba(255,255,255,0.35)',borderTopColor:'#fff',borderRadius:'50%',animation:'spin 0.7s linear infinite'}}/>;
  var EMOJIS = ['🎯','🏠','🚗','✈️','🎓','💍','📱','💻','🏖️','💰','🐷','🎸','🏥','🎮','📷'];

  return (
    <div style={{background:T.bg,minHeight:'100%',paddingBottom:100}}>
      <div style={{padding:'56px 20px 16px',display:'flex',justifyContent:'space-between',alignItems:'flex-end'}}>
        <div>
          <h1 style={{margin:0,fontSize:28,fontWeight:800,color:T.fg1,letterSpacing:'-0.025em'}}>Tabungan</h1>
          <div style={{fontSize:12,color:T.fg3,marginTop:2}}>{goals.length} tujuan keluarga</div>
        </div>
        <button onClick={function(){setShowAddGoal(true);}}
          style={{width:36,height:36,borderRadius:12,border:0,cursor:'pointer',
            background:'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')',
            display:'flex',alignItems:'center',justifyContent:'center',fontSize:22,color:'#fff'}}>+</button>
      </div>

      {/* Summary hero */}
      <div style={{padding:'0 20px 20px'}}>
        <div style={{background:'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')',
          borderRadius:22,padding:20,color:'#fff',boxShadow:'0 10px 32px '+accent[500]+'55'}}>
          <div style={{fontSize:11,opacity:0.85,fontWeight:600,letterSpacing:'0.04em',textTransform:'uppercase',marginBottom:4}}>Total terkumpul</div>
          <div style={{fontSize:30,fontWeight:800,letterSpacing:'-0.025em'}}>{fmtRp(totalSaved)}</div>
          <div style={{fontSize:12,opacity:0.8,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>

      {/* Goals list */}
      <div style={{padding:'0 20px',display:'flex',flexDirection:'column',gap:14}}>
        {goals.length===0 ? (
          <div style={{textAlign:'center',padding:'40px 0',color:T.fg4}}>
            <div style={{fontSize:40,marginBottom:12}}>🐷</div>
            <div style={{fontSize:14,fontWeight:600,color:T.fg2}}>Belum ada goals tabungan</div>
            <div style={{fontSize:12,marginTop:4}}>Tap + untuk mulai rencanakan impianmu</div>
          </div>
        ) : goals.map(function(g){
          var pct = Math.min(100, g.target>0?g.saved/g.target*100:0);
          var remaining = g.target - g.saved;
          var linkedAcc = accounts && g.account_id && accounts.find(function(a){return a.id===g.account_id;});
          return (
            <div key={g.id} style={{background:T.surface,borderRadius:20,padding:16,border:'1px solid '+T.border,boxShadow:'0 2px 8px rgba(0,0,0,0.04)'}}>
              <div style={{display:'flex',alignItems:'flex-start',gap:12,marginBottom:14}}>
                <div style={{width:52,height:52,borderRadius:18,background:T.surfaceAlt,
                  display:'flex',alignItems:'center',justifyContent:'center',fontSize:28,flexShrink:0}}>
                  {g.emoji}
                </div>
                <div style={{flex:1,minWidth:0}}>
                  <div style={{fontSize:16,fontWeight:700,color:T.fg1}}>{g.name}</div>
                  <div style={{display:'flex',gap:8,flexWrap:'wrap',marginTop:4}}>
                    {g.due && <span style={{fontSize:11,color:T.fg3}}>Target: {new Date(g.due).toLocaleDateString('id-ID',{month:'short',year:'numeric'})}</span>}
                    {linkedAcc && <span style={{fontSize:11,color:'#8b5cf6',fontWeight:600}}>🔗 {linkedAcc.icon} {linkedAcc.name}</span>}
                    {g.monthly_auto > 0 && (function(){
                      var sc = null; try{sc=JSON.parse(g.notes||'');}catch(e){}
                      var fl = {daily:'hari',weekly:'minggu',monthly:'bln',custom:'pilihan'}[(sc&&sc.freq)||'monthly']||'bln';
                      var dl = sc&&sc.days&&sc.days.length?' ('+sc.days.join(',')+'%)':'';
                      return <span style={{fontSize:11,color:'#10b981',fontWeight:600}}>⚡ {fmtRp(g.monthly_auto,{short:true})}/{fl}{dl}</span>;
                    })()}
                  </div>
                </div>
                <div style={{textAlign:'right',flexShrink:0}}>
                  <div style={{fontSize:15,fontWeight:800,color:T.fg1}}>{fmtRp(g.saved,{short:true})}</div>
                  <div style={{fontSize:11,color:T.fg3}}>dari {fmtRp(g.target,{short:true})}</div>
                </div>
              </div>
              <div style={{height:8,background:T.surfaceAlt,borderRadius:4,overflow:'hidden',marginBottom:8}}>
                <div style={{height:'100%',borderRadius:4,
                  background:pct>=100?'#10b981':'linear-gradient(90deg,'+accent.grad[0]+','+accent.grad[1]+')',
                  width:pct+'%',transition:'width 0.4s ease'}}/>
              </div>
              <div style={{display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                <span style={{fontSize:11,color:T.fg3}}>{pct.toFixed(0)}% · sisa {fmtRp(Math.max(remaining,0),{short:true})}</span>
                <div style={{display:'flex',gap:6}}>
                  <button onClick={function(){setTopupGoal(g);setTopupAmt('');}}
                    style={{fontSize:12,fontWeight:700,color:accent[600],cursor:'pointer',
                      padding:'4px 10px',borderRadius:8,border:0,background:accent.tint,fontFamily:'inherit'}}>
                    + Nabung
                  </button>
                  {g.saved > 0 && (
                    <button onClick={function(){setWithdrawGoal(g);setWithdrawAmt('');}}
                      style={{fontSize:12,fontWeight:700,color:'#f59e0b',cursor:'pointer',
                        padding:'4px 10px',borderRadius:8,border:0,background:'rgba(245,158,11,0.1)',fontFamily:'inherit'}}>
                      Cairkan
                    </button>
                  )}
                  <button onClick={function(){setEditGoal(g);}}
                    style={{fontSize:12,fontWeight:700,color:T.fg3,cursor:'pointer',
                      padding:'4px 10px',borderRadius:8,border:0,background:T.surfaceAlt,fontFamily:'inherit'}}>
                    Edit
                  </button>
                </div>
              </div>
            </div>
          );
        })}
      </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={function(e){if(e.target===e.currentTarget)setShowAddGoal(false);}}>
          <div style={{background:T.surface,borderRadius:'24px 24px 0 0',padding:'24px 20px 48px',width:'100%',maxWidth:480,maxHeight:'92vh',overflowY:'auto'}}>
            <div style={{width:40,height:4,background:T.border,borderRadius:99,margin:'0 auto 20px'}}/>
            <div style={{fontSize:18,fontWeight:800,color:T.fg1,marginBottom:14}}>Tambah Goal</div>
            {/* Emoji picker */}
            <div style={{display:'flex',gap:6,flexWrap:'wrap',marginBottom:14}}>
              {EMOJIS.map(function(e){
                return <button key={e} onClick={function(){setGoalEmoji(e);}}
                  style={{width:40,height:40,borderRadius:10,fontSize:20,cursor:'pointer',
                    border:'2px solid '+(goalEmoji===e?accent[500]:T.border),
                    background:goalEmoji===e?accent.tint:'transparent'}}>{e}</button>;
              })}
            </div>
            {/* Nama */}
            <div style={{marginBottom:12}}>
              <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Nama Goal</div>
              <input type="text" placeholder="Misal: DP Rumah, Liburan Jepang..." value={goalName}
                onChange={function(e){setGoalName(e.target.value);}} autoFocus
                style={{width:'100%',height:48,borderRadius:12,border:'1.5px solid '+T.border,
                  background:T.bg,color:T.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}/>
            </div>
            {/* Target dana */}
            <div style={{marginBottom:12}}>
              <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Target Dana</div>
              <div style={{display:'flex',alignItems:'center',gap:8,background:T.bg,border:'1.5px solid '+T.border,borderRadius:12,padding:'0 14px'}}>
                <span style={{color:T.fg3,fontSize:13}}>Rp</span>
                <input type="text" inputMode="numeric" placeholder="10.000.000" value={goalTarget}
                  onChange={function(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:T.fg1,fontFamily:'inherit'}}/>
              </div>
            </div>
            {/* Nabung otomatis */}
            <div style={{marginBottom:12}}>
              <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:8,textTransform:'uppercase',letterSpacing:'0.05em'}}>
                Nabung Otomatis (opsional)
              </div>
              <div style={{display:'grid',gridTemplateColumns:'1fr 1fr 1fr 1fr',gap:5,marginBottom:8}}>
                {[{v:'daily',l:'Harian'},{v:'weekly',l:'Mingguan'},{v:'monthly',l:'Bulanan'},{v:'custom',l:'Pilih hari'}].map(function(f){
                  return <button key={f.v} onClick={function(){setAutoFreq(f.v);setAutoDays([]);}}
                    style={{height:32,borderRadius:9,border:'1.5px solid '+(autoFreq===f.v?accent[500]:T.border),
                      background:autoFreq===f.v?accent.tint:'transparent',
                      color:autoFreq===f.v?accent[600]:T.fg3,
                      fontWeight:600,fontSize:11,cursor:'pointer',fontFamily:'inherit'}}>
                    {f.l}
                  </button>;
                })}
              </div>
              {(autoFreq==='weekly'||autoFreq==='custom') && (
                <div style={{marginBottom:8}}>
                  <div style={{fontSize:11,color:T.fg3,marginBottom:5}}>
                    {autoFreq==='weekly'?'Pilih 1 hari dalam seminggu:':'Pilih hari-hari tertentu:'}
                  </div>
                  <div style={{display:'flex',gap:4,flexWrap:'wrap'}}>
                    {['Sen','Sel','Rab','Kam','Jum','Sab','Min'].map(function(day){
                      var on = autoDays.indexOf(day)!==-1;
                      return <button key={day} onClick={function(){
                          setAutoDays(autoFreq==='weekly'?(on?[]:[day]):(on?autoDays.filter(function(d){return d!==day;}):autoDays.concat([day])));
                        }}
                        style={{width:36,height:30,borderRadius:8,border:'1.5px solid '+(on?accent[500]:T.border),
                          background:on?accent.tint:'transparent',color:on?accent[600]:T.fg3,
                          fontWeight:700,fontSize:11,cursor:'pointer',fontFamily:'inherit'}}>
                        {day}
                      </button>;
                    })}
                  </div>
                </div>
              )}
              <div style={{display:'flex',alignItems:'center',gap:8,background:T.bg,border:'1.5px solid '+T.border,borderRadius:12,padding:'0 14px'}}>
                <span style={{color:T.fg3,fontSize:13}}>Rp</span>
                <input type="text" inputMode="numeric"
                  placeholder={autoFreq==='daily'?'10.000':autoFreq==='weekly'?'25.000':'100.000'}
                  value={monthlyAuto}
                  onChange={function(e){setMonthlyAuto(parseInt(e.target.value.replace(/\D/g,'')||'0').toLocaleString('id-ID'));}}
                  style={{flex:1,height:44,border:0,outline:'none',background:'transparent',fontSize:14,fontWeight:700,color:T.fg1,fontFamily:'inherit'}}/>
                <span style={{color:T.fg3,fontSize:11,fontWeight:600,flexShrink:0}}>
                  {autoFreq==='daily'?'/hari':autoFreq==='weekly'?'/minggu':autoFreq==='custom'?'/hari':'/bulan'}
                </span>
              </div>
              {!!monthlyAuto && (function(){
                var amt = parseInt(monthlyAuto.replace(/\D/g,'')||'0',10)||0;
                var est = autoFreq==='daily'?amt*30:autoFreq==='weekly'?amt*4:autoFreq==='custom'?amt*(autoDays.length||1)*4:amt*12;
                var lbl = autoFreq==='daily'?'est. /bulan':autoFreq==='weekly'?'est. /bulan':autoFreq==='custom'?'est. /bulan':'est. /tahun';
                return <div style={{fontSize:11,color:accent[600],marginTop:5,fontWeight:600}}>{fmtRp(est,{short:true})} {lbl}</div>;
              })()}
              <div style={{fontSize:11,color:T.fg4,marginTop:4}}>Pengingat saja — kamu konfirmasi sendiri setiap periode</div>
            </div>
            {/* Link ke rekening */}
            {accounts && accounts.filter(function(a){return a.type!=='credit';}).length > 0 && (
              <div style={{marginBottom:12}}>
                <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>
                  Linked ke rekening (opsional)
                </div>
                <select value={goalAccountId} onChange={function(e){setGoalAccountId(e.target.value);}}
                  style={{width:'100%',height:48,borderRadius:12,border:'1.5px solid '+T.border,
                    background:T.bg,color:T.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}>
                  <option value="">-- Tidak ada (bebas) --</option>
                  {accounts.filter(function(a){return a.type!=='credit';}).map(function(a){
                    return <option key={a.id} value={a.id}>{a.icon} {a.name}</option>;
                  })}
                </select>
                {goalAccountId && <div style={{fontSize:11,color:'#8b5cf6',marginTop:4}}>
                  Saldo rekening ini akan dikurangi sebesar goal terkumpul (virtual pocket)
                </div>}
              </div>
            )}
            {/* Target tanggal */}
            <div style={{marginBottom:16}}>
              <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Target Tanggal (opsional)</div>
              <input type="date" value={goalDate} onChange={function(e){setGoalDate(e.target.value);}}
                style={{width:'100%',height:48,borderRadius:12,border:'1.5px solid '+T.border,
                  background:T.bg,color:T.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',fontFamily:'inherit',
                background:goalName&&goalTarget&&!savingGoal?'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')':'#ccc',
                color:'#fff',fontSize:15,fontWeight:700,display:'flex',alignItems:'center',justifyContent:'center',gap:8}}>
              {savingGoal ? spinner : goalEmoji+' Buat Goal'}
            </button>
          </div>
        </div>
      )}

      {/* Withdraw / Cairkan modal */}
      {withdrawGoal && (
        <div style={{position:'fixed',inset:0,zIndex:200,background:'rgba(0,0,0,0.5)',display:'flex',alignItems:'center',justifyContent:'center',padding:20}}
          onClick={function(e){if(e.target===e.currentTarget){setWithdrawGoal(null);setWithdrawAmt('');}}}>
          <div style={{background:T.surface,borderRadius:24,padding:24,width:'100%',maxWidth:360,boxShadow:'0 20px 60px rgba(0,0,0,0.2)'}}>
            <div style={{fontSize:24,textAlign:'center',marginBottom:8}}>{withdrawGoal.emoji}</div>
            <div style={{fontSize:16,fontWeight:800,color:T.fg1,textAlign:'center',marginBottom:4}}>Cairkan Tabungan</div>
            <div style={{fontSize:12,color:T.fg3,textAlign:'center',marginBottom:6}}>
              {withdrawGoal.name}
            </div>
            <div style={{fontSize:13,color:'#10b981',textAlign:'center',fontWeight:700,marginBottom:16}}>
              Terkumpul: {fmtRp(withdrawGoal.saved)}
            </div>
            <div style={{display:'flex',alignItems:'center',gap:8,background:T.bg,border:'1.5px solid #f59e0b',borderRadius:12,padding:'0 14px',marginBottom:8}}>
              <span style={{color:T.fg3,fontSize:13}}>Rp</span>
              <input type="text" inputMode="numeric" placeholder="0" value={withdrawAmt} autoFocus
                onChange={function(e){setWithdrawAmt(parseInt(e.target.value.replace(/\D/g,'')||'0').toLocaleString('id-ID'));}}
                style={{flex:1,height:50,border:0,outline:'none',background:'transparent',fontSize:20,fontWeight:800,color:T.fg1,fontFamily:'inherit'}}/>
            </div>
            {withdrawAmt && parseInt(withdrawAmt.replace(/\D/g,''),10) > withdrawGoal.saved && (
              <div style={{fontSize:11,color:'#ef4444',marginBottom:8,textAlign:'center'}}>Melebihi saldo terkumpul</div>
            )}
            <div style={{fontSize:11,color:T.fg3,textAlign:'center',marginBottom:14}}>
              Dana akan dikurangi dari goal. Pastikan sudah ditransfer ke rekening kamu.
            </div>
            <div style={{display:'flex',gap:10}}>
              <button onClick={function(){setWithdrawGoal(null);setWithdrawAmt('');}}
                style={{flex:1,height:46,borderRadius:14,border:'1px solid '+T.border,background:'transparent',color:T.fg2,fontSize:14,fontWeight:600,cursor:'pointer',fontFamily:'inherit'}}>
                Batal
              </button>
              <button onClick={handleWithdraw}
                disabled={!withdrawAmt || parseInt(withdrawAmt.replace(/\D/g,''),10) > withdrawGoal.saved}
                style={{flex:2,height:46,borderRadius:14,border:0,cursor:'pointer',fontFamily:'inherit',
                  background:withdrawAmt&&parseInt(withdrawAmt.replace(/\D/g,''),10)<=withdrawGoal.saved
                    ?'linear-gradient(135deg,#f59e0b,#d97706)':'#ccc',
                  color:'#fff',fontSize:14,fontWeight:700}}>
                Cairkan
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Edit Goal modal */}
      {editGoal && <GoalEditModal theme={T} accent={accent} goal={editGoal}
        accounts={accounts} onClose={function(){setEditGoal(null);}} onSave={handleEditGoal} onDelete={handleDeleteGoal} />}

      {/* Topup modal */}
      {topupGoal && (
        <div style={{position:'fixed',inset:0,zIndex:200,background:'rgba(0,0,0,0.5)',display:'flex',alignItems:'center',justifyContent:'center',padding:20}}
          onClick={function(e){if(e.target===e.currentTarget){setTopupGoal(null);setTopupAmt('');}}}>
          <div style={{background:T.surface,borderRadius:24,padding:24,width:'100%',maxWidth:360,boxShadow:'0 20px 60px rgba(0,0,0,0.2)'}}>
            <div style={{fontSize:24,textAlign:'center',marginBottom:8}}>{topupGoal.emoji}</div>
            <div style={{fontSize:16,fontWeight:800,color:T.fg1,textAlign:'center',marginBottom:4}}>{topupGoal.name}</div>
            <div style={{fontSize:12,color:T.fg3,textAlign:'center',marginBottom:20}}>
              {fmtRp(topupGoal.saved,{short:true})} / {fmtRp(topupGoal.target,{short:true})}
            </div>
            <div style={{display:'flex',alignItems:'center',gap:8,background:T.bg,border:'1.5px solid '+T.border,borderRadius:12,padding:'0 14px',marginBottom:16}}>
              <span style={{color:T.fg3,fontSize:13}}>Rp</span>
              <input type="text" inputMode="numeric" placeholder="0" value={topupAmt} autoFocus
                onChange={function(e){setTopupAmt(parseInt(e.target.value.replace(/\D/g,'')||'0').toLocaleString('id-ID'));}}
                style={{flex:1,height:50,border:0,outline:'none',background:'transparent',fontSize:20,fontWeight:800,color:T.fg1,fontFamily:'inherit'}}/>
            </div>
            <div style={{display:'flex',gap:10}}>
              <button onClick={function(){setTopupGoal(null);setTopupAmt('');}}
                style={{flex:1,height:48,borderRadius:14,border:'1px solid '+T.border,background:'transparent',color:T.fg2,fontSize:14,fontWeight:600,cursor:'pointer',fontFamily:'inherit'}}>
                Batal
              </button>
              <button onClick={handleTopup} disabled={!topupAmt}
                style={{flex:2,height:48,borderRadius:14,border:0,cursor:'pointer',fontFamily:'inherit',
                  background:topupAmt?'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')':'#ccc',
                  color:'#fff',fontSize:14,fontWeight:700}}>
                + Simpan
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── PROFILE ─────────────────────────────────────────────────────
function ScreenProfile({ theme, accent, auth }) {
  var T = theme;
  var _s1=React.useState(false),editing=_s1[0],setEditing=_s1[1];
  var _s2=React.useState((auth&&auth.profile&&auth.profile.full_name)||''),name=_s2[0],setName=_s2[1];
  var _s3=React.useState(false),saving=_s3[0],setSaving=_s3[1];
  var _s4=React.useState(''),msg=_s4[0],setMsg=_s4[1];
  var _s5=React.useState((auth&&auth.profile&&auth.profile.birth_date)||''),birthDate=_s5[0],setBirthDate=_s5[1];
  var _s6=React.useState(false),editingBirth=_s6[0],setEditingBirth=_s6[1];
  var profile = auth&&auth.profile;

  // Hitung usia dari birth_date
  var age = null;
  if (birthDate) {
    var bd = new Date(birthDate);
    var now = new Date();
    age = now.getFullYear() - bd.getFullYear() -
      (now.getMonth() < bd.getMonth() || (now.getMonth()===bd.getMonth() && now.getDate()<bd.getDate()) ? 1 : 0);
  }

  async function handleSaveBirthDate() {
    if (!window.SB || !auth) return;
    setSaving(true);
    await window.SB.from('profiles').update({birth_date: birthDate||null}).eq('id', auth.user.id);
    setSaving(false);
    setEditingBirth(false);
    setMsg('Tanggal lahir disimpan ✓');
    setTimeout(function(){setMsg('');},2000);
  }
  var initial = ((profile&&profile.full_name)||'?')[0].toUpperCase();

  async function handleSave() {
    if(!name.trim()||!window.SB) return;
    setSaving(true);
    var r = await window.SB.from('profiles').update({full_name:name.trim()}).eq('id',auth.user.id);
    setSaving(false);
    if(r.error){setMsg('Gagal: '+r.error.message);return;}
    setMsg('Nama diperbarui ✓'); setEditing(false);
    setTimeout(function(){setMsg('');},2000);
  }

  return (
    <div style={{background:T.bg,minHeight:'100%',paddingBottom:80}}>
      <div style={{padding:'56px 20px 24px'}}>
        <div style={{display:'flex',flexDirection:'column',alignItems:'center',marginBottom:28}}>
          <div style={{width:72,height:72,borderRadius:24,marginBottom:12,
            background:'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')',
            display:'flex',alignItems:'center',justifyContent:'center',fontSize:30,fontWeight:800,color:'#fff'}}>{initial}</div>
          {editing ? (
            <div style={{display:'flex',gap:8,alignItems:'center',width:'100%',maxWidth:280}}>
              <input value={name} onChange={function(e){setName(e.target.value);}} autoFocus
                style={{flex:1,height:44,borderRadius:12,border:'1.5px solid '+accent[500],
                  background:T.bg,color:T.fg1,fontSize:16,fontWeight:700,padding:'0 12px',fontFamily:'inherit',outline:'none',textAlign:'center'}}/>
              <button onClick={handleSave} disabled={saving}
                style={{height:44,borderRadius:12,border:0,cursor:'pointer',background:accent[500],color:'#fff',fontWeight:700,padding:'0 14px',fontSize:14}}>
                {saving?'...':'✓'}
              </button>
              <button onClick={function(){setEditing(false);setName((profile&&profile.full_name)||'');}}
                style={{height:44,borderRadius:12,border:'1px solid '+T.border,background:'transparent',color:T.fg3,cursor:'pointer',padding:'0 12px',fontSize:14}}>
                ✕
              </button>
            </div>
          ) : (
            <div style={{display:'flex',alignItems:'center',gap:8}}>
              <div style={{fontSize:20,fontWeight:800,color:T.fg1}}>{(profile&&profile.full_name)||'Kamu'}</div>
              <button onClick={function(){setEditing(true);}}
                style={{background:'none',border:'none',cursor:'pointer',color:T.fg3,fontSize:14}}>✏️</button>
            </div>
          )}
          <div style={{fontSize:13,color:T.fg3,marginTop:4}}>{auth&&auth.user&&auth.user.email}</div>
          {msg&&<div style={{fontSize:12,color:accent[500],marginTop:6}}>{msg}</div>}
        </div>
        {/* Birth date field — editable */}
        <div style={{marginBottom:12}}>
          <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>
            Tanggal Lahir
          </div>
          {editingBirth ? (
            <div style={{display:'flex',gap:8}}>
              <input type="date" value={birthDate} onChange={function(e){setBirthDate(e.target.value);}}
                style={{flex:1,height:44,borderRadius:12,border:'1.5px solid '+accent[500],
                  background:T.bg,color:T.fg1,fontSize:14,padding:'0 12px',fontFamily:'inherit',outline:'none'}}/>
              <button onClick={handleSaveBirthDate} disabled={saving}
                style={{height:44,borderRadius:12,border:0,cursor:'pointer',background:accent[500],
                  color:'#fff',fontWeight:700,padding:'0 16px',fontSize:14,fontFamily:'inherit'}}>
                {saving?'...':'✓'}
              </button>
              <button onClick={function(){setEditingBirth(false);}}
                style={{height:44,borderRadius:12,border:'1px solid '+T.border,cursor:'pointer',
                  background:'transparent',color:T.fg3,padding:'0 12px',fontFamily:'inherit'}}>✕</button>
            </div>
          ) : (
            <div onClick={function(){setEditingBirth(true);}}
              style={{display:'flex',justifyContent:'space-between',alignItems:'center',
                padding:'12px 16px',background:T.surface,borderRadius:14,border:'1px solid '+T.border,cursor:'pointer'}}>
              <div>
                {birthDate
                  ? <><span style={{fontSize:14,fontWeight:700,color:T.fg1}}>{new Date(birthDate).toLocaleDateString('id-ID',{day:'numeric',month:'long',year:'numeric'})}</span>
                      <span style={{fontSize:12,color:T.fg3,marginLeft:8}}>{age} tahun</span></>
                  : <span style={{fontSize:13,color:T.fg4}}>Belum diisi — tap untuk isi</span>
                }
              </div>
              <span style={{fontSize:12,color:accent[500]}}>✏️</span>
            </div>
          )}
          {!birthDate && (
            <div style={{fontSize:11,color:'#f59e0b',marginTop:4}}>
              ⚠️ Isi tanggal lahir agar usia di FIRE Calculator otomatis terkunci
            </div>
          )}
        </div>

        {[
          {label:'Keluarga',value:(auth&&auth.family&&auth.family.name)||'-',icon:'🏠'},
          {label:'Kode Undangan',value:(auth&&auth.family&&auth.family.invite_code)||'-',icon:'🎟️',mono:true},
          {label:'Role',value:(profile&&profile.role)==='admin'?'👑 Admin':'👤 Member',icon:null},
          {label:'Bergabung',value:(profile&&profile.joined_at)?new Date(profile.joined_at).toLocaleDateString('id-ID'):'-',icon:'📅'},
        ].map(function(item){
          return (
            <div key={item.label} style={{display:'flex',justifyContent:'space-between',alignItems:'center',
              padding:'14px 16px',background:T.surface,borderRadius:14,marginBottom:8,border:'1px solid '+T.border}}>
              <div style={{fontSize:13,color:T.fg3}}>{item.label}</div>
              <div style={{fontSize:14,fontWeight:700,color:T.fg1,fontFamily:item.mono?'monospace':'inherit',letterSpacing:item.mono?'0.15em':'normal'}}>
                {item.icon?item.icon+' ':''}{item.value}
              </div>
            </div>
          );
        })}
        <button onClick={async function(){if(confirm('Yakin keluar?'))await window.SB.auth.signOut();}}
          style={{width:'100%',marginTop:24,height:50,borderRadius:14,border:'1px solid #fecaca',
            background:'rgba(239,68,68,0.05)',color:'#ef4444',fontSize:15,fontWeight:700,cursor:'pointer',fontFamily:'inherit'}}>
          Keluar dari Akun
        </button>
      </div>
    </div>
  );
}

// ─── SECURITY ────────────────────────────────────────────────────
function ScreenSecurity({ theme, accent, auth }) {
  var T = theme;
  var _s1=React.useState(''),np=_s1[0],setNp=_s1[1];
  var _s2=React.useState(''),cp=_s2[0],setCp=_s2[1];
  var _s3=React.useState(false),saving=_s3[0],setSaving=_s3[1];
  var _s4=React.useState(''),msg=_s4[0],setMsg=_s4[1];
  async function handleChange() {
    if(np.length<6){setMsg('Minimal 6 karakter');return;}
    if(np!==cp){setMsg('Password tidak cocok');return;}
    setSaving(true);
    var r = await window.SB.auth.updateUser({password:np});
    setSaving(false);
    if(r.error){setMsg('Error: '+r.error.message);return;}
    setMsg('Password berhasil diubah ✓'); setNp(''); setCp('');
    setTimeout(function(){setMsg('');},3000);
  }
  return (
    <div style={{background:T.bg,minHeight:'100%',padding:'56px 20px',paddingBottom:80}}>
      <h1 style={{fontSize:28,fontWeight:800,color:T.fg1,letterSpacing:'-0.025em',marginBottom:4}}>Keamanan</h1>
      <p style={{fontSize:13,color:T.fg3,marginBottom:28}}>Ubah password akun kamu</p>
      <div style={{background:T.surface,borderRadius:20,padding:20,border:'1px solid '+T.border}}>
        <div style={{fontSize:14,fontWeight:700,color:T.fg1,marginBottom:16}}>🔑 Ubah Password</div>
        {[{label:'Password Baru',val:np,set:setNp,ph:'Minimal 6 karakter'},{label:'Konfirmasi',val:cp,set:setCp,ph:'Ulangi password baru'}].map(function(f){
          return (
            <div key={f.label} style={{marginBottom:12}}>
              <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>{f.label}</div>
              <input type="password" placeholder={f.ph} value={f.val} onChange={function(e){f.set(e.target.value);}}
                style={{width:'100%',height:48,borderRadius:12,border:'1.5px solid '+T.border,background:T.bg,color:T.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}/>
            </div>
          );
        })}
        {msg&&<div style={{fontSize:12,color:msg.includes('✓')?accent[500]:'#ef4444',marginBottom:8}}>{msg}</div>}
        <button onClick={handleChange} disabled={!np||!cp||saving}
          style={{width:'100%',height:50,borderRadius:14,border:0,cursor:'pointer',fontFamily:'inherit',
            background:np&&cp&&!saving?'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')':'#ccc',
            color:'#fff',fontSize:15,fontWeight:700}}>
          {saving?'Menyimpan...':'🔑 Simpan Password Baru'}
        </button>
      </div>
    </div>
  );
}

// ─── EXPORT ──────────────────────────────────────────────────────
function ScreenExport({ theme, accent, auth }) {
  var T = theme;
  var _s1=React.useState(false),loading=_s1[0],setLoading=_s1[1];
  var _s2=React.useState(''),msg=_s2[0],setMsg=_s2[1];
  async function exportCSV() {
    if(!auth||!auth.family||!window.SB) return;
    setLoading(true);
    var r = await window.SB.from('transactions').select('date,type,amount,note,account,category:categories(name)')
      .eq('family_id',auth.family.id).order('date',{ascending:false});
    setLoading(false);
    if(r.error){setMsg('Error: '+r.error.message);return;}
    var rows = r.data||[];
    var csv = 'Tanggal,Tipe,Jumlah,Kategori,Catatan,Akun\n';
    rows.forEach(function(t){
      csv += [t.date,t.type,t.amount,(t.category&&t.category.name)||'',(t.note||'').replace(/,/g,' '),t.account||''].join(',')+'\n';
    });
    var blob = new Blob([csv],{type:'text/csv;charset=utf-8;'});
    var a = document.createElement('a');
    a.href=URL.createObjectURL(blob);
    a.download='indiecash-'+new Date().toISOString().split('T')[0]+'.csv';
    a.click();
    setMsg(rows.length+' transaksi diekspor ✓');
    setTimeout(function(){setMsg('');},3000);
  }
  return (
    <div style={{background:T.bg,minHeight:'100%',padding:'56px 20px',paddingBottom:80}}>
      <h1 style={{fontSize:28,fontWeight:800,color:T.fg1,letterSpacing:'-0.025em',marginBottom:4}}>Export Data</h1>
      <p style={{fontSize:13,color:T.fg3,marginBottom:28}}>Download semua data transaksi</p>
      <div style={{background:T.surface,borderRadius:20,padding:20,border:'1px solid '+T.border,marginBottom:14}}>
        <div style={{fontSize:15,fontWeight:700,color:T.fg1,marginBottom:6}}>📊 Export CSV</div>
        <p style={{fontSize:13,color:T.fg3,lineHeight:1.5,marginBottom:14}}>Semua transaksi dalam format spreadsheet (Excel / Google Sheets)</p>
        <button onClick={exportCSV} disabled={loading}
          style={{width:'100%',height:46,borderRadius:12,border:0,cursor:'pointer',fontFamily:'inherit',
            background:'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')',
            color:'#fff',fontSize:14,fontWeight:700}}>
          {loading?'⏳ Memproses...':'⬇️ Download CSV'}
        </button>
      </div>
      {msg&&<div style={{fontSize:13,color:accent[500],textAlign:'center',fontWeight:600}}>{msg}</div>}
    </div>
  );
}

// ─── HELP ────────────────────────────────────────────────────────
function ScreenHelp({ theme, accent }) {
  var T = theme;
  var _s1=React.useState(null),open=_s1[0],setOpen=_s1[1];
  var faqs = [
    {q:'Cara tambah transaksi?',a:'Tap tombol + hijau di tengah navbar. Pilih tipe, masukkan nominal, pilih kategori, lalu Simpan.'},
    {q:'Cara undang anggota keluarga?',a:'Buka Lainnya → Akun saya. Salin Kode Undangan dan bagikan ke anggota keluarga.'},
    {q:'Apa itu FIRE Calculator?',a:'FIRE (Financial Independence, Retire Early) membantu kamu menghitung kapan bisa pensiun berdasarkan tabungan dan pengeluaran.'},
    {q:'Bagaimana pocket/envelope budgeting bekerja?',a:'Ketika kamu membuat savings goal dan menghubungkannya ke rekening bank, saldo "tersedia" di rekening itu akan dikurangi sebesar jumlah yang sudah terkumpul di goal tersebut. Contoh: BCA 2.2jt, ada goal Jalan-jalan 800rb yang linked → BCA tersedia = 1.4jt.'},
    {q:'Bagaimana pencatatan investasi saham/kripto?',a:'Tambah akun tipe Investasi. Isi "Modal" = total uang yang pernah kamu masukkan. Isi "Nilai sekarang" = harga pasar saat ini. App akan menghitung P&L (profit/loss) otomatis. Update nilai secara berkala sesuai frekuensi yang kamu mau.'},
    {q:'Bagaimana scan struk bekerja?',a:'Buka Lainnya → Scan Struk. Foto atau upload gambar struk, AI akan otomatis membaca nominal dan kategori.'},
    {q:'Apakah data saya aman?',a:'Data disimpan dengan Row Level Security di Supabase — hanya anggota keluarga yang bisa mengakses data kamu.'},
  ];
  return (
    <div style={{background:T.bg,minHeight:'100%',padding:'56px 20px',paddingBottom:80}}>
      <h1 style={{fontSize:28,fontWeight:800,color:T.fg1,letterSpacing:'-0.025em',marginBottom:4}}>Bantuan</h1>
      <p style={{fontSize:13,color:T.fg3,marginBottom:24}}>FAQ &amp; cara penggunaan INDIECASH</p>
      <div style={{display:'flex',flexDirection:'column',gap:8}}>
        {faqs.map(function(faq,i){
          return (
            <div key={i} onClick={function(){setOpen(open===i?null:i);}}
              style={{background:T.surface,borderRadius:16,border:'1px solid '+T.border,overflow:'hidden',cursor:'pointer'}}>
              <div style={{padding:'14px 16px',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
                <div style={{fontSize:14,fontWeight:600,color:T.fg1,flex:1,marginRight:8}}>{faq.q}</div>
                <div style={{fontSize:18,color:T.fg3,flexShrink:0,transform:open===i?'rotate(180deg)':'none',transition:'transform 0.2s'}}>⌄</div>
              </div>
              {open===i&&(
                <div style={{padding:'0 16px 14px',fontSize:13,color:T.fg2,lineHeight:1.6,borderTop:'1px solid '+T.border}}>{faq.a}</div>
              )}
            </div>
          );
        })}
      </div>
      <div style={{marginTop:24,background:accent.tint,borderRadius:16,padding:16,border:'1px solid '+accent[100]}}>
        <div style={{fontSize:14,fontWeight:700,color:accent[700],marginBottom:6}}>💬 Butuh bantuan lebih?</div>
        <div style={{fontSize:13,color:accent[600],fontWeight:600}}>📧 hello@indiecash.id</div>
      </div>
    </div>
  );
}

function UpdateValModal({ theme, accent, account, onClose, onSave }) {
  var T = theme;
  var _s1=React.useState(account.balance?account.balance.toLocaleString('id-ID'):''),newVal=_s1[0],setNewVal=_s1[1];
  var _s2=React.useState(false),saving=_s2[0],setSaving=_s2[1];

  var currentVal = account.balance || 0;
  var newValNum  = parseInt((newVal||'').replace(/\D/g,''),10) || 0;
  var pnlChange  = newValNum - currentVal;
  var totalPnl   = newValNum - (account.cost_basis||0);

  async function handleSave() {
    if (!newValNum || saving) return;
    setSaving(true);
    await window.SB.from('accounts').update({
      balance: newValNum,
      last_updated: new Date().toISOString().split('T')[0],
    }).eq('id', account.id);
    window.dispatchEvent(new Event('tx-added'));
    onSave && onSave();
    onClose();
  }

  return (
    <div style={{
      position:'fixed',inset:0,zIndex:200,
      background:'rgba(0,0,0,0.5)',
      display:'flex',alignItems:'flex-end',justifyContent:'center',
    }} onClick={onClose}>
      <div onClick={function(e){e.stopPropagation();}} style={{
        background:T.surface,borderRadius:'24px 24px 0 0',
        padding:'20px 20px 32px',width:'100%',maxWidth:480,
      }}>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:16}}>
          <div>
            <div style={{fontSize:16,fontWeight:800,color:T.fg1}}>Update Nilai Investasi</div>
            <div style={{fontSize:12,color:T.fg3,marginTop:2}}>{account.name}</div>
          </div>
          <button onClick={onClose} style={{appearance:'none',border:0,background:T.surfaceAlt,
            width:32,height:32,borderRadius:'50%',cursor:'pointer',
            display:'flex',alignItems:'center',justifyContent:'center'}}>
            <Icon name="x" size={16} color={T.fg2} stroke={2}/>
          </button>
        </div>

        {/* Current vs New */}
        <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:12,marginBottom:16}}>
          <div style={{background:T.surfaceAlt,borderRadius:12,padding:'12px 14px'}}>
            <div style={{fontSize:10,color:T.fg3,fontWeight:600,textTransform:'uppercase',letterSpacing:'0.06em',marginBottom:4}}>Nilai Saat Ini</div>
            <div style={{fontSize:18,fontWeight:800,color:T.fg1}}>{fmtRp(currentVal,{short:true})}</div>
            {account.cost_basis > 0 && (
              <div style={{fontSize:10,color:T.fg3,marginTop:2}}>Modal: {fmtRp(account.cost_basis,{short:true})}</div>
            )}
          </div>
          <div style={{background: pnlChange>0?'rgba(16,185,129,0.08)':pnlChange<0?'rgba(239,68,68,0.08)':T.surfaceAlt,
            borderRadius:12,padding:'12px 14px',
            border: pnlChange>0?'1px solid rgba(16,185,129,0.2)':pnlChange<0?'1px solid rgba(239,68,68,0.2)':'none'}}>
            <div style={{fontSize:10,color:T.fg3,fontWeight:600,textTransform:'uppercase',letterSpacing:'0.06em',marginBottom:4}}>Perubahan</div>
            <div style={{fontSize:18,fontWeight:800,color:pnlChange>0?'#10b981':pnlChange<0?'#ef4444':T.fg3}}>
              {pnlChange>0?'+':''}{pnlChange!==0?fmtRp(pnlChange,{short:true}):'—'}
            </div>
            {account.cost_basis > 0 && newValNum > 0 && (
              <div style={{fontSize:10,fontWeight:600,color:totalPnl>=0?'#10b981':'#ef4444',marginTop:2}}>
                Total P&L: {totalPnl>=0?'+':''}{fmtRp(totalPnl,{short:true})}
              </div>
            )}
          </div>
        </div>

        {/* Input nilai baru */}
        <div style={{marginBottom:16}}>
          <div style={{fontSize:11,fontWeight:700,color:T.fg3,textTransform:'uppercase',letterSpacing:'0.08em',marginBottom:8}}>
            Nilai Baru
          </div>
          <div style={{display:'flex',alignItems:'center',gap:8,
            background:T.surfaceAlt,borderRadius:14,padding:'12px 16px',
            border:'2px solid '+accent[300]}}>
            <span style={{color:T.fg3,fontSize:18,fontWeight:700}}>Rp</span>
            <input type="text" inputMode="numeric" autoFocus
              value={newVal}
              onChange={function(e){
                var raw=e.target.value.replace(/\D/g,'');
                setNewVal(raw?parseInt(raw).toLocaleString('id-ID'):'');
              }}
              style={{flex:1,border:0,outline:0,background:'transparent',
                fontFamily:'inherit',fontSize:28,fontWeight:800,color:T.fg1,
                letterSpacing:'-0.02em'}}
            />
          </div>
        </div>

        <button disabled={!newValNum||saving} onClick={handleSave} style={{
          appearance:'none',border:0,width:'100%',height:52,borderRadius:14,
          cursor:newValNum?'pointer':'not-allowed',fontFamily:'inherit',
          background:newValNum?'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')':T.surfaceAlt,
          color:newValNum?'#fff':T.fg4,fontSize:16,fontWeight:700,
          boxShadow:newValNum?'0 6px 20px '+accent[500]+'44':'none',
        }}>
          {saving?'Menyimpan…':'Simpan Nilai Baru'}
        </button>
      </div>
    </div>
  );
}

function GoalEditModal({ theme, accent, goal, accounts, onClose, onSave, onDelete }) {
  var T = theme;
  var _s1 = React.useState(goal.name||''),      gName    = _s1[0], setGName    = _s1[1];
  var _s2 = React.useState(goal.emoji||'🎯'),   gEmoji   = _s2[0], setGEmoji   = _s2[1];
  var _s3 = React.useState(goal.target?goal.target.toLocaleString('id-ID'):''), gTarget = _s3[0], setGTarget = _s3[1];
  var _s4 = React.useState(goal.due||''),        gDate    = _s4[0], setGDate    = _s4[1];
  var _s5 = React.useState(goal.account_id||''), gAcct    = _s5[0], setGAcct    = _s5[1];
  var _s6 = React.useState(false),               saving   = _s6[0], setSaving   = _s6[1];
  var EMOJIS = ['🎯','🏠','🚗','✈️','🎓','💍','📱','💻','🏖️','💰','🐷','🎸','🏥','🎮','📷'];

  async function handleSave() {
    if (!gName.trim()) return;
    setSaving(true);
    await onSave(goal, {
      name:         gName.trim(),
      icon:         gEmoji,
      target_amount:parseInt(gTarget.replace(/\D/g,''),10)||goal.target,
      target_date:  gDate||null,
      account_id:   gAcct||null,
    });
    setSaving(false);
  }

  return (
    <div style={{position:'fixed',inset:0,zIndex:200,background:'rgba(0,0,0,0.5)',display:'flex',alignItems:'flex-end',justifyContent:'center'}}
      onClick={function(e){if(e.target===e.currentTarget)onClose();}}>
      <div style={{background:T.surface,borderRadius:'24px 24px 0 0',padding:'24px 20px 48px',width:'100%',maxWidth:480,maxHeight:'90vh',overflowY:'auto'}}>
        <div style={{width:40,height:4,background:T.border,borderRadius:99,margin:'0 auto 20px'}}/>
        <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:14}}>
          <div style={{fontSize:18,fontWeight:800,color:T.fg1}}>Edit Goal</div>
          <button onClick={function(){onDelete(goal);}}
            style={{fontSize:12,color:'#ef4444',background:'rgba(239,68,68,0.08)',border:0,
              borderRadius:8,padding:'6px 12px',cursor:'pointer',fontWeight:600,fontFamily:'inherit'}}>
            Hapus
          </button>
        </div>
        <div style={{display:'flex',gap:5,flexWrap:'wrap',marginBottom:14}}>
          {EMOJIS.map(function(e){
            return <button key={e} onClick={function(){setGEmoji(e);}}
              style={{width:38,height:38,borderRadius:9,fontSize:18,cursor:'pointer',
                border:'2px solid '+(gEmoji===e?accent[500]:T.border),
                background:gEmoji===e?accent.tint:'transparent'}}>{e}</button>;
          })}
        </div>
        <div style={{marginBottom:12}}>
          <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Nama</div>
          <input type="text" value={gName} onChange={function(e){setGName(e.target.value);}} autoFocus
            style={{width:'100%',height:46,borderRadius:12,border:'1.5px solid '+T.border,
              background:T.bg,color:T.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}/>
        </div>
        <div style={{marginBottom:12}}>
          <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Target Dana</div>
          <div style={{display:'flex',alignItems:'center',gap:8,background:T.bg,border:'1.5px solid '+T.border,borderRadius:12,padding:'0 14px'}}>
            <span style={{color:T.fg3,fontSize:13}}>Rp</span>
            <input type="text" inputMode="numeric" value={gTarget}
              onChange={function(e){setGTarget(parseInt(e.target.value.replace(/\D/g,'')||'0').toLocaleString('id-ID'));}}
              style={{flex:1,height:46,border:0,outline:'none',background:'transparent',fontSize:16,fontWeight:700,color:T.fg1,fontFamily:'inherit'}}/>
          </div>
        </div>
        {accounts && accounts.filter(function(a){return a.type!=='credit';}).length > 0 && (
          <div style={{marginBottom:12}}>
            <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Linked ke Rekening</div>
            <select value={gAcct} onChange={function(e){setGAcct(e.target.value);}}
              style={{width:'100%',height:46,borderRadius:12,border:'1.5px solid '+T.border,
                background:T.bg,color:T.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}>
              <option value="">-- Tidak ada --</option>
              {accounts.filter(function(a){return a.type!=='credit';}).map(function(a){
                return <option key={a.id} value={a.id}>{a.icon} {a.name}</option>;
              })}
            </select>
          </div>
        )}
        <div style={{marginBottom:16}}>
          <div style={{fontSize:12,fontWeight:600,color:T.fg3,marginBottom:6,textTransform:'uppercase',letterSpacing:'0.05em'}}>Target Tanggal</div>
          <input type="date" value={gDate} onChange={function(e){setGDate(e.target.value);}}
            style={{width:'100%',height:46,borderRadius:12,border:'1.5px solid '+T.border,
              background:T.bg,color:T.fg1,fontSize:14,padding:'0 14px',fontFamily:'inherit',outline:'none'}}/>
        </div>
        <div style={{display:'flex',gap:10}}>
          <button onClick={onClose}
            style={{flex:1,height:48,borderRadius:14,border:'1px solid '+T.border,background:'transparent',
              color:T.fg2,fontSize:14,fontWeight:600,cursor:'pointer',fontFamily:'inherit'}}>
            Batal
          </button>
          <button onClick={handleSave} disabled={!gName.trim()||saving}
            style={{flex:2,height:48,borderRadius:14,border:0,cursor:'pointer',fontFamily:'inherit',
              background:gName.trim()&&!saving?'linear-gradient(135deg,'+accent.grad[0]+','+accent.grad[1]+')':'#ccc',
              color:'#fff',fontSize:15,fontWeight:700}}>
            {saving?'Menyimpan...':'✓ Simpan Perubahan'}
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenAccounts, AccountModal, ScreenGoals, GoalEditModal, ScreenProfile, ScreenSecurity, ScreenExport, ScreenHelp });
