// vault.jsx — Multi-sig fond reparații. Admin + Tenant views.

// ─────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────
function vaultTxStatus(tx) {
  if (tx.status === 'executed')  return { label: 'Executat',           color: '#059669', bg: '#D1FAE5' };
  if (tx.status === 'rejected')  return { label: 'Respins',            color: '#DC2626', bg: '#FADEDB' };
  if (tx.status === 'cancelled') return { label: 'Anulat',             color: '#6B7280', bg: '#F3F4F6' };
  return                              { label: 'Așteaptă semnături',color: '#D97706', bg: '#FEF3C7' };
}

function vaultTxSigStatus(tx) {
  const committeeSigners = window.VAULT_SIGNERS.filter(s => s.role !== 'admin');
  const adminSigned = tx.signatures?.some(s => s.signer_id === 's1');
  const committeeSigned = tx.signatures?.filter(s => s.signer_id !== 's1').length || 0;
  const adminRequired = window.VAULT_RULES.threshold_admin;
  const committeeRequired = window.VAULT_RULES.threshold_committee;
  return {
    adminSigned, committeeSigned,
    adminRequired, committeeRequired,
    total: tx.signatures?.length || 0,
    threshold: adminRequired + committeeRequired,
    canExecute: adminSigned && committeeSigned >= committeeRequired,
  };
}

function signerById(id) { return window.VAULT_SIGNERS.find(s => s.id === id); }

// ═════════════════════════════════════════════════════════════
// ADMIN — Vault screen (full control)
// ═════════════════════════════════════════════════════════════
function VaultScreen({ state, tr, lang }) {
  const [selected, setSelected] = React.useState(null);
  const [tab, setTab] = React.useState('pending');
  const [showCreate, setShowCreate] = React.useState(false);
  const [signerSwitchOpen, setSignerSwitchOpen] = React.useState(false);

  const pending = state.vaultTx.filter(t => t.status === 'pending_signatures');
  const executed = state.vaultTx.filter(t => t.status === 'executed');
  const rejected = state.vaultTx.filter(t => t.status === 'rejected' || t.status === 'cancelled');

  const yearOut = executed.filter(t => t.type === 'outflow').reduce((s, t) => s + t.amount, 0);
  const yearIn = executed.filter(t => t.type === 'inflow').reduce((s, t) => s + t.amount, 0);

  const currentSigner = signerById(state.currentSigner);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title="Fond reparații · Vault"
        subtitle="Bani protejați multi-semnătură · Admin + 2 din 3 membri comitet"
        right={<div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
          <button onClick={() => setSignerSwitchOpen(true)} title="Schimbă rolul (demo)" style={{
            display: 'inline-flex', alignItems: 'center', gap: 8,
            padding: '8px 12px', borderRadius: 10,
            background: 'var(--surface)', border: '1px solid var(--border)',
            cursor: 'pointer', fontFamily: 'inherit', fontSize: 12.5, color: 'var(--ink-2)',
          }}>
            <span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--success)' }} />
            Vezi ca <b style={{ color: 'var(--ink)' }}>{currentSigner?.name.split(' ')[0]}</b>
            <Icon name="chevDown" size={13} />
          </button>
          <Button variant="primary" icon="plus" onClick={() => setShowCreate(true)}>Plată nouă</Button>
        </div>}
      />

      {/* Trust banner */}
      <Card style={{ background: 'linear-gradient(135deg, #DDF0E4, #c6e6d2)', border: '1px solid #059669', boxShadow: '0 1px 2px rgba(28, 22, 12, 0.04)' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
          <div style={{ width: 44, height: 44, borderRadius: 12, background: '#059669', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22, flexShrink: 0 }}>🔐</div>
          <div style={{ flex: 1, fontSize: 13.5, color: '#065F46', lineHeight: 1.55 }}>
            <b>Cum funcționează:</b> orice plată din fondul de reparații necesită <b>3 semnături</b> — administratorul (obligatoriu) + 2 membri comitet din 3. Banii nu pot fi mutați de o singură persoană. Tranzacțiile cu factură ANAF e-Factura sunt validate automat. Locatarii văd public balanța și toate plățile.
          </div>
        </div>
      </Card>

      {/* Balance + stats */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr 1fr', gap: 'var(--gap)' }}>
        <Card style={{ background: 'linear-gradient(135deg, #1F4738, #173329)', color: '#fff' }}>
          <div style={{ fontSize: 11, opacity: 0.7, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>Sold cont fond reparații</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 36, fontWeight: 700, letterSpacing: '-0.02em', lineHeight: 1 }}>
            <Ticker value={state.vault.balance} decimals={2} /> <span style={{ fontSize: 18, opacity: 0.6 }}>RON</span>
          </div>
          <div style={{ fontSize: 12, opacity: 0.8, marginTop: 10, fontFamily: 'var(--font-mono)' }}>
            {state.vault.bank_account}
          </div>
          <div style={{ fontSize: 11, opacity: 0.65, marginTop: 4 }}>
            {state.vault.bank} · deschis {new Date(state.vault.opened_at).toLocaleDateString('ro-RO', { day: 'numeric', month: 'long', year: 'numeric' })}
          </div>
        </Card>
        <SummaryCard icon="arrowRight" iconBg="#FADEDB" iconColor="#A8482F" label="Ieșit anul 2025" value={<>{window.fmtRONshort(yearOut)} <span style={{ fontSize: 16, color: 'var(--muted)' }}>RON</span></>} sub={`${executed.filter(t => t.type === 'outflow').length} plăți executate`} />
        <SummaryCard icon="arrowLeft" iconBg="#DDF0E4" iconColor="#065F46" label="Intrat 2025" value={<>{window.fmtRONshort(yearIn)} <span style={{ fontSize: 16, color: 'var(--muted)' }}>RON</span></>} sub={`${state.vault.monthly_collection.toFixed(0)} RON/lună din lista de plată`} />
        <SummaryCard icon="clock" iconBg="#FEF3C7" iconColor="#92400E" label="În așteptare" value={<>{pending.length} <span style={{ fontSize: 16, color: 'var(--muted)' }}>plăți</span></>} sub={`${window.fmtRONshort(pending.reduce((s, t) => s + t.amount, 0))} RON cer semnături`} />
      </div>

      {/* Signers */}
      <Card>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, margin: 0, color: 'var(--ink)' }}>
            Semnatari
          </h3>
          <span style={{ fontSize: 12, color: 'var(--muted)' }}>
            Regulă: <b style={{ color: 'var(--ink-2)' }}>1 admin + 2 din 3 comitet</b> · sau <b style={{ color: 'var(--ink-2)' }}>AGA ≥ 7 voturi</b>
          </span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
          {window.VAULT_SIGNERS.map(s => (
            <div key={s.id} style={{
              padding: 14, borderRadius: 12,
              background: state.currentSigner === s.id ? 'var(--primary-light)' : 'var(--surface-2)',
              border: state.currentSigner === s.id ? '1.5px solid var(--primary)' : '1px solid var(--border)',
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <div style={{
                width: 40, height: 40, borderRadius: 999,
                background: s.role === 'admin' ? 'var(--accent)' : 'var(--primary)', color: '#fff',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontWeight: 700, fontSize: 14, fontFamily: 'var(--font-display)',
              }}>{s.name.split(' ').map(p => p[0]).join('').slice(0, 2)}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.name}</div>
                <div style={{ fontSize: 11, color: 'var(--muted)', display: 'flex', alignItems: 'center', gap: 4 }}>
                  {s.role === 'admin' && <span style={{ padding: '1px 6px', borderRadius: 4, background: 'var(--accent)', color: '#fff', fontSize: 9, fontWeight: 700, letterSpacing: '0.05em' }}>ADMIN</span>}
                  <span>{s.bio}</span>
                </div>
              </div>
            </div>
          ))}
        </div>
      </Card>

      {/* Tabs */}
      <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--surface-2)', borderRadius: 12, width: 'fit-content' }}>
        {[
          { id: 'pending',  label: `În așteptare (${pending.length})` },
          { id: 'executed', label: `Executate (${executed.length})` },
          { id: 'rejected', label: `Respinse (${rejected.length})` },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '8px 16px', borderRadius: 8, border: 0, cursor: 'pointer',
            background: tab === t.id ? 'var(--surface)' : 'transparent',
            color: tab === t.id ? 'var(--ink)' : 'var(--muted)',
            fontFamily: 'inherit', fontSize: 13.5, fontWeight: 600,
            boxShadow: tab === t.id ? '0 1px 2px rgba(28,22,12,0.08)' : 'none',
          }}>{t.label}</button>
        ))}
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
        {(tab === 'pending' ? pending : tab === 'executed' ? executed : rejected).map(tx => (
          <VaultTxCard key={tx.id} tx={tx} state={state} onClick={() => setSelected(tx)} />
        ))}
        {((tab === 'pending' && pending.length === 0) || (tab === 'rejected' && rejected.length === 0)) && (
          <Card><div style={{ textAlign: 'center', padding: 20, color: 'var(--muted)', fontSize: 13.5 }}>Nimic aici.</div></Card>
        )}
      </div>

      <Drawer open={!!selected} onClose={() => setSelected(null)} title={selected ? `Plată #${selected.id}` : ''} width={620}>
        {selected && <VaultTxDetail tx={state.vaultTx.find(x => x.id === selected.id) || selected} state={state} lang={lang} />}
      </Drawer>

      <VaultCreateModal open={showCreate} onClose={() => setShowCreate(false)} state={state} lang={lang} />
      <SignerSwitchModal open={signerSwitchOpen} onClose={() => setSignerSwitchOpen(false)} state={state} />
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Transaction card
// ─────────────────────────────────────────────────────────────
function VaultTxCard({ tx, state, onClick }) {
  const st = vaultTxStatus(tx);
  const sig = vaultTxSigStatus(tx);
  const proposer = signerById(tx.proposed_by);
  const daysUntil = tx.deadline ? Math.ceil((new Date(tx.deadline) - new Date('2025-11-15T18:00:00')) / 86400000) : null;

  return (
    <Card onClick={onClick}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
        <div style={{
          width: 48, height: 48, borderRadius: 12, flexShrink: 0,
          background: tx.type === 'inflow' ? '#DDF0E4' : '#F8E0D5',
          color: tx.type === 'inflow' ? '#065F46' : '#A8482F',
          display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 22,
        }}>{tx.type === 'inflow' ? '↘' : '↗'}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <span style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, color: 'var(--ink)' }}>{tx.title}</span>
            {tx.invoice?.anaf_validated && (
              <span title="Validat ANAF e-Factura" style={{ display: 'inline-flex', alignItems: 'center', gap: 3, padding: '2px 7px', borderRadius: 999, background: '#E0F2FE', color: '#0369A1', fontSize: 10, fontWeight: 700 }}>
                ✓ ANAF
              </span>
            )}
          </div>
          {tx.description && (
            <div style={{ fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.4, marginBottom: 6 }}>
              {tx.description.slice(0, 110)}{tx.description.length > 110 ? '...' : ''}
            </div>
          )}
          <div style={{ display: 'flex', gap: 14, fontSize: 11.5, color: 'var(--muted)', alignItems: 'center' }}>
            {tx.payee && <span>→ <b style={{ color: 'var(--ink-2)' }}>{tx.payee}</b></span>}
            {proposer && <span>· propus de {proposer.name.split(' ')[0]}</span>}
            <span>· {new Date(tx.proposed_at).toLocaleDateString('ro-RO', { day: 'numeric', month: 'short' })}</span>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6, flexShrink: 0 }}>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 18, fontWeight: 700, color: tx.type === 'inflow' ? 'var(--success)' : 'var(--ink)' }}>
            {tx.type === 'inflow' ? '+' : '-'}{window.fmtRONshort(tx.amount)} RON
          </div>
          {tx.status === 'pending_signatures' ? (
            <SignatureRing tx={tx} />
          ) : (
            <span style={{ padding: '3px 9px', borderRadius: 999, background: st.bg, color: st.color, fontSize: 11, fontWeight: 600 }}>{st.label}</span>
          )}
        </div>
      </div>
    </Card>
  );
}

// ─────────────────────────────────────────────────────────────
// Signature ring — visual indicator of how many signed
// ─────────────────────────────────────────────────────────────
function SignatureRing({ tx, large }) {
  const sig = vaultTxSigStatus(tx);
  const size = large ? 56 : 28;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
      <div style={{ display: 'flex', gap: -4 }}>
        {window.VAULT_SIGNERS.map((s, i) => {
          const signed = tx.signatures?.some(x => x.signer_id === s.id);
          const rejected = tx.rejections?.some(x => x.signer_id === s.id);
          return (
            <div key={s.id} title={`${s.name} — ${signed ? 'semnat' : rejected ? 'respins' : 'nu a semnat'}`} style={{
              width: size / 2 + 4, height: size / 2 + 4, borderRadius: 999,
              background: signed ? 'var(--success)' : rejected ? 'var(--danger)' : 'var(--neutral-bg)',
              color: signed || rejected ? '#fff' : 'var(--muted)',
              border: '2px solid var(--surface)',
              marginLeft: i > 0 ? -6 : 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: large ? 12 : 9, fontWeight: 700, fontFamily: 'var(--font-mono)',
            }}>{signed ? '✓' : rejected ? '✗' : s.name.split(' ').map(p => p[0]).join('').slice(0, 1)}</div>
          );
        })}
      </div>
      <span style={{ fontFamily: 'var(--font-mono)', fontSize: large ? 14 : 11, fontWeight: 700, color: sig.canExecute ? 'var(--success)' : 'var(--ink-2)' }}>
        {sig.total}/{sig.threshold}
      </span>
    </div>
  );
}

window.VaultScreen = VaultScreen;
window.SignatureRing = SignatureRing;
window.vaultTxStatus = vaultTxStatus;
window.vaultTxSigStatus = vaultTxSigStatus;
window.signerById = signerById;
