// Desktop Equipment-Analyse — comprehensive analytics modal opened from the
// Equipment toolbar. Aggregates rentals + maintenance data into KPIs, rankings,
// revenue history, and a full detail table. Read-only.

// ── Helpers ─────────────────────────────────────────────────────────────
// Date arithmetic
const _eaYM = (iso) => iso ? iso.slice(0, 7) : '';
const _eaMonthsBack = (n) => {
  const today = new Date();
  const out = [];
  for (let i = n - 1; i >= 0; i--) {
    const d = new Date(today.getFullYear(), today.getMonth() - i, 1);
    out.push({
      key: `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`,
      label: DE_MONTHS_SHORT[d.getMonth()],
      isCurrent: i === 0,
    });
  }
  return out;
};

// Per-rental: which equipment IDs + qty + dailyRate it has
function _eaRentalLines(r) {
  if (Array.isArray(r.items) && r.items.length) {
    return r.items.map((it) => ({
      equipmentId: it.equipmentId,
      qty: Math.max(1, Number(it.quantity) || 1),
      dailyRate: Number(it.dailyRate) || 0,
    }));
  }
  if (r.equipmentId) return [{ equipmentId: r.equipmentId, qty: Math.max(1, Number(r.quantity) || 1), dailyRate: Number(r.dailyRate) || 0 }];
  return [];
}

// Revenue contribution of one equipment item across all (non-cancelled) rentals.
function eqRevenue(equipmentId, rentals) {
  let total = 0;
  for (const r of rentals || []) {
    const days = Math.max(1, daysBetween(r.start, r.end));
    for (const l of _eaRentalLines(r)) {
      if (l.equipmentId === equipmentId) total += days * l.qty * l.dailyRate;
    }
  }
  return total;
}

// Monthly revenue by equipment: { '2026-05': 240, ... } over the past `n` months.
function eqMonthlyRevenue(equipmentId, rentals, months) {
  const map = {};
  months.forEach((m) => map[m.key] = 0);
  for (const r of rentals || []) {
    const key = _eaYM(r.start);
    if (!(key in map)) continue;
    const days = Math.max(1, daysBetween(r.start, r.end));
    for (const l of _eaRentalLines(r)) {
      if (l.equipmentId === equipmentId) map[key] += days * l.qty * l.dailyRate;
    }
  }
  return map;
}

// ── Small atoms ─────────────────────────────────────────────────────────
function EaKpi({ label, value, sub, color, icon }) {
  const t = useTheme();
  return (
    <div style={{ background: t.cardAlt, borderRadius: 12, padding: '14px 16px', border: `0.5px solid ${t.sep}` }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
        {icon && <div style={{ width: 22, height: 22, borderRadius: 6, background: (color || t.accent) + '22', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon d={icon} color={color || t.accent} size={12} sw={2.2} />
        </div>}
        <div style={{ fontSize: 10.5, fontWeight: 700, color: t.textSec, textTransform: 'uppercase', letterSpacing: 0.5 }}>{label}</div>
      </div>
      <div style={{ fontSize: 22, fontWeight: 700, color: color || t.text, marginTop: 8, letterSpacing: -0.4, ...NUMS }}>{value}</div>
      {sub && <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 2, ...NUMS }}>{sub}</div>}
    </div>
  );
}

function EaSection({ title, sub, children, action }) {
  const t = useTheme();
  return (
    <div style={{ marginTop: 22 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 700, color: t.text, letterSpacing: -0.2 }}>{title}</div>
          {sub && <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 1 }}>{sub}</div>}
        </div>
        {action}
      </div>
      {children}
    </div>
  );
}

// ── Main view ──────────────────────────────────────────────────────────
function EquipmentAnalyseSheet({ open, onClose, equipment, rentals, go }) {
  const t = useTheme();
  const [tab, setTab] = useState('overview'); // overview | revenue | maint | table
  const [revRange, setRevRange] = useState(12); // months
  useEffect(() => { if (!open) setTab('overview'); }, [open]);
  if (!open) return null;

  // ── Aggregates ────────────────────────────────────────────────────
  const totalKinds = equipment.length;
  const totalUnits = equipment.reduce((s, e) => s + Math.max(1, Number(e.qty) || 1), 0);
  const stockBy = equipment.map((e) => ({ e, st: eqStock(e, rentals) }));
  const liveOut = stockBy.reduce((s, x) => s + x.st.vermietet, 0);
  const inRepair = stockBy.reduce((s, x) => s + x.st.reparatur, 0);
  const available = stockBy.reduce((s, x) => s + x.st.verfuegbar, 0);
  const liveUtilPct = totalUnits > 0 ? Math.round(liveOut / totalUnits * 100) : 0;
  const repairPct = totalUnits > 0 ? Math.round(inRepair / totalUnits * 100) : 0;

  const enriched = equipment.map((e) => {
    const revenue = eqRevenue(e.id, rentals);
    const uses = eqUses(e, rentals);
    const util = eqUtil(e, rentals, equipment);
    const st = eqStock(e, rentals);
    const open = (e.maint || []).filter((m) => !m.done).length;
    const lastService = [...(e.maint || [])].filter((m) => m.done).sort((a, b) => (b.date || '').localeCompare(a.date || ''))[0];
    const nextTuev = (e.maint || []).filter((m) => m.type === 'tuev' && !m.done).sort((a, b) => (a.date || '').localeCompare(b.date || ''))[0];
    return { e, revenue, uses, util, st, openMaint: open, lastService, nextTuev };
  });
  const totalRevenue = enriched.reduce((s, x) => s + x.revenue, 0);
  const totalUses = enriched.reduce((s, x) => s + x.uses, 0);
  const avgDailyRate = equipment.length > 0 ? Math.round(equipment.reduce((s, e) => s + (Number(e.price) || 0), 0) / equipment.length) : 0;
  const openMaintTotal = enriched.reduce((s, x) => s + x.openMaint, 0);

  // By kind (category group)
  const byKind = {};
  equipment.forEach((e) => {
    const k = e.kind || 'Sonstige';
    if (!byKind[k]) byKind[k] = { kind: k, units: 0, revenue: 0, items: 0 };
    byKind[k].units += Math.max(1, Number(e.qty) || 1);
    byKind[k].items += 1;
    byKind[k].revenue += eqRevenue(e.id, rentals);
  });
  const kinds = Object.values(byKind).sort((a, b) => b.revenue - a.revenue);

  // Monthly revenue history (combined + per-equipment)
  const months = _eaMonthsBack(revRange);
  const monthlyTotal = months.map((m) => ({ ...m, value: 0 }));
  const perEqMonthly = equipment.map((e) => ({ e, m: eqMonthlyRevenue(e.id, rentals, months) }));
  perEqMonthly.forEach(({ m }) => {
    months.forEach((mm, i) => { monthlyTotal[i].value += m[mm.key] || 0; });
  });
  const maxMonthly = Math.max(1, ...monthlyTotal.map((m) => m.value));

  // All maintenance entries, flattened with equipment ref
  const allMaint = [];
  equipment.forEach((e) => (e.maint || []).forEach((m) => allMaint.push({ ...m, e })));
  allMaint.sort((a, b) => (a.done === b.done ? (b.date || '').localeCompare(a.date || '') : (a.done ? 1 : -1)));

  // ── Visual styles ─────────────────────────────────────────────────
  const card = { background: t.card, borderRadius: 14, padding: 18, border: `0.5px solid ${t.sep}` };
  const tabs = [
    ['overview', 'Übersicht', icons.bolt],
    ['revenue',  'Umsatz',    icons.euro],
    ['maint',    'Wartung',   icons.bell],
    ['table',    'Tabelle',   icons.doc],
  ];

  return (
    <div role="dialog" aria-modal="true"
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100 }}>
      <div style={{ background: t.bg, borderRadius: 18, width: 'min(1180px, 96vw)', height: 'min(860px, 92vh)', display: 'flex', flexDirection: 'column', boxShadow: '0 24px 64px rgba(0,0,0,0.35)', overflow: 'hidden' }}>
        {/* Header */}
        <div style={{ padding: '18px 26px', borderBottom: `0.5px solid ${t.sep}`, display: 'flex', alignItems: 'center', gap: 14, background: t.card }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 22, fontWeight: 700, color: t.text, letterSpacing: -0.5 }}>Equipment-Analyse</div>
            <div style={{ fontSize: 12.5, color: t.textSec, marginTop: 2 }}>{totalKinds} Geräte · {totalUnits} Einheiten · {rentals.length} Mietvorgänge ausgewertet</div>
          </div>
          <Pressable onClick={onClose} scale={0.94}>
            <div style={{ width: 32, height: 32, borderRadius: 16, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon d="M6 6l12 12M18 6L6 18" color={t.text} size={13} sw={2.2} />
            </div>
          </Pressable>
        </div>

        {/* Tabs */}
        <div style={{ padding: '12px 26px 0', borderBottom: `0.5px solid ${t.sep}`, display: 'flex', gap: 4, background: t.card }}>
          {tabs.map(([k, label, ic]) => {
            const sel = tab === k;
            return (
              <Pressable key={k} onClick={() => setTab(k)} scale={0.97}>
                <div style={{ padding: '9px 14px 11px', display: 'flex', alignItems: 'center', gap: 6, borderBottom: sel ? `2px solid ${t.text}` : '2px solid transparent', color: sel ? t.text : t.textSec, fontWeight: 600, fontSize: 13 }}>
                  <Icon d={ic} color={sel ? t.text : t.textSec} size={13} sw={2.2} />
                  {label}
                </div>
              </Pressable>
            );
          })}
        </div>

        {/* Body */}
        <div className="rf-scroll" style={{ flex: 1, overflow: 'auto', padding: '20px 26px 30px' }}>

          {tab === 'overview' && (
            <>
              {/* KPI row */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
                <EaKpi label="Bestand" value={`${totalUnits}`} sub={`${totalKinds} Geräte`} icon={icons.cube || icons.doc} />
                <EaKpi label="Aktuell vermietet" value={`${liveUtilPct}%`} sub={`${liveOut} von ${totalUnits} Einheiten`} icon={icons.truck} color={t.accent} />
                <EaKpi label="Verfügbar" value={`${available}`} sub={`${Math.round(available / Math.max(1, totalUnits) * 100)}% des Bestands`} icon={icons.check} color={t.green} />
                <EaKpi label="In Reparatur" value={`${inRepair}`} sub={`${repairPct}% des Bestands`} icon={icons.wrench || icons.edit} color={t.orange} />
                <EaKpi label="Umsatz gesamt" value={`${Math.round(totalRevenue).toLocaleString('de-DE')} €`} sub={`Aus ${rentals.length} Mietvorgängen`} icon={icons.euro} color={t.green} />
                <EaKpi label="Ø Tagessatz" value={`${avgDailyRate} €`} sub="Über alle Geräte" icon={icons.euro} />
                <EaKpi label="Vermietungen" value={`${totalUses}`} sub="Gesamthistorie" icon={icons.bolt} color={t.accent} />
                <EaKpi label="Offene Wartungen" value={`${openMaintTotal}`} sub={openMaintTotal === 0 ? 'Alles aktuell' : 'Bedarf prüfen'} icon={icons.bell} color={openMaintTotal === 0 ? t.green : t.orange} />
              </div>

              {/* Auslastungs-Ranking */}
              <EaSection title="Auslastungs-Ranking" sub="Gesamthistorische Vermietungen je Gerät — wer ist am gefragtesten?">
                <div style={{ ...card }}>
                  {[...enriched].sort((a, b) => b.uses - a.uses || b.revenue - a.revenue).map(({ e, util, uses, revenue }, i, arr) => {
                    const maxUses = Math.max(1, ...arr.map((x) => x.uses));
                    const pct = uses / maxUses * 100;
                    return (
                      <Pressable key={e.id} onClick={() => { go && go('equipment', { equipmentId: e.id }); onClose(); }} scale={0.998} hoverBg={t.cardAlt}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 8px', borderBottom: i === arr.length - 1 ? 'none' : `0.5px solid ${t.sep}` }}>
                          <div style={{ width: 22, fontSize: 11, fontWeight: 700, color: t.textTer, textAlign: 'center', ...NUMS }}>{i + 1}</div>
                          <EqAvatar item={e} size={34} radius={8} />
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.name}</div>
                            <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.cat} · {e.kind}</div>
                          </div>
                          <div style={{ width: 220, height: 8, borderRadius: 4, background: t.chipStrong, overflow: 'hidden', flexShrink: 0 }}>
                            <div style={{ width: `${pct}%`, height: '100%', background: t.accent, borderRadius: 4 }} />
                          </div>
                          <div style={{ width: 80, textAlign: 'right', flexShrink: 0 }}>
                            <div style={{ fontSize: 13, fontWeight: 700, color: t.text, ...NUMS }}>{uses}×</div>
                            <div style={{ fontSize: 10.5, color: t.textSec, ...NUMS }}>Anteil {util}%</div>
                          </div>
                          <div style={{ width: 90, textAlign: 'right', flexShrink: 0 }}>
                            <div style={{ fontSize: 13, fontWeight: 700, color: t.green, ...NUMS }}>{Math.round(revenue).toLocaleString('de-DE')} €</div>
                            <div style={{ fontSize: 10.5, color: t.textSec }}>Umsatz</div>
                          </div>
                        </div>
                      </Pressable>
                    );
                  })}
                </div>
              </EaSection>

              {/* Sortiments-Mix */}
              <EaSection title="Sortiments-Mix nach Typ" sub="Verteilung von Bestand und Umsatz auf die Gerätearten">
                <div style={{ ...card }}>
                  {kinds.map((k, i) => {
                    const unitPct = totalUnits ? (k.units / totalUnits * 100) : 0;
                    const revPct = totalRevenue ? (k.revenue / totalRevenue * 100) : 0;
                    return (
                      <div key={k.kind} style={{ padding: '12px 4px', borderBottom: i === kinds.length - 1 ? 'none' : `0.5px solid ${t.sep}` }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                          <div style={{ flex: 1, fontSize: 13, fontWeight: 600, color: t.text }}>{k.kind}</div>
                          <div style={{ fontSize: 11.5, color: t.textSec, ...NUMS }}>{k.items} Geräte · {k.units} Einheiten</div>
                          <div style={{ fontSize: 13, fontWeight: 700, color: t.green, marginLeft: 12, ...NUMS }}>{Math.round(k.revenue).toLocaleString('de-DE')} €</div>
                        </div>
                        <div style={{ display: 'flex', gap: 4, marginTop: 7 }}>
                          <div style={{ flex: 1 }}>
                            <div style={{ fontSize: 10, color: t.textTer, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 3 }}>Bestand</div>
                            <div style={{ height: 6, borderRadius: 3, background: t.chipStrong, overflow: 'hidden' }}>
                              <div style={{ width: `${unitPct}%`, height: '100%', background: t.accent, borderRadius: 3 }} />
                            </div>
                          </div>
                          <div style={{ flex: 1 }}>
                            <div style={{ fontSize: 10, color: t.textTer, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 3 }}>Umsatzanteil</div>
                            <div style={{ height: 6, borderRadius: 3, background: t.chipStrong, overflow: 'hidden' }}>
                              <div style={{ width: `${revPct}%`, height: '100%', background: t.green, borderRadius: 3 }} />
                            </div>
                          </div>
                        </div>
                      </div>
                    );
                  })}
                </div>
              </EaSection>
            </>
          )}

          {tab === 'revenue' && (
            <>
              <EaSection title="Umsatz-Verlauf" sub={`Monatlicher Equipment-Umsatz · letzte ${revRange} Monate`}
                action={<Segmented size="sm" value={revRange} onChange={setRevRange} options={[[6, '6 Monate'], [12, '12 Monate'], [24, '24 Monate']]} />}>
                <div style={{ ...card }}>
                  <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, height: 200, paddingBottom: 28, borderBottom: `0.5px solid ${t.sep}`, position: 'relative' }}>
                    {monthlyTotal.map((m) => {
                      const h = m.value / maxMonthly * 170;
                      return (
                        <div key={m.key} title={`${m.label}: ${Math.round(m.value).toLocaleString('de-DE')} €`} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                          <div style={{ fontSize: 10, color: t.text, fontWeight: 700, opacity: m.value > 0 ? 1 : 0.3, ...NUMS }}>{m.value > 0 ? Math.round(m.value) + '€' : ''}</div>
                          <div style={{ width: '70%', height: Math.max(2, h), borderRadius: 4, background: m.isCurrent ? t.accent : t.text + '88' }} />
                        </div>
                      );
                    })}
                    <div style={{ position: 'absolute', bottom: 6, left: 0, right: 0, display: 'flex', gap: 8 }}>
                      {monthlyTotal.map((m) => (
                        <div key={m.key} style={{ flex: 1, textAlign: 'center', fontSize: 10.5, color: m.isCurrent ? t.text : t.textSec, fontWeight: m.isCurrent ? 700 : 500 }}>{m.label}</div>
                      ))}
                    </div>
                  </div>
                </div>
              </EaSection>

              <EaSection title="Umsatz-Beitrag je Gerät" sub="Wer trägt wieviel zum Gesamtumsatz bei?">
                <div style={{ ...card }}>
                  {[...enriched].sort((a, b) => b.revenue - a.revenue).map(({ e, revenue, uses }, i, arr) => {
                    const pct = totalRevenue > 0 ? revenue / totalRevenue * 100 : 0;
                    return (
                      <Pressable key={e.id} onClick={() => { go && go('equipment', { equipmentId: e.id }); onClose(); }} scale={0.998} hoverBg={t.cardAlt}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 8px', borderBottom: i === arr.length - 1 ? 'none' : `0.5px solid ${t.sep}` }}>
                          <EqAvatar item={e} size={32} radius={7} />
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ fontSize: 13, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.name}</div>
                            <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, ...NUMS }}>{uses} Vermietungen · Ø {uses > 0 ? Math.round(revenue / uses) : 0} € pro Vorgang</div>
                          </div>
                          <div style={{ flex: 1, height: 10, borderRadius: 5, background: t.chipStrong, overflow: 'hidden', maxWidth: 280 }}>
                            <div style={{ width: `${pct}%`, height: '100%', background: t.green, borderRadius: 5 }} />
                          </div>
                          <div style={{ width: 110, textAlign: 'right', flexShrink: 0 }}>
                            <div style={{ fontSize: 14, fontWeight: 700, color: t.text, ...NUMS }}>{Math.round(revenue).toLocaleString('de-DE')} €</div>
                            <div style={{ fontSize: 10.5, color: t.textSec, ...NUMS }}>{pct.toFixed(1)}% Anteil</div>
                          </div>
                        </div>
                      </Pressable>
                    );
                  })}
                </div>
              </EaSection>
            </>
          )}

          {tab === 'maint' && (
            <>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
                <EaKpi label="Offene Einträge" value={`${allMaint.filter((m) => !m.done).length}`} sub="Wartung & Reparatur" icon={icons.bell} color={t.orange} />
                <EaKpi label="In Reparatur" value={`${inRepair}`} sub="Einheiten gesperrt" icon={icons.edit} color={t.red} />
                <EaKpi label="TÜV fällig" value={`${allMaint.filter((m) => m.type === 'tuev' && !m.done).length}`} sub="Anhänger gesamt" icon={icons.cal} color="#AF52DE" />
                <EaKpi label="Erledigt gesamt" value={`${allMaint.filter((m) => m.done).length}`} sub="Historie" icon={icons.check} color={t.green} />
              </div>

              <EaSection title="Alle Wartungs- & Reparatur-Einträge" sub="Sortiert: offen zuerst, dann nach Datum">
                <div style={{ ...card, padding: 0 }}>
                  {allMaint.length === 0 ? (
                    <div style={{ padding: '32px 16px', textAlign: 'center', fontSize: 13, color: t.textSec }}>Keine Einträge.</div>
                  ) : allMaint.map((m, i) => {
                    const mm = maintMeta(m.type);
                    return (
                      <Pressable key={m.id} onClick={() => { go && go('equipment', { equipmentId: m.e.id }); onClose(); }} scale={0.998} hoverBg={t.cardAlt}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 16px', borderBottom: i === allMaint.length - 1 ? 'none' : `0.5px solid ${t.sep}`, opacity: m.done ? 0.6 : 1 }}>
                          <div style={{ width: 32, height: 32, borderRadius: 8, background: mm.color + '22', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 15 }}>{mm.icon}</div>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                              <span style={{ fontSize: 13.5, fontWeight: 600, color: t.text, textDecoration: m.done ? 'line-through' : 'none' }}>{m.title}</span>
                              <span style={{ fontSize: 9.5, fontWeight: 700, padding: '2px 7px', borderRadius: 100, background: mm.color + '22', color: mm.color, textTransform: 'uppercase', letterSpacing: 0.3 }}>{mm.label}</span>
                            </div>
                            <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 2 }}>{m.e.name}{m.note ? ' · ' + m.note : ''}</div>
                          </div>
                          <div style={{ textAlign: 'right', flexShrink: 0 }}>
                            <div style={{ fontSize: 12, fontWeight: 600, color: t.text, ...NUMS }}>{m.date ? fmtDateDE(m.date) : '—'}</div>
                            <div style={{ fontSize: 10.5, fontWeight: 700, color: m.done ? t.green : mm.color, marginTop: 2, textTransform: 'uppercase', letterSpacing: 0.4 }}>{m.done ? 'erledigt' : 'offen'}</div>
                          </div>
                        </div>
                      </Pressable>
                    );
                  })}
                </div>
              </EaSection>
            </>
          )}

          {tab === 'table' && (
            <EaSection title="Detail-Tabelle" sub="Alle Kennzahlen pro Gerät">
              <div style={{ background: t.card, borderRadius: 12, border: `0.5px solid ${t.sep}`, overflow: 'hidden' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '2.4fr 1.2fr 0.8fr 0.8fr 0.8fr 1fr 1.1fr', padding: '11px 16px', borderBottom: `0.5px solid ${t.sep}`, background: t.cardAlt, fontSize: 10.5, fontWeight: 700, color: t.textSec, textTransform: 'uppercase', letterSpacing: 0.5 }}>
                  <div>Gerät</div>
                  <div>Kategorie</div>
                  <div style={{ textAlign: 'center' }}>Bestand</div>
                  <div style={{ textAlign: 'center' }}>Reparatur</div>
                  <div style={{ textAlign: 'center' }}>€ / Tag</div>
                  <div style={{ textAlign: 'right' }}>Vermietungen</div>
                  <div style={{ textAlign: 'right' }}>Umsatz</div>
                </div>
                {[...enriched].sort((a, b) => b.revenue - a.revenue).map(({ e, revenue, uses, st }, i, arr) => (
                  <Pressable key={e.id} onClick={() => { go && go('equipment', { equipmentId: e.id }); onClose(); }} scale={0.998} hoverBg={t.cardAlt}>
                    <div style={{ display: 'grid', gridTemplateColumns: '2.4fr 1.2fr 0.8fr 0.8fr 0.8fr 1fr 1.1fr', padding: '12px 16px', borderBottom: i === arr.length - 1 ? 'none' : `0.5px solid ${t.sep}`, alignItems: 'center' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10, minWidth: 0 }}>
                        <EqAvatar item={e} size={28} radius={6} />
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontSize: 13, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.name}</div>
                          <div style={{ fontSize: 10.5, color: t.textSec, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.kind}</div>
                        </div>
                      </div>
                      <div style={{ fontSize: 12, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.cat}</div>
                      <div style={{ textAlign: 'center', fontSize: 12.5, fontWeight: 600, color: t.text, ...NUMS }}>
                        <span style={{ color: t.green }}>{st.verfuegbar}</span><span style={{ color: t.textTer }}> / {st.total}</span>
                      </div>
                      <div style={{ textAlign: 'center', fontSize: 12.5, fontWeight: 600, color: st.reparatur > 0 ? t.orange : t.textTer, ...NUMS }}>{st.reparatur || '—'}</div>
                      <div style={{ textAlign: 'center', fontSize: 12.5, fontWeight: 600, color: t.text, ...NUMS }}>{e.price} €</div>
                      <div style={{ textAlign: 'right', fontSize: 12.5, fontWeight: 600, color: t.text, ...NUMS }}>{uses}</div>
                      <div style={{ textAlign: 'right', fontSize: 13, fontWeight: 700, color: t.green, ...NUMS }}>{Math.round(revenue).toLocaleString('de-DE')} €</div>
                    </div>
                  </Pressable>
                ))}
                <div style={{ display: 'grid', gridTemplateColumns: '2.4fr 1.2fr 0.8fr 0.8fr 0.8fr 1fr 1.1fr', padding: '12px 16px', background: t.cardAlt, fontSize: 12.5, fontWeight: 700, color: t.text, borderTop: `1px solid ${t.sep}` }}>
                  <div>Summe</div>
                  <div style={{ color: t.textSec }}>{kinds.length} Typ{kinds.length === 1 ? '' : 'en'}</div>
                  <div style={{ textAlign: 'center', ...NUMS }}>{available} / {totalUnits}</div>
                  <div style={{ textAlign: 'center', color: inRepair > 0 ? t.orange : t.textTer, ...NUMS }}>{inRepair || '—'}</div>
                  <div style={{ textAlign: 'center', color: t.textSec, ...NUMS }}>Ø {avgDailyRate} €</div>
                  <div style={{ textAlign: 'right', ...NUMS }}>{totalUses}</div>
                  <div style={{ textAlign: 'right', color: t.green, ...NUMS }}>{Math.round(totalRevenue).toLocaleString('de-DE')} €</div>
                </div>
              </div>
            </EaSection>
          )}

        </div>
      </div>
    </div>
  );
}

Object.assign(window, { EquipmentAnalyseSheet, eqRevenue, eqMonthlyRevenue });
