// admin.jsx — Admin (desktop) — sidebar + screens

function AdminApp({ state, tr, t, setTweak, lang }) {
  const [screen, setScreen] = React.useState('dashboard');
  const [calculating, setCalculating] = React.useState(false);

  return (
    <div style={{ display: 'flex', minHeight: '100vh', paddingTop: 72 }}>
      <AdminSidebar screen={screen} setScreen={setScreen} tr={tr} lang={lang} state={state} />
      <main style={{ flex: 1, padding: '24px 32px 60px', minWidth: 0 }}>
        {screen === 'dashboard'  && <DashboardScreen state={state} tr={tr} setScreen={setScreen} lang={lang} />}
        {screen === 'expenses'   && <ExpensesScreen  state={state} tr={tr} lang={lang} calculating={calculating} setCalculating={setCalculating} setScreen={setScreen} />}
        {screen === 'efactura'   && <EFacturaScreen  state={state} tr={tr} lang={lang} />}
        {screen === 'apartments' && <ApartmentsScreen state={state} tr={tr} viewMode={t.aptView} lang={lang} />}
        {screen === 'monthly'    && <MonthlyListScreen state={state} tr={tr} lang={lang} />}
        {screen === 'rules'      && <RulesScreen state={state} tr={tr} lang={lang} />}
        {screen === 'compliance' && <ComplianceScreen state={state} tr={tr} lang={lang} />}
        {screen === 'arrears'    && <ArrearsScreen state={state} tr={tr} lang={lang} />}
        {screen === 'score'      && <ScoreScreen state={state} tr={tr} lang={lang} />}
        {screen === 'whatsapp'   && <WhatsAppScreen state={state} tr={tr} lang={lang} />}
        {screen === 'budget'     && <BudgetScreen state={state} tr={tr} lang={lang} />}
        {screen === 'access'     && <AccessScreen state={state} tr={tr} lang={lang} />}
        {screen === 'announcements' && <AnnouncementsScreen state={state} tr={tr} lang={lang} />}
        {screen === 'legal'      && <LegalScreen state={state} tr={tr} lang={lang} />}
        {screen === 'audit'      && <AuditScreen state={state} tr={tr} lang={lang} />}
        {screen === 'cadastre'   && <CadastreScreen state={state} tr={tr} lang={lang} />}
        {screen === 'fiscal'     && <FiscalScreen state={state} tr={tr} lang={lang} />}
        {screen === 'onboarding' && <OnboardingScreen state={state} tr={tr} lang={lang} />}
        {screen === 'emergencies'&& <EmergenciesScreen state={state} tr={tr} lang={lang} />}
        {screen === 'vault'      && <VaultScreen state={state} tr={tr} lang={lang} />}
        {screen === 'issues'     && <IssuesScreen state={state} tr={tr} lang={lang} />}
        {screen === 'aga'        && <AGAScreen state={state} tr={tr} lang={lang} />}
        {screen === 'reports'    && <ReportsScreen state={state} tr={tr} lang={lang} />}
      </main>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Sidebar
// ─────────────────────────────────────────────────────────────
function AdminSidebar({ screen, setScreen, tr, lang, state }) {
  const newIssues = state?.issues?.filter(i => i.status === 'nou').length || 0;
  const activeProposals = state?.proposals?.filter(p => p.status === 'active').length || 0;
  const activeEmerg = state?.activeEmergency ? 1 : 0;
  const pendingTx = state?.vaultTx?.filter(t => t.status === 'pending_signatures').length || 0;
  const pendingFactura = window.EFACTURA_INBOX?.filter(f => f.status === 'pending').length || 0;
  const expiredCompliance = window.COMPLIANCE_ITEMS?.filter(c => {
    const s = window.complianceStatus(c);
    return s.state === 'expired' || s.state === 'urgent';
  }).length || 0;
  const debtors = Object.keys(window.ARREARS_LEDGER || {}).length;

  const sections = [
    { title: null, items: [
      { id: 'dashboard',  label: tr('nav.dashboard'),  icon: 'home' },
    ]},
    { title: 'Zilnic', items: [
      { id: 'issues',     label: 'Sesizări', icon: 'bell', badge: newIssues, badgeColor: 'var(--danger)' },
      { id: 'emergencies',label: 'Avarii', icon: 'flame', badge: activeEmerg, badgeColor: 'var(--danger)', pulse: activeEmerg > 0 },
      { id: 'access',     label: 'Acces apartament', icon: 'door' },
      { id: 'announcements', label: 'Anunțuri', icon: 'mail' },
      { id: 'whatsapp',   label: 'WhatsApp Bot', icon: 'phone' },
    ]},
    { title: 'Bani', items: [
      { id: 'expenses',   label: tr('nav.expenses'),   icon: 'receipt' },
      { id: 'efactura',   label: 'e-Factura', icon: 'mail', badge: pendingFactura, badgeColor: '#0EA5E9' },
      { id: 'monthly',    label: tr('nav.monthly'),    icon: 'list' },
      { id: 'arrears',    label: 'Restanțieri', icon: 'clock', badge: debtors, badgeColor: 'var(--danger)' },
      { id: 'vault',      label: 'Fond reparații', icon: 'spark', badge: pendingTx, badgeColor: 'var(--warning)' },
      { id: 'budget',     label: 'Buget anual', icon: 'calc' },
    ]},
    { title: 'Scară', items: [
      { id: 'apartments', label: tr('nav.apartments'), icon: 'building' },
      { id: 'rules',      label: 'Reguli scară', icon: 'sliders' },
      { id: 'compliance', label: 'Verificări obligatorii', icon: 'check', badge: expiredCompliance, badgeColor: 'var(--danger)', pulse: expiredCompliance > 0 },
      { id: 'aga',        label: 'Hotărâri AGA', icon: 'users', badge: activeProposals, badgeColor: 'var(--primary)' },
      { id: 'legal',      label: 'Legal & Documente', icon: 'sparkles' },
      { id: 'audit',      label: 'Audit cenzor', icon: 'check' },
      { id: 'cadastre',   label: 'Cadastru ANCPI', icon: 'building' },
      { id: 'fiscal',     label: 'Declarații fiscale', icon: 'receipt' },
      { id: 'onboarding', label: 'Onboarding', icon: 'plus' },
    ]},
    { title: 'Insight', items: [
      { id: 'reports',    label: tr('nav.reports'),    icon: 'chart' },
      { id: 'score',      label: 'BlocApp Score', icon: 'sparkles' },
    ]},
  ];
  return (
    <aside style={{
      width: 240, flexShrink: 0,
      borderRight: '1px solid var(--border)',
      padding: '20px 12px',
      display: 'flex', flexDirection: 'column',
      background: 'var(--surface)',
      height: '100vh', position: 'sticky', top: 0,
    }}>
      <div style={{ padding: '0 8px 24px', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{
          width: 36, height: 36, borderRadius: 10,
          background: 'var(--primary)', color: '#fff',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18,
          boxShadow: '0 4px 12px color-mix(in oklab, var(--primary), transparent 70%)',
        }}>B</div>
        <div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 700, color: 'var(--ink)', letterSpacing: '-0.01em' }}>BlocApp</div>
          <div style={{ fontSize: 11.5, color: 'var(--muted)', fontWeight: 500 }}>{window.BUILDING.name}</div>
        </div>
      </div>

      <nav style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 1, overflowY: 'auto', minHeight: 0 }}>
        {sections.map((section, si) => (
          <div key={si} style={{ marginTop: section.title ? 14 : 0 }}>
            {section.title && (
              <div style={{ padding: '6px 12px 4px', fontSize: 10, fontWeight: 700, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
                {section.title}
              </div>
            )}
            {section.items.map(item => {
              const active = screen === item.id;
              return (
                <button key={item.id} onClick={() => setScreen(item.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  width: '100%',
                  padding: '0 12px', height: 36,
                  border: 0, background: active ? 'var(--primary-light)' : 'transparent',
                  color: active ? 'var(--primary)' : 'var(--ink-2)',
                  borderRadius: 8, cursor: 'pointer',
                  fontFamily: 'inherit', fontSize: 13.5, fontWeight: active ? 600 : 500,
                  textAlign: 'left', letterSpacing: '-0.005em',
                  transition: 'background 160ms ease, color 160ms ease',
                }}
                onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = 'var(--surface-2)'; }}
                onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = 'transparent'; }}
                >
                  <Icon name={item.icon} size={16} stroke={active ? 2 : 1.7} />
                  <span style={{ flex: 1 }}>{item.label}</span>
                  {item.badge > 0 && (
                    <span style={{
                      display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                      minWidth: 18, height: 18, padding: '0 5px',
                      background: item.badgeColor, color: '#fff',
                      borderRadius: 999, fontSize: 10.5, fontWeight: 700,
                      fontFamily: 'var(--font-mono)',
                    }}>{item.badge}</span>
                  )}
                </button>
              );
            })}
          </div>
        ))}
      </nav>

      <div style={{ marginTop: 'auto', padding: '16px 8px 0', borderTop: '1px solid var(--border)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 0' }}>
          <div style={{
            width: 36, height: 36, borderRadius: 999,
            background: 'var(--accent)', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontWeight: 600, fontSize: 14,
          }}>IV</div>
          <div style={{ minWidth: 0 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>{window.BUILDING.admin_name}</div>
            <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{lang === 'ro' ? 'Administrator' : 'Admin'}</div>
          </div>
        </div>
      </div>
    </aside>
  );
}

// ═════════════════════════════════════════════════════════════
// 1. Dashboard
// ═════════════════════════════════════════════════════════════
function DashboardScreen({ state, tr, setScreen, lang }) {
  const { totals, charges, payments, apartments, aptStatus } = state;
  const collectRatio = totals.totalDue > 0 ? totals.totalPaid / totals.totalDue : 0;
  const overdueCount = apartments.filter(a => aptStatus(a.id).status === 'unpaid' || aptStatus(a.id).status === 'overdue').length;

  // Aggregate alerts from all modules
  const alerts = React.useMemo(() => {
    const list = [];
    // Active emergency
    if (state.activeEmergency) {
      const em = state.emergencies.find(e => e.id === state.activeEmergency);
      if (em) list.push({
        id: 'em-' + em.id, severity: 'critical', screen: 'emergencies',
        icon: '🚨', title: 'AVARIE ACTIVĂ — necesită autorizare',
        sub: em.title || em.category, action: 'Vezi detalii',
      });
    }
    // Compliance expired/urgent
    (window.COMPLIANCE_ITEMS || []).forEach(c => {
      const s = window.complianceStatus(c);
      if (s.state === 'expired') list.push({
        id: 'cmp-' + c.id, severity: 'critical', screen: 'compliance',
        icon: c.icon, title: `${c.title} — EXPIRAT`,
        sub: `${c.category} · risc amendă ${c.penalty_if_missed?.split('·')[0] || ''}`,
        action: 'Programează URGENT',
      });
      if (s.state === 'urgent') list.push({
        id: 'cmp-' + c.id, severity: 'high', screen: 'compliance',
        icon: c.icon, title: `${c.title}`,
        sub: `${c.category} · ${s.label}`,
        action: 'Programează',
      });
    });
    // Vault pending signatures
    const pendingTx = state.vaultTx.filter(t => t.status === 'pending_signatures');
    if (pendingTx.length > 0) list.push({
      id: 'vault-pending', severity: 'high', screen: 'vault',
      icon: '🔐', title: `${pendingTx.length} plăți așteaptă semnături`,
      sub: `Fond reparații · ${window.fmtRONshort(pendingTx.reduce((s, t) => s + t.amount, 0))} RON în total`,
      action: 'Vezi Vault',
    });
    // e-Factura pending
    const pendingFact = (window.EFACTURA_INBOX || []).filter(f => f.status === 'pending');
    const flagged = pendingFact.filter(f => f.anomaly || f.status === 'duplicate');
    if (flagged.length > 0) list.push({
      id: 'ef-flagged', severity: 'high', screen: 'efactura',
      icon: '⚠️', title: `${flagged.length} facturi suspecte`,
      sub: 'Sume neobișnuite sau duplicate — verifică',
      action: 'Vezi facturi',
    });
    if (pendingFact.length > 0 && flagged.length === 0) list.push({
      id: 'ef-pending', severity: 'normal', screen: 'efactura',
      icon: '📥', title: `${pendingFact.length} facturi de importat`,
      sub: 'Sosite automat din ANAF SPV',
      action: 'Importă',
    });
    // Arrears chronic
    const chronicDebtors = Object.entries(window.ARREARS_LEDGER || {}).filter(([_, l]) => {
      return Math.max(...l.map(x => x.days_late)) > 90;
    });
    if (chronicDebtors.length > 0) list.push({
      id: 'arrears-chronic', severity: 'high', screen: 'arrears',
      icon: '⚖️', title: `${chronicDebtors.length} apartament${chronicDebtors.length > 1 ? 'e' : ''} eligibil${chronicDebtors.length > 1 ? 'e' : ''} pentru instanță`,
      sub: 'Restanțe peste 90 zile · acțiune legală posibilă',
      action: 'Vezi restanțe',
    });
    // New issues
    const newIssues = state.issues.filter(i => i.status === 'nou');
    const urgentIssues = newIssues.filter(i => i.priority === 'urgent');
    if (urgentIssues.length > 0) list.push({
      id: 'iss-urgent', severity: 'critical', screen: 'issues',
      icon: '🔴', title: `${urgentIssues.length} sesizare urgentă de la locatari`,
      sub: urgentIssues[0].title,
      action: 'Vezi',
    });
    else if (newIssues.length > 0) list.push({
      id: 'iss-new', severity: 'normal', screen: 'issues',
      icon: '🔔', title: `${newIssues.length} sesizări noi de la locatari`,
      sub: 'Necesită răspuns',
      action: 'Vezi',
    });
    // AGA expiring votes
    const expiringAGA = state.proposals.filter(p => {
      if (p.status !== 'active') return false;
      const days = Math.ceil((new Date(p.deadline) - new Date('2025-11-15')) / 86400000);
      return days <= 7 && days > 0;
    });
    if (expiringAGA.length > 0) list.push({
      id: 'aga-expire', severity: 'high', screen: 'aga',
      icon: '🗳', title: `${expiringAGA.length} vot AGA expiră săptămâna asta`,
      sub: expiringAGA[0].title,
      action: 'Vezi votare',
    });

    // Sort by severity
    const order = { critical: 0, high: 1, normal: 2 };
    return list.sort((a, b) => order[a.severity] - order[b.severity]);
  }, [state]);

  const criticalCount = alerts.filter(a => a.severity === 'critical').length;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title={lang === 'ro' ? 'Acasă' : 'Home'}
        subtitle={`${window.BUILDING.name} · ${lang === 'ro' ? 'Noiembrie 2025' : 'November 2025'}`}
        right={<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <Button variant="secondary" size="sm" icon="bell">3</Button>
          <Button variant="primary" size="sm" icon="plus" onClick={() => setScreen('expenses')}>{tr('btn.add_expense')}</Button>
        </div>}
      />

      {/* Consolidated alerts feed */}
      {alerts.length > 0 && (
        <Card padded={false}>
          <div style={{ padding: '16px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, margin: 0, color: 'var(--ink)' }}>
                {lang === 'ro' ? 'Atenția ta este necesară' : 'Needs your attention'}
              </h3>
              <span style={{ padding: '2px 9px', borderRadius: 999, background: 'var(--surface-2)', color: 'var(--ink-2)', fontSize: 11, fontWeight: 700 }}>{alerts.length}</span>
              {criticalCount > 0 && (
                <span style={{ padding: '2px 9px', borderRadius: 999, background: 'var(--danger)', color: '#fff', fontSize: 11, fontWeight: 700 }}>{criticalCount} CRITICE</span>
              )}
            </div>
            <span style={{ fontSize: 12, color: 'var(--muted)' }}>{lang === 'ro' ? 'Sortat după urgență' : 'Sorted by urgency'}</span>
          </div>
          {alerts.slice(0, 8).map(a => <AlertRow key={a.id} alert={a} onAction={() => setScreen(a.screen)} />)}
        </Card>
      )}

      {/* Summary Cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 'var(--gap)' }}>
        <SummaryCard
          icon="receipt" iconBg="#F8E0D5" iconColor="#A8482F"
          label={tr('card.total_expenses')}
          value={<><Ticker value={totals.totalExpense} decimals={2} /> <span style={{ fontSize: 16, color: 'var(--muted)' }}>RON</span></>}
          sub={`${state.expenses.length} ${lang === 'ro' ? 'cheltuieli' : 'expenses'}`}
        />
        <SummaryCard
          icon="check" iconBg="#DDF0E4" iconColor="#1f6b3e"
          label={tr('card.collected')}
          value={<><Ticker value={totals.totalPaid} decimals={2} /> <span style={{ fontSize: 16, color: 'var(--muted)' }}>RON</span></>}
          sub={
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 4 }}>
              <div style={{ flex: 1, height: 6, background: 'var(--neutral-bg)', borderRadius: 999, overflow: 'hidden' }}>
                <div style={{ width: `${Math.min(100, collectRatio * 100)}%`, height: '100%', background: 'var(--success)', transition: 'width 800ms ease' }} />
              </div>
              <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink-2)', fontFamily: 'var(--font-mono)' }}>{Math.round(collectRatio * 100)}%</span>
            </div>
          }
        />
        <SummaryCard
          icon="spark" iconBg="#DDF0E4" iconColor="#065F46"
          label="Fond reparații"
          value={<><Ticker value={state.vault.balance} decimals={0} /> <span style={{ fontSize: 16, color: 'var(--muted)' }}>RON</span></>}
          sub={`${state.vaultTx.filter(t => t.status === 'pending_signatures').length} plăți așteaptă semnături`}
        />
        <SummaryCard
          icon="sparkles" iconBg="#1F4738" iconColor="#fff"
          label="BlocApp Score"
          value={<><span style={{ fontFamily: 'var(--font-display)', fontWeight: 700, color: 'var(--ink)' }}>B+</span> <span style={{ fontSize: 16, color: 'var(--muted)' }}>· 4.2/5</span></>}
          sub="Public · vezi raport"
        />
      </div>

      {/* Chart + activity */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 'var(--gap)' }}>
        <Card>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 18, gap: 12 }}>
            <div style={{ minWidth: 0, flex: 1 }}>
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, margin: 0, color: 'var(--ink)' }}>
                {lang === 'ro' ? 'Cheltuieli vs. încasări' : 'Expenses vs. collected'}
              </h3>
              <p style={{ fontSize: 12.5, color: 'var(--muted)', margin: '4px 0 0' }}>
                {lang === 'ro' ? 'Ultimele 6 luni · total scară, RON' : 'Last 6 months · building total, RON'}
              </p>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 12, color: 'var(--ink-2)', flexShrink: 0 }}>
              <Legend color="var(--primary)" label={lang === 'ro' ? 'Cheltuieli' : 'Expenses'} />
              <Legend color="var(--accent)" label={lang === 'ro' ? 'Încasări' : 'Collected'} />
            </div>
          </div>
          <BarChart data={window.MONTHLY_HISTORY} current={{ month: lang === 'ro' ? 'Noiembrie' : 'Nov', total_expenses: totals.totalExpense, total_collected: totals.totalPaid }} />
        </Card>

        <Card>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, margin: 0, color: 'var(--ink)' }}>
            {lang === 'ro' ? 'Activitate recentă' : 'Recent activity'}
          </h3>
          <p style={{ fontSize: 12.5, color: 'var(--muted)', margin: '4px 0 16px' }}>
            {lang === 'ro' ? 'Ultimele plăți' : 'Latest payments'}
          </p>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {window.RECENT_ACTIVITY.slice(0, 6).map(r => {
              const apt = state.apartments.find(a => a.id === r.apt);
              return (
                <div key={r.id} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: '1px solid var(--border)' }}>
                  <div style={{
                    width: 32, height: 32, borderRadius: 999,
                    background: 'var(--primary-light)', color: 'var(--primary)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontWeight: 600, fontSize: 12, fontFamily: 'var(--font-mono)',
                  }}>{apt?.number}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {apt?.owner_name}
                    </div>
                    <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{r.ts} · {r.action}</div>
                  </div>
                  <div style={{ fontFamily: 'var(--font-mono)', fontSize: 13.5, fontWeight: 600, color: 'var(--success)' }}>
                    +{window.fmtRONshort(r.amount)}
                  </div>
                </div>
              );
            })}
          </div>
        </Card>
      </div>
    </div>
  );
}

function AlertRow({ alert, onAction }) {
  const sev = {
    critical: { bg: '#FEE2E2', fg: '#991B1B', dot: '#DC2626' },
    high:     { bg: '#FEF3C7', fg: '#92400E', dot: '#D97706' },
    normal:   { bg: 'var(--surface-2)', fg: 'var(--ink-2)', dot: 'var(--muted)' },
  }[alert.severity];
  return (
    <button onClick={onAction} style={{
      width: '100%', padding: '14px 24px',
      background: 'transparent', border: 0, borderBottom: '1px solid var(--border)', cursor: 'pointer',
      fontFamily: 'inherit', textAlign: 'left',
      display: 'flex', alignItems: 'center', gap: 14,
      transition: 'background 160ms ease',
    }}
    onMouseEnter={(e) => e.currentTarget.style.background = sev.bg}
    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
    >
      <div style={{
        width: 38, height: 38, borderRadius: 10, flexShrink: 0,
        background: sev.bg, color: sev.fg,
        display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 18,
      }}>{alert.icon}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 2 }}>
          <span style={{ width: 6, height: 6, borderRadius: 999, background: sev.dot, flexShrink: 0 }} />
          <span style={{ fontSize: 13.5, fontWeight: 600, color: 'var(--ink)' }}>{alert.title}</span>
        </div>
        <div style={{ fontSize: 12, color: 'var(--muted)', lineHeight: 1.4 }}>{alert.sub}</div>
      </div>
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 12px', borderRadius: 8, background: sev.fg, color: '#fff', fontSize: 12, fontWeight: 600, flexShrink: 0 }}>
        {alert.action}
        <Icon name="arrowRight" size={13} stroke={2.4} />
      </div>
    </button>
  );
}

// ─────────────────────────────────────────────────────────────
// Summary card
// ─────────────────────────────────────────────────────────────
function SummaryCard({ icon, iconBg, iconColor, label, value, sub }) {
  return (
    <Card>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12,
          background: iconBg, color: iconColor,
          display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
        }}>
          <Icon name={icon} size={20} stroke={2} />
        </div>
        <div style={{ minWidth: 0, flex: 1 }}>
          <div style={{ fontSize: 12.5, fontWeight: 500, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
          <div style={{ fontFamily: 'var(--font-display)', fontSize: 26, fontWeight: 600, color: 'var(--ink)', marginTop: 4, fontVariantNumeric: 'tabular-nums', letterSpacing: '-0.02em' }}>{value}</div>
          <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 6 }}>{sub}</div>
        </div>
      </div>
    </Card>
  );
}

function PageHeader({ title, subtitle, right }) {
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 16 }}>
      <div>
        <h1 style={{ fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 600, margin: 0, color: 'var(--ink)', letterSpacing: '-0.02em' }}>{title}</h1>
        <p style={{ fontSize: 14, color: 'var(--muted)', margin: '6px 0 0' }}>{subtitle}</p>
      </div>
      {right}
    </div>
  );
}

function Legend({ color, label }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
      <div style={{ width: 10, height: 10, borderRadius: 3, background: color }} />
      {label}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Bar chart (SVG, no library) — 6 months history + current
// ─────────────────────────────────────────────────────────────
function BarChart({ data, current }) {
  const all = [...data, current];
  const max = Math.max(...all.map(d => Math.max(d.total_expenses, d.total_collected))) * 1.15;
  const W = 600, H = 220, padX = 28, padY = 30;
  const innerW = W - padX * 2;
  const innerH = H - padY * 2;
  const groupW = innerW / all.length;
  const barW = 14;

  const yScale = (v) => padY + innerH - (v / max) * innerH;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 240, fontFamily: 'var(--font-mono)' }}>
      {/* Y grid */}
      {[0, 0.25, 0.5, 0.75, 1].map(p => {
        const y = padY + innerH - p * innerH;
        return (
          <g key={p}>
            <line x1={padX} y1={y} x2={W - padX} y2={y} stroke="var(--border)" strokeDasharray={p === 0 ? '' : '2 4'} />
            <text x={padX - 6} y={y + 3} fontSize="9" fill="var(--muted)" textAnchor="end">
              {Math.round((max * p) / 1000)}k
            </text>
          </g>
        );
      })}
      {all.map((d, i) => {
        const cx = padX + groupW * i + groupW / 2;
        const isCurrent = i === all.length - 1;
        const yE = yScale(d.total_expenses);
        const yC = yScale(d.total_collected);
        return (
          <g key={i}>
            <rect x={cx - barW - 2} y={yE} width={barW}
                  height={Math.max(0, padY + innerH - yE)}
                  fill="var(--primary)" rx="3"
                  opacity={isCurrent ? 1 : 0.85} />
            <rect x={cx + 2} y={yC} width={barW}
                  height={Math.max(0, padY + innerH - yC)}
                  fill="var(--accent)" rx="3"
                  opacity={isCurrent ? 1 : 0.85} />
            <text x={cx} y={H - 8} fontSize="10" fill={isCurrent ? 'var(--ink)' : 'var(--muted)'} textAnchor="middle" fontWeight={isCurrent ? 700 : 500} fontFamily="inherit">
              {d.month.slice(0, 3)}
            </text>
            {isCurrent && (
              <text x={cx} y={yScale(d.total_expenses) - 6} fontSize="9.5" fill="var(--ink)" textAnchor="middle" fontWeight="700">
                {Math.round(d.total_expenses)}
              </text>
            )}
          </g>
        );
      })}
    </svg>
  );
}

// ─────────────────────────────────────────────────────────────
// Status table (compact, reused in Dashboard + MonthlyList)
// ─────────────────────────────────────────────────────────────
function StatusTable({ state, tr, lang, limit, onRowClick }) {
  const { apartments, aptStatus } = state;
  const rows = limit ? apartments.slice(0, limit) : apartments;
  return (
    <div style={{ overflowX: 'auto' }}>
      <table style={{ width: '100%', borderCollapse: 'separate', borderSpacing: 0, fontSize: 13.5 }}>
        <thead>
          <tr style={{ textAlign: 'left', color: 'var(--muted)', fontSize: 11.5, textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>
            <th style={{ padding: '10px 12px 10px 0', width: 56 }}>Ap.</th>
            <th style={{ padding: '10px 12px' }}>{lang === 'ro' ? 'Proprietar' : 'Owner'}</th>
            <th style={{ padding: '10px 12px', textAlign: 'right' }}>{lang === 'ro' ? 'De plătit' : 'Due'}</th>
            <th style={{ padding: '10px 12px', textAlign: 'right' }}>{lang === 'ro' ? 'Plătit' : 'Paid'}</th>
            <th style={{ padding: '10px 12px' }}>Status</th>
            <th style={{ padding: '10px 0 10px 12px', textAlign: 'right', width: 130 }}></th>
          </tr>
        </thead>
        <tbody>
          {rows.map(a => {
            const s = aptStatus(a.id);
            return (
              <tr key={a.id} style={{ borderTop: '1px solid var(--border)' }}>
                <td style={{ padding: '14px 12px 14px 0' }}>
                  <span style={{
                    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
                    width: 32, height: 32, borderRadius: 8,
                    background: 'var(--primary-light)', color: 'var(--primary)',
                    fontFamily: 'var(--font-mono)', fontWeight: 600, fontSize: 12,
                  }}>{a.number}</span>
                </td>
                <td style={{ padding: '14px 12px' }}>
                  <div style={{ fontWeight: 600, color: 'var(--ink)' }}>{a.owner_name}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{window.floorLabel(a.floor)} · {a.persons_count} {lang === 'ro' ? 'pers.' : 'pers.'}</div>
                </td>
                <td style={{ padding: '14px 12px', textAlign: 'right', fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--ink)' }}>
                  {window.fmtRON(s.due)}
                </td>
                <td style={{ padding: '14px 12px', textAlign: 'right', fontFamily: 'var(--font-mono)', color: s.paid > 0 ? 'var(--success)' : 'var(--muted)', fontWeight: 600 }}>
                  {s.paid > 0 ? window.fmtRON(s.paid) : '—'}
                </td>
                <td style={{ padding: '14px 12px' }}>
                  <StatusBadge status={s.status} t={tr} />
                </td>
                <td style={{ padding: '14px 0 14px 12px', textAlign: 'right' }}>
                  {s.status !== 'paid' && (
                    <Button size="sm" variant="ghost" onClick={() => state.openPayModal && state.openPayModal(a)}>
                      {lang === 'ro' ? 'Plată' : 'Pay'} <Icon name="arrowRight" size={13} />
                    </Button>
                  )}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

window.AdminApp = AdminApp;
window.PageHeader = PageHeader;
window.SummaryCard = SummaryCard;
window.BarChart = BarChart;
window.StatusTable = StatusTable;
