// admin-apt-list.jsx — Apartments, MonthlyList, Reports, Payment modal

// ═════════════════════════════════════════════════════════════
// 3. Apartments Screen — grid or table, drawer detail
// ═════════════════════════════════════════════════════════════
function ApartmentsScreen({ state, tr, viewMode, lang }) {
  const [selected, setSelected] = React.useState(null);
  const [search, setSearch] = React.useState('');
  const [payApt, setPayApt] = React.useState(null);

  const filtered = state.apartments.filter(a =>
    !search ||
    a.owner_name.toLowerCase().includes(search.toLowerCase()) ||
    a.number.includes(search)
  );

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title={lang === 'ro' ? 'Apartamente' : 'Apartments'}
        subtitle={lang === 'ro'
          ? `${state.apartments.length} apartamente · ${state.apartments.reduce((s, a) => s + a.persons_count, 0)} persoane · ${state.apartments.reduce((s, a) => s + (a.surface_mp || 0), 0)} m²`
          : `${state.apartments.length} apartments · ${state.apartments.reduce((s, a) => s + a.persons_count, 0)} persons · ${state.apartments.reduce((s, a) => s + (a.surface_mp || 0), 0)} m²`}
        right={<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <SearchInput value={search} onChange={setSearch} placeholder={lang === 'ro' ? 'Caută proprietar...' : 'Search owner...'} />
          <Button variant="secondary" icon="download">Import Excel</Button>
          <Button variant="primary" icon="plus">{lang === 'ro' ? 'Apartament nou' : 'New apartment'}</Button>
        </div>}
      />

      {viewMode === 'card' ? (
        <ApartmentGrid apartments={filtered} state={state} onSelect={setSelected} onPay={setPayApt} tr={tr} lang={lang} />
      ) : (
        <Card padded={false}>
          <StatusTable state={{ ...state, apartments: filtered, openPayModal: setPayApt }} tr={tr} lang={lang} />
        </Card>
      )}

      <Drawer open={!!selected} onClose={() => setSelected(null)} title={selected ? `Ap. ${selected.number} · ${selected.owner_name}` : ''} width={520}>
        {selected && <ApartmentDetail apt={selected} state={state} tr={tr} lang={lang} onPay={() => { setPayApt(selected); setSelected(null); }} />}
      </Drawer>

      <PaymentModal apt={payApt} state={state} onClose={() => setPayApt(null)} lang={lang} />
    </div>
  );
}

function SearchInput({ value, onChange, placeholder }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 8,
      padding: '8px 12px', borderRadius: 10,
      border: '1px solid var(--border)', background: 'var(--surface)',
      width: 240,
    }}>
      <Icon name="search" size={15} style={{ color: 'var(--muted)' }} />
      <input value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} style={{
        flex: 1, border: 0, outline: 'none', background: 'transparent',
        fontFamily: 'inherit', fontSize: 13.5, color: 'var(--ink)',
      }} />
    </div>
  );
}

function ApartmentGrid({ apartments, state, onSelect, onPay, tr, lang }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 'var(--gap)' }}>
      {apartments.map(a => {
        const s = state.aptStatus(a.id);
        return (
          <Card key={a.id} onClick={() => onSelect(a)} style={{
            transition: 'transform 200ms ease, box-shadow 200ms ease',
            cursor: 'pointer',
          }}>
            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 16 }}>
              <div style={{
                width: 48, height: 48, borderRadius: 12,
                background: 'var(--primary-light)', color: 'var(--primary)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 20,
              }}>{a.number}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 14.5, color: 'var(--ink)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                  {a.owner_name}
                </div>
                <div style={{ fontSize: 12, color: 'var(--muted)' }}>
                  {window.floorLabel(a.floor)} · {a.rooms} {lang === 'ro' ? 'cam.' : 'rm'} · {a.surface_mp} m²
                </div>
              </div>
              <StatusBadge status={s.status} t={tr} size="sm" />
            </div>

            <div style={{ display: 'flex', gap: 10, marginBottom: 14, fontSize: 12, color: 'var(--ink-2)' }}>
              <InfoTag icon="users" text={`${a.persons_count}`} />
              <InfoTag icon="phone" text={a.owner_phone.slice(0, 12)} />
            </div>

            <div style={{
              padding: '12px 14px', borderRadius: 10,
              background: 'var(--surface-2)',
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            }}>
              <div>
                <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>
                  {lang === 'ro' ? 'Luna curentă' : 'Current month'}
                </div>
                <div style={{ fontFamily: 'var(--font-mono)', fontSize: 16, fontWeight: 700, color: 'var(--ink)' }}>
                  {window.fmtRON(s.due)}
                </div>
              </div>
              {s.status === 'paid' ? (
                <div style={{ color: 'var(--success)', fontSize: 24 }}>✓</div>
              ) : (
                <Button size="sm" variant="primary" onClick={(e) => { e.stopPropagation(); onPay(a); }}>
                  {lang === 'ro' ? 'Plată' : 'Pay'}
                </Button>
              )}
            </div>
          </Card>
        );
      })}
    </div>
  );
}

function InfoTag({ icon, text }) {
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontFamily: 'var(--font-mono)' }}>
      <Icon name={icon} size={13} style={{ color: 'var(--muted)' }} />
      {text}
    </div>
  );
}

// Apartment detail drawer
function ApartmentDetail({ apt, state, tr, lang, onPay }) {
  const s = state.aptStatus(apt.id);
  const r = state.readings[apt.id];
  const charges = state.charges[apt.id];
  const last6 = window.TENANT_HISTORY.slice(0, 6); // demo

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      {/* Owner card */}
      <Card style={{ background: 'var(--surface-2)', boxShadow: 'none' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{
            width: 56, height: 56, borderRadius: 999,
            background: 'var(--accent)', color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontWeight: 700, fontSize: 20, fontFamily: 'var(--font-display)',
          }}>{apt.owner_name.split(' ').map(p => p[0]).join('').slice(0, 2)}</div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 600, color: 'var(--ink)' }}>{apt.owner_name}</div>
            <div style={{ fontSize: 12.5, color: 'var(--muted)', display: 'flex', gap: 10, marginTop: 4 }}>
              <span><Icon name="phone" size={12} /> {apt.owner_phone}</span>
            </div>
          </div>
          <Button size="sm" variant="ghost" icon="edit">{lang === 'ro' ? 'Editează' : 'Edit'}</Button>
        </div>
      </Card>

      {/* Apartment facts */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
        <Fact label={lang === 'ro' ? 'Etaj' : 'Floor'} value={apt.floor === 0 ? 'P' : apt.floor} />
        <Fact label={lang === 'ro' ? 'Camere' : 'Rooms'} value={apt.rooms} />
        <Fact label={lang === 'ro' ? 'Suprafață' : 'Surface'} value={`${apt.surface_mp} m²`} />
        <Fact label={lang === 'ro' ? 'Persoane' : 'Persons'} value={apt.persons_count} />
      </div>

      {/* Current month */}
      <div>
        <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, margin: '0 0 12px', color: 'var(--ink)' }}>
          {lang === 'ro' ? 'Noiembrie 2025' : 'November 2025'}
        </h4>
        <div style={{
          padding: 18, borderRadius: 14,
          background: 'var(--primary-light)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
            <div>
              <div style={{ fontSize: 12, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>
                {lang === 'ro' ? 'De plătit' : 'Due'}
              </div>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 30, fontWeight: 600, color: 'var(--ink)', letterSpacing: '-0.02em' }}>
                {window.fmtRON(s.due)}
              </div>
            </div>
            <StatusBadge status={s.status} t={tr} />
          </div>
          {s.status !== 'paid' && (
            <Button variant="primary" full icon="check" onClick={onPay}>
              {tr('btn.register_pay')}
            </Button>
          )}
        </div>

        {/* Breakdown */}
        {charges && (
          <div style={{ marginTop: 16, display: 'flex', flexDirection: 'column', gap: 8 }}>
            {Object.entries(charges.breakdown).filter(([_, v]) => (v.amount || 0) > 0.01).map(([catId, entry]) => {
              const cat = entry.category || window.CATEGORIES.find(c => c.id === catId);
              if (!cat) return null;
              return (
                <div key={catId} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13 }}>
                  <span style={{ fontSize: 14 }}>{cat.icon}</span>
                  <span style={{ flex: 1, color: 'var(--ink-2)' }}>{cat.name}</span>
                  <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--ink)', fontWeight: 600 }}>{window.fmtRON(entry.amount)}</span>
                </div>
              );
            })}
            {/* Excluded */}
            {charges.excluded && Object.keys(charges.excluded).length > 0 && (
              <div style={{ marginTop: 8, paddingTop: 12, borderTop: '1px dashed var(--border)' }}>
                {Object.entries(charges.excluded).map(([catId, reason]) => {
                  const cat = window.CATEGORIES.find(c => c.id === catId);
                  if (!cat) return null;
                  return (
                    <div key={catId} style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 12, opacity: 0.65, padding: '3px 0' }}>
                      <span style={{ fontSize: 12 }}>{cat.icon}</span>
                      <span style={{ flex: 1, color: 'var(--muted)', textDecoration: 'line-through' }}>{cat.name}</span>
                      <span style={{ fontSize: 11, color: 'var(--muted)', fontStyle: 'italic' }}>{reason}</span>
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        )}
      </div>

      {/* Meter readings */}
      {r && (
        <div>
          <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, margin: '0 0 12px', color: 'var(--ink)' }}>
            {lang === 'ro' ? 'Indexuri apometre' : 'Meter readings'}
          </h4>
          <Card padded={false} style={{ background: 'var(--surface-2)' }}>
            <MeterRow icon="💧" label={lang === 'ro' ? 'Apă rece' : 'Cold water'} prev={r.cold_prev} curr={r.cold_curr} />
            <MeterRow icon="🚿" label={lang === 'ro' ? 'Apă caldă' : 'Hot water'} prev={r.hot_prev} curr={r.hot_curr} last />
          </Card>
        </div>
      )}

      {/* History */}
      <div>
        <h4 style={{ fontFamily: 'var(--font-display)', fontSize: 15, fontWeight: 600, margin: '0 0 12px', color: 'var(--ink)' }}>
          {lang === 'ro' ? 'Istoric plăți' : 'Payment history'}
        </h4>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {last6.map((h, i) => (
            <div key={h.id} style={{
              padding: '12px 0', borderTop: i > 0 ? '1px solid var(--border)' : 'none',
              display: 'flex', alignItems: 'center', gap: 12, fontSize: 13.5,
            }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 500, color: 'var(--ink)' }}>{h.month}</div>
                <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{h.method} · {h.paid_at}</div>
              </div>
              <div style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--ink)' }}>
                {window.fmtRON(h.amount)}
              </div>
              <StatusBadge status={h.status} t={tr} size="sm" />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function Fact({ label, value }) {
  return (
    <div style={{ padding: '12px', borderRadius: 10, background: 'var(--surface-2)', textAlign: 'center' }}>
      <div style={{ fontSize: 10.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>{label}</div>
      <div style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600, color: 'var(--ink)', marginTop: 2 }}>{value}</div>
    </div>
  );
}

function MeterRow({ icon, label, prev, curr, last }) {
  const consumption = curr - prev;
  return (
    <div style={{
      padding: '14px 18px',
      borderBottom: last ? 'none' : '1px solid var(--border)',
      display: 'flex', alignItems: 'center', gap: 14,
    }}>
      <div style={{ fontSize: 18 }}>{icon}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontSize: 13, fontWeight: 500, color: 'var(--ink)' }}>{label}</div>
        <div style={{ fontSize: 11, color: 'var(--muted)', fontFamily: 'var(--font-mono)' }}>
          {prev.toFixed(3)} → {curr.toFixed(3)}
        </div>
      </div>
      <div style={{ textAlign: 'right' }}>
        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 15, fontWeight: 700, color: 'var(--primary)' }}>+{consumption.toFixed(3)}</div>
        <div style={{ fontSize: 10.5, color: 'var(--muted)' }}>m³</div>
      </div>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// 4. Monthly List Screen — full payment list, register, print preview
// ═════════════════════════════════════════════════════════════
function MonthlyListScreen({ state, tr, lang }) {
  const [payApt, setPayApt] = React.useState(null);
  const [showNotif, setShowNotif] = React.useState(false);
  const toast = useToast();

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title={lang === 'ro' ? 'Lista de plată' : 'Payment list'}
        subtitle={lang === 'ro' ? 'Noiembrie 2025 · scadență 25 noiembrie' : 'November 2025 · due Nov 25'}
        right={<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <Button variant="secondary" icon="print">{lang === 'ro' ? 'Print' : 'Print'}</Button>
          <Button variant="secondary" icon="download">{tr('btn.export')}</Button>
          <Button variant="primary" icon="mail" onClick={() => setShowNotif(true)}>{tr('btn.send_notif')}</Button>
        </div>}
      />

      {/* Document-style preview */}
      <Card padded={false} style={{
        boxShadow: '0 1px 2px rgba(28, 22, 12, 0.04), 0 12px 32px rgba(28, 22, 12, 0.08)',
      }}>
        {/* Letterhead */}
        <div style={{ padding: '32px 36px', borderBottom: '2px solid var(--ink)' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontSize: 11.5, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.1em', fontWeight: 600 }}>
                {lang === 'ro' ? 'Asociația de Proprietari' : 'Owners Association'}
              </div>
              <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 28, fontWeight: 600, margin: '6px 0', color: 'var(--ink)', letterSpacing: '-0.02em' }}>
                {window.BUILDING.name}
              </h2>
              <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>
                {window.BUILDING.address}, {window.BUILDING.city}
              </div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 21, fontWeight: 600, color: 'var(--primary)', letterSpacing: '-0.01em' }}>
                {lang === 'ro' ? 'Lista de plată' : 'Payment list'}
              </div>
              <div style={{ fontSize: 14, color: 'var(--ink-2)', marginTop: 2 }}>
                {lang === 'ro' ? 'Noiembrie 2025' : 'November 2025'}
              </div>
              <div style={{ fontSize: 12.5, color: 'var(--danger)', marginTop: 6, fontWeight: 600 }}>
                {lang === 'ro' ? 'Scadență: 25 noiembrie 2025' : 'Due: November 25, 2025'}
              </div>
            </div>
          </div>
        </div>

        {/* Summary stats */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', borderBottom: '1px solid var(--border)' }}>
          {[
            { label: lang === 'ro' ? 'Total datorat' : 'Total due',    value: window.fmtRON(state.totals.totalDue),    color: 'var(--ink)' },
            { label: lang === 'ro' ? 'Total încasat' : 'Total paid',    value: window.fmtRON(state.totals.totalPaid),  color: 'var(--success)' },
            { label: lang === 'ro' ? 'De recuperat' : 'Outstanding',    value: window.fmtRON(state.totals.totalDue - state.totals.totalPaid), color: 'var(--warning-fg)' },
            { label: lang === 'ro' ? 'Apartamente' : 'Apartments',      value: String(state.apartments.length), color: 'var(--ink)' },
          ].map((s, i, arr) => (
            <div key={i} style={{ padding: '18px 24px', borderRight: i < arr.length - 1 ? '1px solid var(--border)' : 'none' }}>
              <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>{s.label}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 17, fontWeight: 700, color: s.color, marginTop: 4 }}>{s.value}</div>
            </div>
          ))}
        </div>

        {/* Full table */}
        <div style={{ padding: '0 8px' }}>
          <StatusTable state={{ ...state, openPayModal: setPayApt }} tr={tr} lang={lang} />
        </div>

        {/* Footer */}
        <div style={{
          padding: '20px 36px', background: 'var(--surface-2)',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          fontSize: 12, color: 'var(--muted)',
        }}>
          <div>
            {lang === 'ro' ? 'Administrator:' : 'Admin:'} <b style={{ color: 'var(--ink-2)' }}>{window.BUILDING.admin_name}</b> · <Icon name="phone" size={11} style={{ verticalAlign: '-1px' }} /> {window.BUILDING.admin_phone}
          </div>
          <div>
            {lang === 'ro' ? 'Generat:' : 'Generated:'} 15 nov 2025, 14:32
          </div>
        </div>
      </Card>

      <PaymentModal apt={payApt} state={state} onClose={() => setPayApt(null)} lang={lang} />

      <Modal open={showNotif} onClose={() => setShowNotif(false)} title={lang === 'ro' ? 'Trimite notificări' : 'Send notifications'}
        footer={<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <Button variant="secondary" onClick={() => setShowNotif(false)}>{lang === 'ro' ? 'Anulează' : 'Cancel'}</Button>
          <Button variant="primary" icon="mail" onClick={() => {
            state.setNotifSent(true);
            setShowNotif(false);
            toast(lang === 'ro' ? `${state.apartments.length} notificări trimise pe email` : `${state.apartments.length} notifications sent by email`);
          }}>{lang === 'ro' ? 'Trimite' : 'Send'} ({state.apartments.length})</Button>
        </div>}
      >
        <div style={{ fontSize: 14, color: 'var(--ink-2)', lineHeight: 1.6 }}>
          <p style={{ marginTop: 0 }}>
            {lang === 'ro'
              ? 'Vor primi un email personalizat fiecare proprietar, cu suma proprie de plată, scadența și un buton de plată online.'
              : 'Each owner will receive a personalized email with their amount due, deadline, and an online payment button.'}
          </p>
          <Card style={{ background: 'var(--surface-2)', boxShadow: 'none', marginTop: 16 }}>
            <div style={{ fontSize: 12, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600, marginBottom: 8 }}>
              {lang === 'ro' ? 'Previzualizare' : 'Preview'}
            </div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, lineHeight: 1.5, color: 'var(--ink-2)' }}>
              <b style={{ color: 'var(--ink)' }}>Subject:</b> [{window.BUILDING.name}] Nota de plată Noiembrie 2025<br/>
              <br/>
              Bună ziua, Ionescu Maria,<br/>
              <br/>
              Apartament 1 — De plătit: <b style={{ color: 'var(--primary)' }}>{window.fmtRON(state.charges['a1']?.total || 0)}</b><br/>
              Scadență: 25 noiembrie 2025<br/>
            </div>
          </Card>
        </div>
      </Modal>
    </div>
  );
}

// ═════════════════════════════════════════════════════════════
// Payment Modal — register payment for an apartment
// ═════════════════════════════════════════════════════════════
function PaymentModal({ apt, state, onClose, lang }) {
  const [amount, setAmount] = React.useState('');
  const [method, setMethod] = React.useState('cash');
  const [reference, setReference] = React.useState('');
  const toast = useToast();

  React.useEffect(() => {
    if (apt) {
      const s = state.aptStatus(apt.id);
      setAmount(s.balance > 0 ? s.balance.toFixed(2) : '');
      setMethod('cash');
      setReference('');
    }
  }, [apt]);

  if (!apt) return null;
  const s = state.aptStatus(apt.id);

  const submit = async () => {
    const amt = parseFloat(amount);
    if (!amt || amt <= 0) {
      toast(lang === 'ro' ? 'Introdu o sumă validă' : 'Enter a valid amount', 'error');
      return;
    }
    const today = new Date().toISOString().slice(0, 10);
    if (window.blocLive) {
      try {
        await window.blocLive.addPayment({
          apt: apt.id, amount_paid: amt, method, reference, date: today,
        });
        state.setPayments(ps => [...ps, {
          apt: apt.id, amount_paid: amt, method, reference, date: today,
        }]);
        toast(lang === 'ro' ? `Plată salvată: ${window.fmtRON(amt)}` : `Payment saved: ${window.fmtRON(amt)}`);
        onClose();
      } catch (err) {
        toast((lang === 'ro' ? 'Eroare salvare: ' : 'Save error: ') + err.message, 'error');
      }
    } else {
      state.setPayments(ps => [...ps, {
        apt: apt.id, amount_paid: amt, method, reference, date: today,
      }]);
      toast(lang === 'ro' ? `Plată înregistrată: ${window.fmtRON(amt)}` : `Payment registered: ${window.fmtRON(amt)}`);
      onClose();
    }
  };

  return (
    <Modal open={!!apt} onClose={onClose} title={lang === 'ro' ? 'Înregistrează plată' : 'Register payment'}
      footer={<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
        <div style={{ fontSize: 12.5, color: 'var(--muted)' }}>
          {lang === 'ro' ? 'Sold rămas:' : 'Balance:'} <b style={{ color: 'var(--ink)', fontFamily: 'var(--font-mono)' }}>{window.fmtRON(s.balance)}</b>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button variant="secondary" onClick={onClose}>{lang === 'ro' ? 'Anulează' : 'Cancel'}</Button>
          <Button variant="success" onClick={submit} icon="check">{lang === 'ro' ? 'Înregistrează' : 'Register'}</Button>
        </div>
      </div>}
    >
      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <Card style={{ background: 'var(--surface-2)', boxShadow: 'none' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{
              width: 44, height: 44, borderRadius: 10,
              background: 'var(--primary-light)', color: 'var(--primary)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 15,
            }}>{apt.number}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, color: 'var(--ink)' }}>{apt.owner_name}</div>
              <div style={{ fontSize: 12, color: 'var(--muted)' }}>{window.floorLabel(apt.floor)} · {apt.persons_count} {lang === 'ro' ? 'persoane' : 'persons'}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>{lang === 'ro' ? 'De plătit' : 'Due'}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 16, fontWeight: 700, color: 'var(--ink)' }}>{window.fmtRON(s.due)}</div>
            </div>
          </div>
        </Card>

        <Field label={lang === 'ro' ? 'Sumă achitată (RON)' : 'Amount paid (RON)'}>
          <Input type="number" value={amount} onChange={setAmount} placeholder="0.00" mono />
          <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
            <SuggestBtn label={lang === 'ro' ? 'Suma totală' : 'Full'} value={s.balance.toFixed(2)} onClick={setAmount} />
            <SuggestBtn label="½" value={(s.balance / 2).toFixed(2)} onClick={setAmount} />
            <SuggestBtn label="100 RON" value="100.00" onClick={setAmount} />
          </div>
        </Field>

        <Field label={lang === 'ro' ? 'Metodă' : 'Method'}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
            {[
              { id: 'cash', label: lang === 'ro' ? 'Numerar' : 'Cash' },
              { id: 'bank_transfer', label: 'Transfer' },
              { id: 'online', label: 'Online' },
              { id: 'other', label: lang === 'ro' ? 'Alt' : 'Other' },
            ].map(m => (
              <button key={m.id} onClick={() => setMethod(m.id)} style={{
                padding: '10px 8px', borderRadius: 10, cursor: 'pointer',
                background: method === m.id ? 'var(--primary)' : 'var(--surface-2)',
                color: method === m.id ? '#fff' : 'var(--ink)',
                border: '1.5px solid ' + (method === m.id ? 'var(--primary)' : 'transparent'),
                fontFamily: 'inherit', fontSize: 13, fontWeight: 600,
                transition: 'all 160ms ease',
              }}>{m.label}</button>
            ))}
          </div>
        </Field>

        <Field label={lang === 'ro' ? 'Nr. chitanță / referință (opțional)' : 'Receipt / reference (optional)'}>
          <Input value={reference} onChange={setReference} placeholder={method === 'cash' ? 'CH-...' : 'OP ...'} />
        </Field>
      </div>
    </Modal>
  );
}

function SuggestBtn({ label, value, onClick }) {
  return (
    <button onClick={() => onClick(value)} style={{
      padding: '5px 10px', borderRadius: 6, cursor: 'pointer',
      background: 'var(--surface-2)', border: '1px solid var(--border)',
      fontSize: 11.5, fontWeight: 500, color: 'var(--ink-2)',
      fontFamily: 'inherit',
    }}>{label}</button>
  );
}

// ═════════════════════════════════════════════════════════════
// 5. Reports Screen — annual, categories, overdue
// ═════════════════════════════════════════════════════════════
function ReportsScreen({ state, tr, lang }) {
  const [tab, setTab] = React.useState('annual');

  // Compute total per category for current month (and add prior months noise)
  const catTotals = React.useMemo(() => {
    const map = {};
    state.expenses.forEach(e => {
      const cat = window.CATEGORIES.find(c => c.id === e.category_id);
      if (!cat) return;
      map[cat.id] = { cat, value: (map[cat.id]?.value || 0) + parseFloat(e.amount) };
    });
    return Object.values(map).sort((a, b) => b.value - a.value);
  }, [state.expenses]);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 24, maxWidth: 1280 }}>
      <PageHeader
        title={lang === 'ro' ? 'Rapoarte' : 'Reports'}
        subtitle={lang === 'ro' ? 'Anul 2025 · sumarul anual și pe categorii' : 'Year 2025 · annual and category summary'}
        right={<Button variant="secondary" icon="download">{lang === 'ro' ? 'Export raport anual' : 'Export annual report'}</Button>}
      />

      <div style={{ display: 'flex', gap: 4, padding: 4, background: 'var(--surface-2)', borderRadius: 12, width: 'fit-content' }}>
        {[
          { id: 'annual',   label: lang === 'ro' ? 'Sumar anual' : 'Annual summary' },
          { id: 'category', label: lang === 'ro' ? 'Pe categorii' : 'By category' },
          { id: 'overdue',  label: lang === 'ro' ? 'Restanțieri' : 'In arrears' },
        ].map(tg => (
          <button key={tg.id} onClick={() => setTab(tg.id)} style={{
            padding: '8px 16px', borderRadius: 8, border: 0, cursor: 'pointer',
            background: tab === tg.id ? 'var(--surface)' : 'transparent',
            color: tab === tg.id ? 'var(--ink)' : 'var(--muted)',
            fontFamily: 'inherit', fontSize: 13.5, fontWeight: 600,
            boxShadow: tab === tg.id ? '0 1px 2px rgba(28,22,12,0.08)' : 'none',
            transition: 'all 160ms ease',
          }}>{tg.label}</button>
        ))}
      </div>

      {tab === 'annual' && <AnnualReport state={state} lang={lang} />}
      {tab === 'category' && <CategoryReport totals={catTotals} lang={lang} />}
      {tab === 'overdue' && <OverdueReport state={state} tr={tr} lang={lang} />}
    </div>
  );
}

function AnnualReport({ state, lang }) {
  // build 12 months — first 4 empty (2025 partial), then mai-oct from history, then nov current
  const months = [
    'Ian','Feb','Mar','Apr','Mai','Iun','Iul','Aug','Sep','Oct','Nov','Dec',
  ];
  const data = months.map((m, i) => {
    if (i < 4) return { month: m, expenses: 0, collected: 0, paid: 0 };
    if (i === 10) return { month: m, expenses: state.totals.totalExpense, collected: state.totals.totalPaid, paid: state.totals.totalPaid };
    if (i === 11) return { month: m, expenses: 0, collected: 0, paid: 0 };
    const h = window.MONTHLY_HISTORY[i - 4];
    return { month: m, expenses: h?.total_expenses || 0, collected: h?.total_collected || 0, paid: h?.total_collected || 0 };
  });

  const totalExp = data.reduce((s, d) => s + d.expenses, 0);
  const totalColl = data.reduce((s, d) => s + d.collected, 0);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--gap)' }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 'var(--gap)' }}>
        <SummaryCard icon="receipt" iconBg="#F8E0D5" iconColor="#A8482F" label={lang === 'ro' ? 'Total 2025' : 'Total 2025'} value={<>{window.fmtRONshort(totalExp)} <span style={{ fontSize: 16, color: 'var(--muted)' }}>RON</span></>} sub={lang === 'ro' ? '7 luni înregistrate' : '7 months recorded'} />
        <SummaryCard icon="check" iconBg="#DDF0E4" iconColor="#1f6b3e" label={lang === 'ro' ? 'Încasat 2025' : 'Collected 2025'} value={<>{window.fmtRONshort(totalColl)} <span style={{ fontSize: 16, color: 'var(--muted)' }}>RON</span></>} sub={`${Math.round((totalColl / totalExp) * 100)}% ${lang === 'ro' ? 'din total' : 'of total'}`} />
        <SummaryCard icon="users" iconBg="#E7E7FA" iconColor="#5B5DD3" label={lang === 'ro' ? 'Medie / lună' : 'Avg / month'} value={<>{window.fmtRONshort(totalExp / 7)} <span style={{ fontSize: 16, color: 'var(--muted)' }}>RON</span></>} sub={lang === 'ro' ? 'cost mediu' : 'avg cost'} />
        <SummaryCard icon="coffee" iconBg="#FAEBC8" iconColor="#8a5a13" label={lang === 'ro' ? 'Per apartament' : 'Per apartment'} value={<>{window.fmtRONshort(totalExp / state.apartments.length / 7)} <span style={{ fontSize: 16, color: 'var(--muted)' }}>RON</span></>} sub={lang === 'ro' ? 'medie lunară' : 'monthly avg'} />
      </div>

      <Card>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, margin: '0 0 18px', color: 'var(--ink)' }}>
          {lang === 'ro' ? 'Evoluție lunară 2025' : 'Monthly evolution 2025'}
        </h3>
        <AnnualChart data={data} />
        <div style={{ marginTop: 18, display: 'flex', gap: 18, fontSize: 12, color: 'var(--ink-2)' }}>
          <Legend color="var(--primary)" label={lang === 'ro' ? 'Cheltuieli' : 'Expenses'} />
          <Legend color="var(--accent)" label={lang === 'ro' ? 'Încasări' : 'Collected'} />
        </div>
      </Card>
    </div>
  );
}

function AnnualChart({ data }) {
  const max = Math.max(...data.map(d => Math.max(d.expenses, d.collected))) * 1.15 || 1000;
  const W = 800, H = 240, padX = 40, padY = 24;
  const innerW = W - padX * 2;
  const innerH = H - padY * 2;
  const groupW = innerW / data.length;
  const barW = 14;
  const yScale = (v) => padY + innerH - (v / max) * innerH;

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 260, fontFamily: 'var(--font-mono)' }}>
      {[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>
        );
      })}
      {data.map((d, i) => {
        const cx = padX + groupW * i + groupW / 2;
        return (
          <g key={i}>
            {d.expenses > 0 && <rect x={cx - barW - 2} y={yScale(d.expenses)} width={barW} height={padY + innerH - yScale(d.expenses)} fill="var(--primary)" rx="3" opacity="0.95" />}
            {d.collected > 0 && <rect x={cx + 2} y={yScale(d.collected)} width={barW} height={padY + innerH - yScale(d.collected)} fill="var(--accent)" rx="3" opacity="0.95" />}
            <text x={cx} y={H - 8} fontSize="10" fill="var(--muted)" textAnchor="middle" fontWeight="500" fontFamily="inherit">{d.month}</text>
          </g>
        );
      })}
    </svg>
  );
}

function CategoryReport({ totals, lang }) {
  const sum = totals.reduce((s, t) => s + t.value, 0);
  // Donut chart
  let cumAngle = -Math.PI / 2;
  const segs = totals.map(t => {
    const angle = (t.value / sum) * Math.PI * 2;
    const seg = { ...t, startA: cumAngle, endA: cumAngle + angle };
    cumAngle += angle;
    return seg;
  });

  const polar = (cx, cy, r, a) => ({ x: cx + r * Math.cos(a), y: cy + r * Math.sin(a) });

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '320px 1fr', gap: 'var(--gap)' }}>
      <Card>
        <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, margin: 0, color: 'var(--ink)' }}>
          {lang === 'ro' ? 'Distribuție cheltuieli' : 'Expense distribution'}
        </h3>
        <p style={{ fontSize: 12.5, color: 'var(--muted)', margin: '4px 0 16px' }}>
          {lang === 'ro' ? 'Noiembrie 2025' : 'November 2025'}
        </p>
        <svg viewBox="0 0 200 200" style={{ width: '100%', height: 240 }}>
          {segs.map((s, i) => {
            const cx = 100, cy = 100, rOut = 88, rIn = 54;
            const p1 = polar(cx, cy, rOut, s.startA);
            const p2 = polar(cx, cy, rOut, s.endA);
            const p3 = polar(cx, cy, rIn, s.endA);
            const p4 = polar(cx, cy, rIn, s.startA);
            const large = (s.endA - s.startA) > Math.PI ? 1 : 0;
            const d = `M ${p1.x} ${p1.y} A ${rOut} ${rOut} 0 ${large} 1 ${p2.x} ${p2.y} L ${p3.x} ${p3.y} A ${rIn} ${rIn} 0 ${large} 0 ${p4.x} ${p4.y} Z`;
            return <path key={i} d={d} fill={s.cat.color} opacity={0.92} stroke="var(--surface)" strokeWidth="2" />;
          })}
          <text x="100" y="96" textAnchor="middle" fontSize="11" fill="var(--muted)" fontFamily="var(--font-mono)">TOTAL</text>
          <text x="100" y="116" textAnchor="middle" fontSize="20" fill="var(--ink)" fontFamily="var(--font-display)" fontWeight="700">{window.fmtRONshort(sum)}</text>
        </svg>
      </Card>
      <Card padded={false}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border)' }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, margin: 0, color: 'var(--ink)' }}>
            {lang === 'ro' ? 'Detaliu pe categorii' : 'Category breakdown'}
          </h3>
        </div>
        {totals.map(t => {
          const pct = (t.value / sum) * 100;
          return (
            <div key={t.cat.id} style={{ padding: '14px 24px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 36, height: 36, borderRadius: 10, background: t.cat.color + '22', color: t.cat.color, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 17 }}>{t.cat.icon}</div>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 13.5 }}>{t.cat.name}</span>
                  <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 600, color: 'var(--ink)', fontSize: 13.5 }}>{window.fmtRON(t.value)}</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                  <div style={{ flex: 1, height: 5, background: 'var(--neutral-bg)', borderRadius: 999, overflow: 'hidden' }}>
                    <div style={{ width: `${pct}%`, height: '100%', background: t.cat.color, transition: 'width 800ms ease' }} />
                  </div>
                  <span style={{ fontSize: 11.5, fontFamily: 'var(--font-mono)', color: 'var(--muted)', width: 40, textAlign: 'right' }}>{pct.toFixed(1)}%</span>
                </div>
              </div>
            </div>
          );
        })}
      </Card>
    </div>
  );
}

function OverdueReport({ state, tr, lang }) {
  const overdue = state.apartments.map(a => {
    const s = state.aptStatus(a.id);
    return { ...a, ...s };
  }).filter(a => a.status === 'unpaid' || a.status === 'partial' || a.status === 'overdue')
    .sort((a, b) => b.balance - a.balance);

  return (
    <Card padded={false}>
      <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 17, fontWeight: 600, margin: 0, color: 'var(--ink)' }}>
            {lang === 'ro' ? 'Apartamente cu sold neachitat' : 'Apartments with outstanding balance'}
          </h3>
          <p style={{ fontSize: 12.5, color: 'var(--muted)', margin: '4px 0 0' }}>
            {overdue.length} {lang === 'ro' ? 'apartamente · total restanță' : 'apartments · total outstanding'} {window.fmtRON(overdue.reduce((s, a) => s + a.balance, 0))}
          </p>
        </div>
        <Button variant="secondary" size="sm" icon="mail">{lang === 'ro' ? 'Trimite somații' : 'Send reminders'}</Button>
      </div>
      <div>
        {overdue.map(a => (
          <div key={a.id} style={{
            padding: '16px 24px', display: 'flex', alignItems: 'center', gap: 14,
            borderBottom: '1px solid var(--border)',
          }}>
            <div style={{ width: 36, height: 36, borderRadius: 10, background: 'var(--danger-bg)', color: 'var(--danger-fg)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--font-mono)', fontWeight: 700 }}>{a.number}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 600, color: 'var(--ink)', fontSize: 14 }}>{a.owner_name}</div>
              <div style={{ fontSize: 12, color: 'var(--muted)' }}>{window.floorLabel(a.floor)} · {a.owner_phone}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.04em', fontWeight: 600 }}>{lang === 'ro' ? 'Sold' : 'Balance'}</div>
              <div style={{ fontFamily: 'var(--font-mono)', fontSize: 16, fontWeight: 700, color: 'var(--danger)' }}>{window.fmtRON(a.balance)}</div>
            </div>
            <StatusBadge status={a.status} t={tr} />
          </div>
        ))}
      </div>
    </Card>
  );
}

Object.assign(window, {
  ApartmentsScreen, MonthlyListScreen, ReportsScreen, PaymentModal,
});
