// Desktop Dashboard — Übersicht. Rich multi-column overview.

function buildAutoTasks(rentals = [], equipment = []) {
  const today = todayISO();
  const out = [];
  rentals.forEach((r) => {
    const eq = equipment.find((e) => e.id === r.equipmentId);
    const eqName = eq ? eq.name : r.equipmentName;
    const dStart = daysBetween(today, r.start) - 1;
    if (r.status !== 'abgeschlossen' && dStart >= 0 && dStart <= 4) {
      const when = dStart === 0 ? 'heute' : dStart === 1 ? 'morgen' : `in ${dStart} Tagen`;
      out.push({ key: 'prep:' + r.id, icon: '📦', text: `Equipment für ${r.tenantName} vorbereiten`, sub: `${eqName} · Abholung ${when}`, rentalId: r.id });
    }
    const dEnd = daysBetween(today, r.end) - 1;
    if (r.status === 'aktiv' && dEnd >= -2 && dEnd <= 1) {
      out.push({ key: 'check:' + r.id, icon: '🔍', text: 'Equipment nach Rückgabe prüfen', sub: `${r.tenantName} · ${eqName}`, rentalId: r.id });
    }
  });
  equipment.forEach((e) => (e.maint || []).forEach((m) => {
    if (!m.done && (m.type === 'defect' || m.type === 'repair')) out.push({ key: 'fix:' + m.id, icon: '🔧', text: m.title, sub: e.name });
  }));
  return out;
}

function Bullet({ done, onClick, color }) {
  const t = useTheme();
  return (
    <Pressable onClick={onClick} scale={0.85}>
      <div style={{ width: 22, height: 22, borderRadius: 11, flexShrink: 0, border: done ? 'none' : `1.5px solid ${t.textTer}`, background: done ? (color || t.accent) : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all 0.15s' }}>
        {done && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="3.2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5L20 7"/></svg>}
      </div>
    </Pressable>
  );
}

function ScreenDashboard({ go, equipment, rentals = [], events = [], tasks, setTasks, dark, toggleDark }) {
  const t = useTheme();
  const toast = useToast();
  const active = rentals.filter((r) => r.status === 'aktiv');
  const reserved = rentals.filter((r) => r.status === 'reserviert');
  const fin = buildFinanceSummary(FIN_BARS);
  const CURRENT_BALANCE = 4820;

  const topShare = equipment.reduce((m, e) => Math.max(m, eqUtil(e, rentals, equipment)), 0);
  const verfuegbar = equipment.reduce((s, e) => s + eqStock(e, rentals).verfuegbar, 0);
  const vermietet = equipment.reduce((s, e) => s + eqStock(e, rentals).vermietet, 0);
  const totalStock = equipment.reduce((s, e) => s + Math.max(1, Number(e.qty) || 1), 0);
  const liveUtilPct = totalStock > 0 ? Math.round(vermietet / totalStock * 100) : 0;
  const depositsHeld = rentals.filter((r) => r.depositStatus === 'erhalten').reduce((s, r) => s + (Number(r.deposit) || 0), 0);
  const openDeposits = rentals.filter((r) => r.depositStatus === 'offen').length;

  // tasks
  const items = (tasks && tasks.items) || [];
  const autoDone = (tasks && tasks.autoDone) || {};
  const autoDismissed = (tasks && tasks.autoDismissed) || {};
  const auto = buildAutoTasks(rentals, equipment).filter((a) => !autoDismissed[a.key]);
  const toggleAuto = (key) => setTasks((prev) => ({ ...prev, autoDone: { ...(prev.autoDone || {}), [key]: !(prev.autoDone || {})[key] } }));
  const toggleManual = (id) => setTasks((prev) => ({ ...prev, items: (prev.items || []).map((x) => x.id === id ? { ...x, done: !x.done } : x) }));
  const removeManual = (id) => setTasks((prev) => ({ ...prev, items: (prev.items || []).filter((x) => x.id !== id) }));
  const dismissAuto = (key) => { setTasks((prev) => ({ ...prev, autoDismissed: { ...(prev.autoDismissed || {}), [key]: true } })); toast('Erledigung entfernt'); };
  const [adding, setAdding] = useState(false);
  const [text, setText] = useState('');
  const [showAllEq, setShowAllEq] = useState(false);
  const addManual = () => { const v = text.trim(); if (!v) { setAdding(false); return; } setTasks((prev) => ({ ...prev, items: [{ id: 'task-' + Date.now(), text: v, done: false }, ...(prev.items || [])] })); setText(''); setAdding(false); toast('Aufgabe hinzugefügt'); };
  const openCount = auto.filter((a) => !autoDone[a.key]).length + items.filter((i) => !i.done).length;

  // tab state for the Benachrichtigungen card
  const [notifTab, setNotifTab] = useState('todo');
  const [upcRange, setUpcRange] = useState('week');

  // upcoming
  const today = todayISO();
  const rentalEvents = rentals.filter((r) => r.status !== 'abgeschlossen').map((r) => ({ id: 'r:' + r.id, rentalId: r.id, fromRental: true, title: r.tenantName, equipmentId: r.equipmentId, start: r.start, end: r.end, startTime: r.startTime, endTime: r.endTime, color: statusMeta(r.status).color }));
  const allUpcoming = [...events, ...rentalEvents].filter((e) => e.end >= today).sort((a, b) => a.start.localeCompare(b.start));
  const rangeDays = upcRange === 'today' ? 0 : upcRange === 'week' ? 7 : 30;
  const upcoming = allUpcoming.filter((e) => {
    const startsIn = Math.max(0, Math.round((fromISO(e.start) - fromISO(today)) / 86400000));
    return startsIn <= rangeDays || e.start <= today; // include running events
  }).slice(0, 8);
  const upcomingCount = allUpcoming.length;

  const card = { background: t.card, borderRadius: 16, boxShadow: t.shadowCard };

  return (
    <>
      <Toolbar title="Übersicht" subtitle="Mittwoch, 20. Mai 2026">
        <Button variant="primary" icon={icons.plus} onClick={() => go('rentals', { newRental: true })}>Neuer Mietvorgang</Button>
      </Toolbar>
      <Scroll style={{ background: t.bg }}>
        <div style={{ maxWidth: 1180, margin: '0 auto', display: 'grid', gridTemplateColumns: '1.55fr 1fr', gap: 18, alignItems: 'start' }}>

          {/* LEFT column */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            {/* Balance hero */}
            <div style={{ ...card, padding: 24 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div>
                  <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1 }}>Kontostand</div>
                  <div style={{ fontSize: 46, fontWeight: 600, color: t.text, letterSpacing: -1.6, marginTop: 6, ...NUMS }}>{CURRENT_BALANCE.toLocaleString('de-DE')}<span style={{ fontSize: 26, color: t.textSec, fontWeight: 500, marginLeft: 4 }}>€</span></div>
                  <div style={{ fontSize: 12, color: t.textSec, marginTop: 4 }}>Verfügbares Guthaben · {DEFAULT_COMPANY.name}</div>
                </div>
                <div style={{ display: 'flex', alignItems: 'flex-end', gap: 5, height: 70 }}>
                  {[0, 180, 340, 180, 580, 760, 440].map((v, i, a) => (
                    <div key={i} style={{ width: 9, height: Math.max(5, v / Math.max(...a) * 70), borderRadius: 4, background: i === a.length - 1 ? t.green : t.green + '55' }}/>
                  ))}
                </div>
              </div>
              <div style={{ marginTop: 20, paddingTop: 18, borderTop: `0.5px solid ${t.sep}`, display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 16 }}>
                {[
                  { l: 'Einnahmen · Mai', v: `+${fin.income.toLocaleString('de-DE')} €`, c: t.green },
                  { l: 'Ausgaben · Mai', v: `−${fin.expenses.toLocaleString('de-DE')} €`, c: t.red },
                  { l: 'Netto · Mai', v: `${fin.net >= 0 ? '+' : ''}${fin.net.toLocaleString('de-DE')} €`, c: t.text },
                ].map((x) => (
                  <div key={x.l}>
                    <div style={{ fontSize: 10, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.6 }}>{x.l}</div>
                    <div style={{ fontSize: 18, fontWeight: 700, color: x.c, marginTop: 4, ...NUMS }}>{x.v}</div>
                  </div>
                ))}
              </div>
            </div>

            {/* KPI tiles */}
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12 }}>
              {[
                { label: 'Aktive Mieten', value: active.length, sub: 'laufend', color: t.green, icon: icons.doc, to: 'rentals' },
                { label: 'Reserviert', value: reserved.length, sub: 'geplant', color: t.orange, icon: icons.clock, to: 'rentals' },
                { label: 'Unterwegs', value: liveUtilPct + '%', sub: `${vermietet} von ${totalStock} Geräten`, color: t.accent, icon: icons.truck, to: 'equipment' },
              ].map((s) => <StatTile key={s.label} {...s} onClick={() => go(s.to)}/>)}
            </div>

            {/* Equipment status */}
            <div style={{ ...card, padding: 20 }}>
              <SectionTitle action="Verwalten ›" onAction={() => go('equipment')}>Equipment-Status</SectionTitle>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12, marginBottom: 16 }}>
                {[['Verfügbar', verfuegbar, t.green], ['Vermietet', vermietet, t.accent], ['In Reparatur', equipment.reduce((s, e) => s + eqStock(e, rentals).reparatur, 0), t.orange]].map(([l, v, c]) => (
                  <div key={l} style={{ background: t.cardAlt, borderRadius: 12, padding: '12px 14px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 7, height: 7, borderRadius: 4, background: c }}/><span style={{ fontSize: 11, color: t.textSec, fontWeight: 600 }}>{l}</span></div>
                    <div style={{ fontSize: 24, fontWeight: 700, color: t.text, marginTop: 4, ...NUMS }}>{v}</div>
                  </div>
                ))}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                {[...equipment].map((e) => ({ e, u: eqUses(e, rentals), util: eqUtil(e, rentals, equipment) })).sort((a, b) => b.u - a.u || b.util - a.util).slice(0, 4).map(({ e, util }) => {
                  const st = eqStock(e, rentals);
                  return (
                    <Pressable key={e.id} onClick={() => go('equipment', { equipmentId: e.id })} scale={0.99} hoverBg={t.cardAlt} style={{ borderRadius: 10 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 10px' }}>
                        <EqAvatar item={e} size={36} radius={9}/>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text }}>{e.name}</div>
                          <div style={{ fontSize: 11.5, color: t.textSec }}>{e.cat} · {e.price} €/Tag</div>
                        </div>
                        <div style={{ width: 120, height: 6, borderRadius: 3, background: t.chipStrong, overflow: 'hidden' }}>
                          <div style={{ width: `${util}%`, height: '100%', borderRadius: 3, background: t.accent }}/>
                        </div>
                        <div style={{ fontSize: 12, fontWeight: 700, color: t.textSec, width: 36, textAlign: 'right', ...NUMS }}>{util}%</div>
                      </div>
                    </Pressable>
                  );
                })}
              </div>
              {equipment.length > 4 && (
                <Pressable onClick={() => setShowAllEq(true)} scale={0.99} hoverBg={t.cardAlt} style={{ borderRadius: 10, marginTop: 6 }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6, padding: '10px 12px', borderTop: `0.5px solid ${t.sep}` }}>
                    <span style={{ fontSize: 12.5, fontWeight: 600, color: t.accent }}>Alle {equipment.length} Geräte anzeigen</span>
                    <Icon d={icons.chev} color={t.accent} size={11} sw={2.4}/>
                  </div>
                </Pressable>
              )}
            </div>

            {/* Active rentals list */}
            <div style={{ ...card, padding: 20 }}>
              <SectionTitle action="Alle Mietvorgänge ›" onAction={() => go('rentals')}>Aktive & reservierte Mieten</SectionTitle>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                {[...active, ...reserved].map((r) => {
                  const eq = equipment.find((e) => e.id === r.equipmentId);
                  const dep = depositMeta(r.depositStatus);
                  return (
                    <Pressable key={r.id} onClick={() => go('rentals', { rentalId: r.id })} scale={0.99} hoverBg={t.cardAlt} style={{ borderRadius: 10 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '9px 10px' }}>
                        <EqAvatar item={eq || {}} size={42} radius={10}/>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{r.tenantName}</div>
                          <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 1 }}>{eq ? eq.name : r.equipmentName} · {fmtRange(r.start, r.end)}</div>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 4 }}><span style={{ width: 6, height: 6, borderRadius: 3, background: dep.color }}/><span style={{ fontSize: 10.5, color: dep.color, fontWeight: 600 }}>{dep.label}</span></div>
                        </div>
                        <div style={{ textAlign: 'right' }}>
                          <StatusPill status={r.status}/>
                          <div style={{ fontSize: 14, fontWeight: 700, color: t.text, marginTop: 6, ...NUMS }}>{rentalTotal(r)} €</div>
                        </div>
                      </div>
                    </Pressable>
                  );
                })}
              </div>
            </div>
          </div>

          {/* RIGHT column */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            {/* Benachrichtigungen — Aufgaben & anstehende Termine */}
            <div style={{ ...card, padding: 20 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14 }}>
                <div>
                  <div style={{ fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: -0.3 }}>Benachrichtigungen</div>
                  <div style={{ fontSize: 12, color: t.textSec, marginTop: 2 }}>Aufgaben & anstehende Termine</div>
                </div>
                {openCount > 0 && (
                  <div style={{ fontSize: 13, color: t.accent, fontWeight: 600 }}>{openCount} offen</div>
                )}
              </div>

              {/* Tab switcher */}
              <div style={{ display: 'flex', background: t.chip, borderRadius: 10, padding: 3, gap: 3, marginBottom: 14 }}>
                {[['todo', 'Zu erledigen', openCount], ['upcoming', 'Anstehend', upcomingCount]].map(([k, l, n]) => {
                  const sel = notifTab === k;
                  return (
                    <Pressable key={k} onClick={() => setNotifTab(k)} scale={0.97} style={{ flex: 1 }}>
                      <div style={{ padding: '8px 0', textAlign: 'center', borderRadius: 8, background: sel ? t.card : 'transparent', boxShadow: sel ? '0 1px 2px rgba(0,0,0,0.06)' : 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7 }}>
                        <span style={{ fontSize: 13, fontWeight: 600, color: sel ? t.text : t.textSec }}>{l}</span>
                        <span style={{ fontSize: 11, fontWeight: 700, color: sel ? t.textSec : t.textTer, background: sel ? t.chip : 'transparent', padding: sel ? '1px 7px' : '0', borderRadius: 100, minWidth: 18, textAlign: 'center', ...NUMS }}>{n}</span>
                      </div>
                    </Pressable>
                  );
                })}
              </div>

              {/* TAB: Zu erledigen */}
              {notifTab === 'todo' && (
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  {auto.length === 0 && items.length === 0 && !adding && <div style={{ padding: '18px 0', textAlign: 'center', color: t.textSec, fontSize: 13 }}>Alles erledigt ✓</div>}
                  {auto.map((a) => {
                    const done = !!autoDone[a.key];
                    return (
                      <div key={a.key} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 0', borderBottom: `0.5px solid ${t.sep}` }}>
                        <Bullet done={done} onClick={() => toggleAuto(a.key)}/>
                        <Pressable onClick={() => a.rentalId ? go('rentals', { rentalId: a.rentalId }) : null} scale={0.99} style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 13.5, fontWeight: 600, color: done ? t.textTer : t.text, textDecoration: done ? 'line-through' : 'none' }}>{a.icon} {a.text}</div>
                          <div style={{ fontSize: 11, color: t.textSec, marginTop: 1 }}>{a.sub}</div>
                        </Pressable>
                        <span style={{ fontSize: 9, color: t.textTer, fontWeight: 700, letterSpacing: 0.4 }}>AUTO</span>
                        <Pressable onClick={() => dismissAuto(a.key)} scale={0.8}><div title="Entfernen" style={{ width: 24, height: 24, borderRadius: 12, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon d="M6 6l12 12M18 6L6 18" color={t.textSec} size={11} sw={2.2}/></div></Pressable>
                      </div>
                    );
                  })}
                  {items.map((it, i) => (
                    <div key={it.id} style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 0', borderBottom: (i < items.length - 1 || adding) ? `0.5px solid ${t.sep}` : 'none' }}>
                      <Bullet done={it.done} onClick={() => toggleManual(it.id)}/>
                      <div style={{ flex: 1, fontSize: 13.5, fontWeight: 600, color: it.done ? t.textTer : t.text, textDecoration: it.done ? 'line-through' : 'none' }}>{it.text}</div>
                      <Pressable onClick={() => removeManual(it.id)} scale={0.8}><div style={{ width: 24, height: 24, borderRadius: 12, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon d="M6 6l12 12M18 6L6 18" color={t.textSec} size={11} sw={2.2}/></div></Pressable>
                    </div>
                  ))}
                  {adding ? (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 0' }}>
                      <div style={{ width: 22, height: 22, borderRadius: 11, border: `1.5px dashed ${t.textTer}` }}/>
                      <input autoFocus value={text} onChange={(e) => setText(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') addManual(); if (e.key === 'Escape') { setText(''); setAdding(false); } }} onBlur={addManual} placeholder="Neue Aufgabe…" style={{ flex: 1, border: 'none', outline: 'none', background: 'transparent', fontSize: 13.5, fontWeight: 600, color: t.text, fontFamily: 'inherit' }}/>
                    </div>
                  ) : (
                    <Pressable onClick={() => setAdding(true)} scale={0.99}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '11px 0 4px' }}>
                        <div style={{ width: 22, height: 22, borderRadius: 11, background: t.accentSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon d={icons.plus} color={t.accent} size={13} sw={2.6}/></div>
                        <div style={{ fontSize: 13.5, fontWeight: 600, color: t.accent }}>Aufgabe hinzufügen</div>
                      </div>
                    </Pressable>
                  )}
                </div>
              )}

              {/* TAB: Anstehend */}
              {notifTab === 'upcoming' && (
                <div>
                  <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
                    {[['today', 'Heute'], ['week', '7 Tage'], ['month', '30 Tage']].map(([k, l]) => {
                      const sel = upcRange === k;
                      return (
                        <Pressable key={k} onClick={() => setUpcRange(k)} scale={0.96} style={{ flex: 1 }}>
                          <div style={{ padding: '7px 0', textAlign: 'center', borderRadius: 100, background: sel ? t.accent : t.chip, color: sel ? '#fff' : t.text, fontSize: 12.5, fontWeight: 600 }}>{l}</div>
                        </Pressable>
                      );
                    })}
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                    {upcoming.length === 0 && <div style={{ padding: '20px 0', textAlign: 'center', color: t.textSec, fontSize: 13 }}>Keine Termine im Zeitraum.</div>}
                    {upcoming.map((ev, i) => {
                      const eq = equipment.find((e) => e.id === ev.equipmentId);
                      const isRental = !!ev.fromRental;
                      return (
                        <Pressable key={ev.id} onClick={() => isRental ? go('rentals', { rentalId: ev.rentalId }) : go('calendar')} scale={0.99} hoverBg={t.cardAlt} style={{ borderRadius: 10 }}>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '9px 8px', borderBottom: i < upcoming.length - 1 ? `0.5px solid ${t.sep}` : 'none' }}>
                            <div style={{ width: 42, height: 42, borderRadius: 11, background: isRental ? t.greenSoft : ev.color + '22', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                              {isRental ?
                                <Icon d={icons.doc} color={t.green} size={18} sw={2}/> :
                                <>
                                  <div style={{ fontSize: 8.5, color: ev.color, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.3 }}>{DE_MONTHS_SHORT[fromISO(ev.start).getMonth()]}</div>
                                  <div style={{ fontSize: 16, color: ev.color, fontWeight: 700, lineHeight: 1.05, ...NUMS }}>{fromISO(ev.start).getDate()}</div>
                                </>
                              }
                            </div>
                            <div style={{ flex: 1, minWidth: 0 }}>
                              <div style={{ fontSize: 13.5, fontWeight: 600, color: t.text, display: 'flex', alignItems: 'center', gap: 6 }}>{ev.title}{isRental && <span style={{ fontSize: 8, fontWeight: 700, color: t.green, background: t.greenSoft, padding: '1px 6px', borderRadius: 100 }}>MIETE</span>}</div>
                              <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 1 }}>{eq ? eq.name + ' · ' : ''}{fmtRange(ev.start, ev.end)}</div>
                              {isRental && (ev.startTime || ev.endTime) && (
                                <div style={{ fontSize: 11, color: t.text, marginTop: 3, display: 'flex', gap: 14, fontWeight: 600 }}>
                                  {ev.startTime && <span>↑ Abholung <span style={{ ...NUMS }}>{ev.startTime}</span></span>}
                                  {ev.endTime && <span>↓ Rückgabe <span style={{ ...NUMS }}>{ev.endTime}</span></span>}
                                </div>
                              )}
                            </div>
                            <Icon d={icons.chev} color={t.textTer} size={14} sw={2}/>
                          </div>
                        </Pressable>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>

            {/* Mini revenue chart */}
            <div style={{ ...card, padding: 20 }}>
              <SectionTitle action="Finanzen ›" onAction={() => go('finance')}>Umsatzverlauf</SectionTitle>
              <ChartBars bars={FIN_BARS}/>
              <div style={{ display: 'flex', gap: 16, marginTop: 14, justifyContent: 'center' }}>
                <Legend color={t.green} label="Einnahmen"/>
                <Legend color={t.red} label="Ausgaben"/>
              </div>
            </div>
          </div>
        </div>
      </Scroll>
      <AllEquipmentSheet open={showAllEq} onClose={() => setShowAllEq(false)} equipment={equipment} rentals={rentals} go={go} />
    </>
  );
}

function AllEquipmentSheet({ open, onClose, equipment, rentals, go }) {
  const t = useTheme();
  const [query, setQuery] = useState('');
  const [sortBy, setSortBy] = useState('util'); // util | name | stock
  useEffect(() => { if (!open) setQuery(''); }, [open]);

  const enriched = equipment.map((e) => ({ e, util: eqUtil(e, rentals, equipment), uses: eqUses(e, rentals), stock: eqStock(e, rentals) }));
  const filtered = enriched.filter(({ e }) => {
    if (!query.trim()) return true;
    const q = query.toLowerCase();
    return (e.name || '').toLowerCase().includes(q) || (e.cat || '').toLowerCase().includes(q) || (e.sub || '').toLowerCase().includes(q);
  });
  const sorted = [...filtered].sort((a, b) => {
    if (sortBy === 'name') return (a.e.name || '').localeCompare(b.e.name || '');
    if (sortBy === 'stock') return b.stock.verfuegbar - a.stock.verfuegbar;
    return b.uses - a.uses || b.util - a.util;
  });

  return (
    <Sheet open={open} onClose={onClose} width={620}>
      <div style={{ padding: '4px 26px 24px', display: 'flex', flexDirection: 'column', maxHeight: '78vh' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <div>
            <div style={{ fontSize: 21, fontWeight: 700, color: t.text, letterSpacing: -0.4 }}>Alle Geräte</div>
            <div style={{ fontSize: 12.5, color: t.textSec, marginTop: 3 }}>{equipment.length} Geräte im Bestand · {filtered.length} angezeigt</div>
          </div>
          <Pressable onClick={onClose}><div style={{ fontSize: 14, color: t.textSec, fontWeight: 500 }}>Schließen</div></Pressable>
        </div>

        <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
          <div style={{ flex: 1, position: 'relative' }}>
            <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Suchen…"
              style={{ width: '100%', padding: '9px 12px 9px 32px', borderRadius: 10, border: `1px solid ${t.inputBorder}`, background: t.inputBg, fontSize: 13.5, color: t.text, outline: 'none', fontFamily: 'inherit', boxSizing: 'border-box' }} />
            <div style={{ position: 'absolute', left: 10, top: '50%', transform: 'translateY(-50%)', display: 'flex' }}>
              <Icon d={icons.search} color={t.textTer} size={14} sw={2} />
            </div>
          </div>
          <Segmented size="sm" value={sortBy} onChange={setSortBy}
            options={[['util', 'Auslastung'], ['name', 'Name'], ['stock', 'Bestand']]} />
        </div>

        <div style={{ marginTop: 12, flex: 1, overflow: 'auto', borderTop: `0.5px solid ${t.sep}` }}>
          {sorted.length === 0 ? (
            <div style={{ padding: '40px 12px', textAlign: 'center', color: t.textSec, fontSize: 13 }}>Keine Treffer.</div>
          ) : sorted.map(({ e, util, stock }, i) => {
            const pillColor = stock.verfuegbar === 0 ? (t.red || '#FF3B30') : stock.verfuegbar < Math.max(1, Number(e.qty) || 1) ? (t.orange || '#FF9500') : (t.green || '#34C759');
            return (
              <Pressable key={e.id} onClick={() => { go('equipment', { equipmentId: e.id }); onClose(); }} scale={0.998} hoverBg={t.cardAlt}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 4px', borderBottom: i === sorted.length - 1 ? 'none' : `0.5px solid ${t.sep}` }}>
                  <EqAvatar item={e} size={38} radius={9} />
                  <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.5, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.cat}{e.sub ? ' · ' + e.sub : ''} · {e.price} €/Tag</div>
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 4, flexShrink: 0 }}>
                    <span style={{ fontSize: 10.5, fontWeight: 700, padding: '2px 8px', borderRadius: 100, background: pillColor + '22', color: pillColor, ...NUMS }}>
                      {stock.verfuegbar}/{stock.total} frei
                    </span>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <div style={{ width: 70, height: 5, borderRadius: 3, background: t.chipStrong, overflow: 'hidden' }}>
                        <div style={{ width: `${util}%`, height: '100%', borderRadius: 3, background: t.accent }}/>
                      </div>
                      <div style={{ fontSize: 11, fontWeight: 700, color: t.textSec, width: 28, textAlign: 'right', ...NUMS }}>{util}%</div>
                    </div>
                  </div>
                  <Icon d={icons.chev} color={t.textTer} size={12} sw={2.2} />
                </div>
              </Pressable>
            );
          })}
        </div>
      </div>
    </Sheet>
  );
}

function Legend({ color, label }) {
  const t = useTheme();
  return <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: t.textSec, fontWeight: 600 }}><span style={{ width: 9, height: 9, borderRadius: 5, background: color }}/>{label}</div>;
}

Object.assign(window, { ScreenDashboard, buildAutoTasks, Bullet, Legend });
