// accounts-ui.jsx — Multi-account breakdown UI for Geld → Overzicht
// Shows balance per rekening, with kind badge and quick "telt mee" hint.
// Tap a row → open AccountSheet (rename + kind + sharePct slider).

const TB_ACCT = SAGE;

function AccountsBreakdown({ state, set, toast }) {
  const rawAccounts = state.bank?.accounts || [];
  // Volgorde: persoonlijk boven, gezamenlijk daarna, dan spaar/overig.
  const kindOrder = { personal: 0, shared: 1, savings: 2, other: 3 };
  const accounts = [...rawAccounts].sort(
    (a, b) => (kindOrder[a.kind] ?? 9) - (kindOrder[b.kind] ?? 9)
  );
  const [editing, setEditing] = React.useState(null);  // uid being edited
  const total = accounts.reduce((s, a) => s + (typeof a.balance === 'number' ? a.balance : 0), 0);

  const updateAccount = (uid, patch) => {
    set(s => ({
      ...s,
      bank: {
        ...(s.bank || {}),
        accounts: (s.bank?.accounts || []).map(a => a.uid === uid ? { ...a, ...patch } : a),
      },
    }));
  };

  return (
    <React.Fragment>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8 }}>
        <div className="vb-cap" style={{ color: TB_ACCT.inkFaint }}>rekeningen</div>
        <div className="vb-num" style={{ fontSize: 13, color: TB_ACCT.inkSoft, fontWeight: 500 }}>
          totaal {fmtEurShort(total)}
        </div>
      </div>
      <div className="vb-card" style={{ padding: 0, marginBottom: 18 }}>
        {accounts.map((a, i) => (
          <AccountRow
            key={a.uid}
            account={a}
            isLast={i === accounts.length - 1}
            txCount={(state.bank?.transactions || []).filter(t => t.accountUid === a.uid).length}
            onTap={() => setEditing(a.uid)}
          />
        ))}
      </div>

      {editing && (
        <AccountSheet
          account={accounts.find(a => a.uid === editing)}
          onClose={() => setEditing(null)}
          onSave={(patch) => {
            updateAccount(editing, patch);
            toast?.('Rekening opgeslagen');
            setEditing(null);
          }}
        />
      )}
    </React.Fragment>
  );
}

function AccountRow({ account, isLast, txCount, onTap }) {
  const meta = (KIND_META && KIND_META[account.kind]) || KIND_META.other;
  const sharePct = account.sharePct != null
    ? account.sharePct
    : (DEFAULT_SHARE_BY_KIND[account.kind] ?? 100);
  return (
    <div onClick={onTap} style={{
      display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px',
      borderTop: isLast ? 'none' : '',
      borderBottom: isLast ? 'none' : `1px solid ${TB_ACCT.hairline}`,
      cursor: 'pointer',
    }}>
      <div style={{
        width: 38, height: 38, borderRadius: 11,
        background: meta.color + '22', color: meta.color,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 18, flexShrink: 0,
      }}>{meta.icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 500, color: TB_ACCT.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {account.label || 'Rekening'}
        </div>
        <div style={{ fontSize: 11, color: TB_ACCT.inkFaint, display: 'flex', gap: 6, alignItems: 'center' }}>
          <span>{meta.label}</span>
          {sharePct !== 100 && (
            <span style={{
              padding: '1px 6px', borderRadius: 99, background: TB_ACCT.bg,
              fontWeight: 600, color: TB_ACCT.inkSoft,
            }}>{sharePct}% telt mee</span>
          )}
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div className="vb-num" style={{ fontSize: 16, fontWeight: 600, color: TB_ACCT.ink, letterSpacing: -0.3 }}>
          {account.balance != null ? fmtEurShort(account.balance) : '—'}
        </div>
        {txCount > 0 && (
          <div style={{ fontSize: 10, color: TB_ACCT.inkFaint, marginTop: 2 }}>{txCount} tx</div>
        )}
      </div>
      <svg width="6" height="10" viewBox="0 0 8 14" style={{ marginLeft: 4, opacity: 0.4 }}>
        <path d="M1 1l6 6-6 6" stroke={TB_ACCT.inkFaint} strokeWidth="2" fill="none" strokeLinecap="round"/>
      </svg>
    </div>
  );
}

function AccountSheet({ account, onClose, onSave }) {
  const [label, setLabel] = React.useState(account?.label || '');
  const [kind, setKind] = React.useState(account?.kind || 'other');
  const [sharePct, setSharePct] = React.useState(
    account?.sharePct != null ? account.sharePct : (DEFAULT_SHARE_BY_KIND[account?.kind] ?? 100)
  );
  // When kind changes, reset sharePct to default unless user explicitly overrode it
  const [userOverrode, setUserOverrode] = React.useState(account?.sharePct != null);

  React.useEffect(() => {
    if (!userOverrode) setSharePct(DEFAULT_SHARE_BY_KIND[kind] ?? 100);
  }, [kind, userOverrode]);

  const submit = () => {
    onSave({
      label: label.trim() || account?.label || 'Rekening',
      kind,
      sharePct: userOverrode ? sharePct : null,
    });
  };

  if (!account) return null;

  const kindOpts = [
    { id: 'personal', meta: KIND_META.personal },
    { id: 'shared',   meta: KIND_META.shared },
    { id: 'savings',  meta: KIND_META.savings },
    { id: 'other',    meta: KIND_META.other },
  ];

  const sheet = (
    <div onClick={onClose} style={{
      position: 'absolute', inset: 0, zIndex: 9990,
      background: 'rgba(28,42,36,0.32)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
    }}>
      <div onClick={e => e.stopPropagation()} className="vb-sheet" style={{
        width: '100%', background: TB_ACCT.bg, borderTopLeftRadius: 28, borderTopRightRadius: 28,
        padding: '14px 18px calc(28px + env(safe-area-inset-bottom, 0px))',
        maxHeight: '90%', overflow: 'auto',
        boxShadow: '0 -20px 60px rgba(0,0,0,0.18)',
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 2, background: TB_ACCT.hairline, margin: '0 auto 16px' }} />
        <div className="vb-display" style={{ fontSize: 20, marginBottom: 4 }}>Rekening bewerken</div>
        {account.iban && (
          <div style={{ fontSize: 11, color: TB_ACCT.inkFaint, fontFamily: 'ui-monospace, monospace', marginBottom: 14 }}>
            {account.iban}
          </div>
        )}

        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* Label */}
          <div>
            <label style={{ fontSize: 12, color: TB_ACCT.inkSoft, display: 'block', marginBottom: 6 }}>Naam</label>
            <input value={label} onChange={e => setLabel(e.target.value)} placeholder="bv. Mijn rekening"
              style={{
                width: '100%', padding: '12px 14px', fontSize: 15, border: `1px solid ${TB_ACCT.hairline}`,
                borderRadius: 12, background: TB_ACCT.card, outline: 'none', boxSizing: 'border-box',
                fontFamily: 'inherit', color: TB_ACCT.ink,
              }} />
          </div>

          {/* Kind */}
          <div>
            <label style={{ fontSize: 12, color: TB_ACCT.inkSoft, display: 'block', marginBottom: 6 }}>Type rekening</label>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
              {kindOpts.map(opt => (
                <button key={opt.id} onClick={() => { setKind(opt.id); setUserOverrode(false); }} style={{
                  padding: '12px 8px', borderRadius: 12, border: 'none', cursor: 'pointer',
                  background: kind === opt.id ? opt.meta.color : TB_ACCT.card,
                  color: kind === opt.id ? '#fff' : TB_ACCT.ink,
                  fontSize: 13, fontWeight: 500, fontFamily: 'inherit',
                  display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'center',
                  transition: 'all .15s',
                }}>
                  <span style={{ fontSize: 16 }}>{opt.meta.icon}</span>
                  {opt.meta.label}
                </button>
              ))}
            </div>
          </div>

          {/* Share pct */}
          <div>
            <label style={{ fontSize: 12, color: TB_ACCT.inkSoft, display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
              <span>Telt mee voor "veilig uit te geven"</span>
              <span className="vb-num" style={{ fontWeight: 600, color: TB_ACCT.ink }}>{sharePct}%</span>
            </label>
            <input type="range" min="0" max="100" step="5"
              value={sharePct}
              onChange={e => { setSharePct(Number(e.target.value)); setUserOverrode(true); }}
              style={{ width: '100%', accentColor: TB_ACCT.accent }} />
            <div style={{ fontSize: 11, color: TB_ACCT.inkFaint, marginTop: 4, lineHeight: 1.4 }}>
              {sharePct === 0 && 'Uitgaven van deze rekening tellen niet mee.'}
              {sharePct > 0 && sharePct < 100 && `Bij gezamenlijke rekening houden we ${sharePct}% van de uitgaven als jouw deel.`}
              {sharePct === 100 && 'Alle uitgaven tellen volledig mee.'}
            </div>
          </div>
        </div>

        <button onClick={submit} style={{
          width: '100%', marginTop: 18, padding: '14px', borderRadius: 14, border: 'none',
          background: TB_ACCT.accent, color: '#fff', fontSize: 15, fontWeight: 600,
          cursor: 'pointer', fontFamily: 'inherit',
        }}>Opslaan</button>
      </div>
    </div>
  );
  const mount = (typeof document !== 'undefined')
    ? (document.querySelector('.app-shell') || document.body) : null;
  return (mount && typeof ReactDOM !== 'undefined' && ReactDOM.createPortal)
    ? ReactDOM.createPortal(sheet, mount) : sheet;
}

// Compact account chip — used in Inbox row and Recent expense row
function AccountChip({ state, accountUid }) {
  const a = (state.bank?.accounts || []).find(x => x.uid === accountUid);
  if (!a) return null;
  const meta = (KIND_META && KIND_META[a.kind]) || KIND_META.other;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: '2px 8px', borderRadius: 99,
      background: meta.color + '18', color: meta.color,
      fontSize: 10, fontWeight: 700, letterSpacing: 0.1,
    }} title={a.label}>
      <span style={{ fontSize: 11 }}>{meta.icon}</span>
      <span>{a.kind === 'shared' ? 'gez' : a.kind === 'personal' ? 'pers' : a.kind === 'savings' ? 'spaar' : 'overig'}</span>
    </span>
  );
}

Object.assign(window, { AccountsBreakdown, AccountRow, AccountSheet, AccountChip });
