// Property detail page (with units list) + Unit detail page (with tabs)

function PropertyDetail({ data, route, setRoute }) {
  const { properties, tenants, transactions, documents, maintenance, store } = data;
  const prop = properties.find(p => p.id === route.propertyId);
  if (!prop) return <div className="page"><div className="empty">Objekt nicht gefunden.</div></div>;

  const [showEdit, setShowEdit] = React.useState(false);
  const [showAddUnit, setShowAddUnit] = React.useState(false);
  const [showDelete, setShowDelete] = React.useState(false);
  const [showImport, setShowImport] = React.useState(false);

  const monthlyRent = prop.units.reduce((s, u) => s + (u.rent || 0), 0);
  const occupied = prop.units.filter(u => u.status === 'vermietet').length;
  const totalSize = prop.units.reduce((s, u) => s + (u.size || 0), 0);

  // P&L for this property
  const propTxns = transactions.filter(t => t.propertyId === prop.id);
  const yr = String(new Date().getFullYear());
  const ytdIncome = propTxns.filter(t => t.date.startsWith(yr) && t.type === 'einnahme').reduce((s, t) => s + t.amount, 0);
  const ytdExpense = propTxns.filter(t => t.date.startsWith(yr) && t.type === 'ausgabe').reduce((s, t) => s + Math.abs(t.amount), 0);

  const propDocs = documents.filter(d => d.propertyId === prop.id && !d.unitId);
  const propMaint = maintenance.filter(m => m.propertyId === prop.id && m.status !== 'erledigt');
  const cloudPropDocs = useDocuments({ propertyId: prop.id, scope: 'allgemein' });

  const yearsHeld = prop.purchaseDate ? ((Date.now() - new Date(prop.purchaseDate)) / (1000 * 60 * 60 * 24 * 365)).toFixed(1) : '—';
  const grossYield = prop.purchasePrice > 0 ? ((monthlyRent * 12) / prop.purchasePrice * 100).toFixed(2) : null;

  return (
    <div className="page">
      <div className="detail-hero">
        <div>
          <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--ink-4)', marginBottom: 12 }}>{prop.type}</div>
          <h1>{prop.name}</h1>
          <div className="addr">{prop.address}</div>
          <div className="page-actions">
            <button className="btn" onClick={() => setShowAddUnit(true)}><Icon.Plus /> Einheit hinzufügen</button>
            <button className="btn btn-ghost" onClick={() => setShowImport(true)}>📊 CSV importieren</button>
            <button className="btn btn-ghost" onClick={() => setShowEdit(true)}>Bearbeiten</button>
            <button className="btn btn-ghost" onClick={() => setShowDelete(true)} style={{ color: 'var(--neg)' }}>Löschen</button>
          </div>
          <div className="detail-hero-meta">
            <div className="detail-meta-item"><div className="l">Baujahr</div><div className="v">{prop.yearBuilt || '—'}</div></div>
            <div className="detail-meta-item"><div className="l">Im Bestand seit</div><div className="v">{prop.purchaseDate ? `${fmtDate(prop.purchaseDate)} (${yearsHeld} Jahre)` : '—'}</div></div>
            <div className="detail-meta-item"><div className="l">Kaufpreis</div><div className="v">{prop.purchasePrice ? fmtEUR(prop.purchasePrice) : '—'}</div></div>
            <div className="detail-meta-item"><div className="l">Bruttorendite</div><div className="v">{grossYield ? `${grossYield} %` : '—'}</div></div>
          </div>
        </div>

        <aside className="detail-hero-side">
          <div className="mini-stat">
            <div className="l">Sollmiete / Monat</div>
            <div className="v">{fmtEUR(monthlyRent)}</div>
          </div>
          <div className="mini-stat">
            <div className="l">Auslastung</div>
            <div className="v">{occupied}/{prop.units.length}</div>
          </div>
          <div className="mini-stat">
            <div className="l">Wohnfläche</div>
            <div className="v">{totalSize} m²</div>
          </div>
          <div style={{ borderTop: '1px solid var(--line)', paddingTop: 16 }}>
            <div className="kv-list">
              <div className="kv"><span className="k">Einnahmen YTD</span><span className="v" style={{ color: 'var(--pos)' }}>+{fmtEUR(ytdIncome)}</span></div>
              <div className="kv"><span className="k">Ausgaben YTD</span><span className="v" style={{ color: 'var(--neg)' }}>−{fmtEUR(ytdExpense)}</span></div>
              <div className="kv"><span className="k">Netto YTD</span><span className="v" style={{ fontWeight: 500 }}>{fmtEUR(ytdIncome - ytdExpense)}</span></div>
            </div>
          </div>
        </aside>
      </div>

      <PropertyForm open={showEdit} onClose={() => setShowEdit(false)} store={store} initial={prop} />
      <UnitForm open={showAddUnit} onClose={() => setShowAddUnit(false)} store={store} propertyId={prop.id} tenants={tenants} />
      <CsvImportModal open={showImport} onClose={() => setShowImport(false)} store={store} properties={properties} defaultPropertyId={prop.id} />
      <ConfirmDialog
        open={showDelete}
        onClose={() => setShowDelete(false)}
        onConfirm={async () => { await store.deleteProperty(prop.id); setRoute({ page: 'properties' }); }}
        title="Objekt löschen"
        message={`„${prop.name}" und alle ${prop.units.length} Einheiten endgültig löschen? Buchungen werden ebenfalls gelöscht. Hochgeladene Dokumente bleiben erhalten.`}
        confirmLabel="Endgültig löschen"
      />

      <div className="section">
        <div className="section-header">
          <h2 className="section-title">Einheiten</h2>
          <button className="section-link" onClick={() => setShowAddUnit(true)}><Icon.Plus /> Hinzufügen</button>
        </div>
        {prop.units.length === 0 ? (
          <div className="empty"><div className="empty-title">Keine Einheiten</div><div>Lege die erste Wohnung / Einheit dieses Objekts an.</div><button className="btn btn-primary" style={{ marginTop: 16 }} onClick={() => setShowAddUnit(true)}><Icon.Plus /> Einheit anlegen</button></div>
        ) : (
        <div className="units-list">
          {prop.units.map((unit, i) => {
            const tenant = unit.tenant ? tenants[unit.tenant] : null;
            return (
              <button key={unit.id} className="unit-row" onClick={() => setRoute({ page: 'properties', propertyId: prop.id, unitId: unit.id })}>
                <div className="unit-num">{String(i + 1).padStart(2, '0')}</div>
                <div>
                  <div className="unit-label">{unit.label}</div>
                  <div className="unit-floor">{unit.floor} · {unit.rooms} Zi · {unit.size} m²</div>
                </div>
                <div>
                  <div className="unit-num-val">{tenant ? tenant.name : <span style={{ color: 'var(--ink-4)' }}>—</span>}</div>
                  <div className="unit-num-label">Mieter</div>
                </div>
                <div>
                  <div className="unit-num-val">{unit.rent ? fmtEUR(unit.rent) : <span style={{ color: 'var(--ink-4)' }}>—</span>}</div>
                  <div className="unit-num-label">Miete</div>
                </div>
                <div>
                  <div className="unit-num-val">{tenant ? fmtDateShort(tenant.since) : '—'}</div>
                  <div className="unit-num-label">Seit</div>
                </div>
                <div><StatusPill status={unit.status} /></div>
                <div className="unit-chevron"><Icon.ChevronRight /></div>
              </button>
            );
          })}
        </div>
        )}
      </div>

      <div className="two-col">
        <div className="section">
          <div className="section-header">
            <h2 className="section-title">Objektdokumente</h2>
            <UploadButton
              className="section-link"
              label="↑ Hochladen"
              meta={{ propertyId: prop.id, scope: 'allgemein' }}
              propertyContext={prop.name}
              onUpload={() => cloudPropDocs.reload()}
            />
          </div>
          <div style={{ marginBottom: 16 }}>
            <DropZone
              compact
              meta={{ propertyId: prop.id, scope: 'allgemein' }}
              propertyContext={prop.name}
              onUpload={() => cloudPropDocs.reload()}
              label="Dateien hierher ziehen oder klicken"
              subLabel={`Wird unter "${prop.name}" als Objekt-Dokument gespeichert`}
            />
          </div>
          {cloudPropDocs.items.length > 0 && (
            <div style={{ marginBottom: 16 }}>
              {cloudPropDocs.items.map(doc => (
                <div key={doc.id} className="doc-row">
                  <div className="doc-icon"></div>
                  <div>
                    <a href={viewDocumentUrl(doc.id)} target="_blank" rel="noopener" title="Im Browser öffnen" style={{ fontWeight: 500, color: 'var(--ink)', textDecoration: 'none' }}>{doc.name}</a>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{(doc.sizeBytes / 1024).toFixed(0)} KB · {fmtDateShort(doc.uploadedAt)}</div>
                  </div>
                  <Pill>{doc.category || 'Cloud'}</Pill>
                  <a href={downloadDocumentUrl(doc.id)} className="doc-download-btn" title="Herunterladen" download>↓</a>
                  <button className="btn-link" style={{ fontSize: 12, color: 'var(--neg)' }} onClick={() => { if (confirm('Wirklich löschen?')) cloudPropDocs.remove(doc.id); }}>Löschen</button>
                  <span></span>
                </div>
              ))}
            </div>
          )}
          {propDocs.length === 0 && cloudPropDocs.items.length === 0 ? (
            <div className="empty"><div className="empty-title">Keine Dokumente</div><div>Lade Versicherungspolicen, Grundbuchauszüge oder Hausgeldabrechnungen hoch.</div></div>
          ) : propDocs.length === 0 ? null : (
            <div>
              {propDocs.map(doc => (
                <div key={doc.id} className="doc-row">
                  <div className="doc-icon"></div>
                  <div>
                    <div style={{ fontWeight: 500, color: 'var(--ink)' }}>{doc.name}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{doc.size}</div>
                  </div>
                  <Pill>{doc.category}</Pill>
                  <span className="muted" style={{ fontSize: 12 }}>{fmtDateShort(doc.date)}</span>
                  <span></span>
                  <span className="unit-chevron"><Icon.ChevronRight /></span>
                </div>
              ))}
            </div>
          )}
        </div>

        <div className="section">
          <div className="section-header">
            <h2 className="section-title">Wartung & Reparatur</h2>
          </div>
          {propMaint.length === 0 ? (
            <div className="text-muted" style={{ fontSize: 13 }}>Keine offenen Vorgänge.</div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {propMaint.map(m => (
                <div key={m.id} style={{ padding: '14px 0', borderBottom: '1px solid var(--line)' }}>
                  <div style={{ fontWeight: 500, marginBottom: 4 }}>{m.title}</div>
                  <div style={{ display: 'flex', gap: 12, alignItems: 'center', fontSize: 12, color: 'var(--ink-3)' }}>
                    <Pill tone={m.status === 'in-arbeit' ? 'warn' : 'default'}>{m.status === 'in-arbeit' ? 'In Arbeit' : 'Geplant'}</Pill>
                    <span>fällig {fmtDateShort(m.due)}</span>
                    <span>·</span>
                    <span style={{ fontVariantNumeric: 'tabular-nums' }}>{fmtEUR(m.cost)}</span>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ───── Unit Detail (Wohnung) with tabs ─────

function UnitDetail({ data, route, setRoute }) {
  const { properties, tenants, transactions, documents, meterReadings, store } = data;
  const prop = properties.find(p => p.id === route.propertyId);
  const unit = prop?.units.find(u => u.id === route.unitId);
  if (!unit) return <div className="page"><div className="empty">Einheit nicht gefunden.</div></div>;

  const [tab, setTab] = React.useState('overview');
  const [showEditUnit, setShowEditUnit] = React.useState(false);
  const [showDeleteUnit, setShowDeleteUnit] = React.useState(false);
  const [showAddTenant, setShowAddTenant] = React.useState(false);
  const [showTxForm, setShowTxForm] = React.useState(false);
  const [editingTx, setEditingTx] = React.useState(null);
  const [txDefaultType, setTxDefaultType] = React.useState('einnahme');
  const tenant = unit.tenant ? tenants[unit.tenant] : null;
  const cloud = useDocuments({ propertyId: prop.id, unitId: unit.id, scope: 'einheit' });

  const unitTxns = transactions.filter(t => t.unitId === unit.id);
  const unitDocs = documents.filter(d => d.unitId === unit.id);
  const unitMeters = meterReadings.filter(m => m.unitId === unit.id);

  const incomeTxns = unitTxns.filter(t => t.type === 'einnahme');
  const expenseTxns = unitTxns.filter(t => t.type === 'ausgabe');

  return (
    <div className="page">
      <div className="page-header">
        <div>
          <div style={{ fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.12em', color: 'var(--ink-4)', marginBottom: 8 }}>{prop.name}</div>
          <h1 className="page-title">{unit.label}</h1>
          <div className="page-subtitle">{unit.floor || '—'}{unit.rooms ? ` · ${unit.rooms} Zimmer` : ''}{unit.size ? ` · ${unit.size} m²` : ''} · <StatusPill status={unit.status} /></div>
        </div>
        <div className="page-actions">
          <button className="btn" onClick={() => setShowEditUnit(true)}>Bearbeiten</button>
          <button className="btn btn-ghost" onClick={() => setShowDeleteUnit(true)} style={{ color: 'var(--neg)' }}>Löschen</button>
          <button className="btn btn-primary" onClick={() => { setEditingTx(null); setShowTxForm(true); }}><Icon.Plus /> Buchung</button>
        </div>
      </div>
      <UnitForm open={showEditUnit} onClose={() => setShowEditUnit(false)} store={store} propertyId={prop.id} tenants={tenants} initial={unit} />
      <ConfirmDialog
        open={showDeleteUnit}
        onClose={() => setShowDeleteUnit(false)}
        onConfirm={async () => { await store.deleteUnit(unit.id); setRoute({ page: 'properties', propertyId: prop.id }); }}
        title="Einheit löschen"
        message={`„${unit.label}" endgültig löschen? Verknüpfte Buchungen werden vom Mieter gelöst (bleiben dem Objekt zugeordnet).`}
        confirmLabel="Endgültig löschen"
      />
      <TenantForm open={showAddTenant} onClose={() => setShowAddTenant(false)} store={store} />
      <TransactionForm
        open={showTxForm} onClose={() => { setShowTxForm(false); setEditingTx(null); }}
        store={store} properties={properties}
        defaultPropertyId={prop.id} defaultUnitId={unit.id} defaultType={txDefaultType}
        initial={editingTx}
      />

      <div className="tabs">
        <button className={`tab ${tab === 'overview' ? 'active' : ''}`} onClick={() => setTab('overview')}>Übersicht</button>
        <button className={`tab ${tab === 'income' ? 'active' : ''}`} onClick={() => setTab('income')}>Einnahmen <span className="tab-count">{incomeTxns.length}</span></button>
        <button className={`tab ${tab === 'expense' ? 'active' : ''}`} onClick={() => setTab('expense')}>Ausgaben <span className="tab-count">{expenseTxns.length}</span></button>
        <button className={`tab ${tab === 'docs' ? 'active' : ''}`} onClick={() => setTab('docs')}>Dokumente <span className="tab-count">{unitDocs.length}</span></button>
        <button className={`tab ${tab === 'meters' ? 'active' : ''}`} onClick={() => setTab('meters')}>Zählerstände</button>
      </div>

      {tab === 'overview' && (
        <div className="two-col">
          <div>
            <div className="section">
              <div className="section-header"><h2 className="section-title">Aktuelle Buchungen</h2></div>
              <div className="table-wrap">
                <table className="table">
                  <thead><tr><th>Datum</th><th>Beschreibung</th><th>Kategorie</th><th className="num">Betrag</th></tr></thead>
                  <tbody>
                    {unitTxns.slice(0, 8).map(tx => (
                      <tr key={tx.id}>
                        <td className="muted">{fmtDateShort(tx.date)}</td>
                        <td className="strong">{tx.description}</td>
                        <td><Pill>{tx.category}</Pill></td>
                        <td className="num strong" style={{ color: tx.amount > 0 ? 'var(--pos)' : 'var(--neg)' }}>
                          {tx.amount > 0 ? '+' : ''}{fmtEUR(tx.amount)}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
            {tenant ? (
              <div className="side-card">
                <h3>Mieter</h3>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <div className="avatar" style={{ width: 36, height: 36, fontSize: 13 }}>{tenant.name.split(' ').map(s => s[0]).slice(0, 2).join('')}</div>
                  <div>
                    <div style={{ fontWeight: 500 }}>{tenant.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{tenant.email}</div>
                  </div>
                </div>
                <div className="kv-list">
                  <div className="kv"><span className="k">Telefon</span><span className="v">{tenant.phone}</span></div>
                  <div className="kv"><span className="k">Mieter seit</span><span className="v">{fmtDate(tenant.since)}</span></div>
                  <div className="kv"><span className="k">Vertragsende</span><span className="v">{tenant.until ? fmtDate(tenant.until) : 'unbefristet'}</span></div>
                  <div className="kv"><span className="k">Kaution</span><span className="v">{fmtEUR(tenant.deposit)}</span></div>
                  <div className="kv"><span className="k">Kaltmiete</span><span className="v">{fmtEUR(unit.rent)}</span></div>
                </div>
                <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
                  <StartMessageButton
                    tenantId={unit.tenant} propertyId={prop.id} unitId={unit.id}
                    label="✉ Nachricht" className="btn btn-primary btn-sm"
                    setRoute={setRoute} data={data} />
                  <button className="btn btn-sm btn-ghost">📞 Anrufen</button>
                </div>
              </div>
            ) : (
              <div className="side-card">
                <h3>Leerstand</h3>
                <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>Diese Einheit ist aktuell nicht vermietet.</div>
                <button
                  className="btn btn-primary"
                  style={{ alignSelf: 'flex-start' }}
                  onClick={() => setRoute({ page: 'contracts', contractWizard: 'mietvertrag-wohn', propertyId: prop.id, unitId: unit.id })}
                >
                  <Icon.Plus /> Mietvertrag mit neuem Mieter
                </button>
              </div>
            )}

            <div className="side-card">
              <h3>Dokumente / Belege</h3>
              <DropZone
                compact
                meta={{ propertyId: prop.id, unitId: unit.id, scope: 'einheit' }}
                propertyContext={prop.name}
                unitContext={unit.label}
                onUpload={() => cloud.reload()}
                label="Datei hierher ziehen"
                subLabel="oder klicken zum Auswählen"
              />
              {cloud.items.length > 0 && (
                <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 6 }}>
                  {cloud.items.length} {cloud.items.length === 1 ? 'Dokument' : 'Dokumente'} hochgeladen ·{' '}
                  <button className="btn-link" onClick={() => setTab('docs')} style={{ fontSize: 11.5 }}>anzeigen →</button>
                </div>
              )}
            </div>

            <div className="side-card">
              <h3>Schnellaktionen</h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                <button className="btn btn-ghost" style={{ justifyContent: 'flex-start' }} onClick={() => { setEditingTx(null); setTxDefaultType('einnahme'); setShowTxForm(true); }}><Icon.Plus /> Einnahme erfassen</button>
                <button className="btn btn-ghost" style={{ justifyContent: 'flex-start' }} onClick={() => { setEditingTx(null); setTxDefaultType('ausgabe'); setShowTxForm(true); }}><Icon.Plus /> Ausgabe erfassen</button>
                <button className="btn btn-ghost" style={{ justifyContent: 'flex-start' }} onClick={() => setRoute({ page: 'maintenance' })}><Icon.Wrench /> Wartung anlegen</button>
              </div>
            </div>
          </div>
        </div>
      )}

      {(tab === 'income' || tab === 'expense') && (
        <TxnTab
          txns={tab === 'income' ? incomeTxns : expenseTxns}
          kind={tab}
          onAdd={() => { setEditingTx(null); setShowTxForm(true); }}
          onEdit={(tx) => { setEditingTx(tx); setShowTxForm(true); }}
          onDelete={async (tx) => { if (confirm('Buchung wirklich löschen?')) await store.deleteTransaction(tx.id); }}
        />
      )}

      {tab === 'docs' && (
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16, alignItems: 'center' }}>
            <div className="text-muted" style={{ fontSize: 13 }}>
              {cloud.items.length + unitDocs.length} Dokumente
              {cloud.loading && <span style={{ marginLeft: 8, fontSize: 11 }}>· lade…</span>}
              {cloud.error && <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--neg)' }}>· {cloud.error}</span>}
            </div>
            <UploadButton
              className="btn btn-primary"
              label="↑ Dokument hochladen"
              meta={{ propertyId: prop.id, unitId: unit.id, scope: 'einheit' }}
              propertyContext={prop.name}
              unitContext={unit.label}
              onUpload={() => cloud.reload()}
            />
          </div>
          <div style={{ marginBottom: 16 }}>
            <DropZone
              compact
              meta={{ propertyId: prop.id, unitId: unit.id, scope: 'einheit' }}
              propertyContext={prop.name}
              unitContext={unit.label}
              onUpload={() => cloud.reload()}
              label="Dateien hierher ziehen oder klicken"
              subLabel={`Wird unter "${prop.name} · ${unit.label}" gespeichert`}
            />
          </div>
          {cloud.items.length > 0 && (
            <div style={{ marginBottom: 24 }}>
              <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--ink-3)', letterSpacing: '.06em', textTransform: 'uppercase', marginBottom: 8 }}>Hochgeladen · Cloud</div>
              {cloud.items.map(doc => (
                <div key={doc.id} className="doc-row">
                  <div className="doc-icon"></div>
                  <div>
                    <a href={viewDocumentUrl(doc.id)} target="_blank" rel="noopener" title="Im Browser öffnen" style={{ fontWeight: 500, color: 'var(--ink)', textDecoration: 'none' }}>{doc.name}</a>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{(doc.sizeBytes / 1024).toFixed(0)} KB · {fmtDateShort(doc.uploadedAt)}</div>
                  </div>
                  <Pill>{doc.category || 'Dokument'}</Pill>
                  <a href={downloadDocumentUrl(doc.id)} className="doc-download-btn" title="Herunterladen" download>↓</a>
                  <button className="btn-link" style={{ fontSize: 12, color: 'var(--neg)' }} onClick={() => { if (confirm('Wirklich löschen?')) cloud.remove(doc.id); }}>Löschen</button>
                  <span></span>
                </div>
              ))}
            </div>
          )}
          {unitDocs.length === 0 && cloud.items.length === 0 ? (
            <div className="empty">
              <div className="empty-title">Noch keine Dokumente</div>
              <div>Mietvertrag, Übergabeprotokoll, Nebenkostenabrechnungen…</div>
            </div>
          ) : unitDocs.length === 0 ? null : (
            <div>
              {unitDocs.map(doc => (
                <div key={doc.id} className="doc-row">
                  <div className="doc-icon"></div>
                  <div>
                    <div style={{ fontWeight: 500, color: 'var(--ink)' }}>{doc.name}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--ink-3)', marginTop: 2 }}>{doc.size}</div>
                  </div>
                  <Pill>{doc.category}</Pill>
                  <span className="muted" style={{ fontSize: 12 }}>{fmtDateShort(doc.date)}</span>
                  <span></span>
                  <span className="unit-chevron"><Icon.ChevronRight /></span>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {tab === 'meters' && (
        <div>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16, alignItems: 'center' }}>
            <div className="text-muted" style={{ fontSize: 13 }}>Letzte Ablesung: {unitMeters[0] ? fmtDate(unitMeters[0].date) : '—'}</div>
            <button className="btn btn-primary"><Icon.Plus /> Ablesung erfassen</button>
          </div>
          {unitMeters.length === 0 ? (
            <div className="empty"><div className="empty-title">Keine Zählerstände</div><div>Erfasse Strom, Wasser und Gas für die jährliche Abrechnung.</div></div>
          ) : (
            <div className="table-wrap">
              <table className="table">
                <thead><tr><th>Zähler</th><th>Datum</th><th className="num">Wert</th><th>Einheit</th></tr></thead>
                <tbody>
                  {unitMeters.map(m => (
                    <tr key={m.id}>
                      <td className="strong">{m.type}</td>
                      <td className="muted">{fmtDateShort(m.date)}</td>
                      <td className="num strong">{fmtNum(m.value)}</td>
                      <td className="muted">{m.unit}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

function TxnTab({ txns, kind, onAdd, onEdit, onDelete }) {
  const total = txns.reduce((s, t) => s + Math.abs(t.amount), 0);
  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16, alignItems: 'center' }}>
        <div>
          <div className="text-muted" style={{ fontSize: 12, textTransform: 'uppercase', letterSpacing: '0.1em' }}>Summe {kind === 'income' ? 'Einnahmen' : 'Ausgaben'}</div>
          <div style={{ fontFamily: 'var(--font-serif)', fontSize: 28, fontVariantNumeric: 'tabular-nums', color: kind === 'income' ? 'var(--pos)' : 'var(--neg)' }}>
            {kind === 'income' ? '+' : '−'}{fmtEUR(total)}
          </div>
        </div>
        <button className="btn btn-primary" onClick={onAdd}><Icon.Plus /> {kind === 'income' ? 'Einnahme' : 'Ausgabe'}</button>
      </div>
      {txns.length === 0 ? (
        <div className="empty"><div className="empty-title">Noch keine {kind === 'income' ? 'Einnahmen' : 'Ausgaben'}</div><div>Erfasse die erste Buchung oben rechts.</div></div>
      ) : (
        <div className="table-wrap">
          <table className="table">
            <thead><tr><th>Datum</th><th>Beschreibung</th><th>Kategorie</th><th className="num">Betrag</th><th></th></tr></thead>
            <tbody>
              {txns.map(tx => (
                <tr key={tx.id}>
                  <td className="muted">{fmtDateShort(tx.date)}</td>
                  <td className="strong">{tx.description || '—'}</td>
                  <td>{tx.category && <Pill>{tx.category}</Pill>}</td>
                  <td className="num strong" style={{ color: tx.amount > 0 ? 'var(--pos)' : 'var(--neg)' }}>
                    {tx.amount > 0 ? '+' : ''}{fmtEUR(tx.amount)}
                  </td>
                  <td className="num" style={{ whiteSpace: 'nowrap' }}>
                    <button className="btn-link" onClick={() => onEdit?.(tx)} style={{ fontSize: 12 }}>✎</button>
                    <button className="btn-link" onClick={() => onDelete?.(tx)} style={{ fontSize: 12, marginLeft: 8, color: 'var(--neg)' }}>✕</button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { PropertyDetail, UnitDetail });
