// Dashboard + Detail screens
const { useState, useEffect } = React;

// Sun / moon glyph for the dark-mode toggle
const ICON_SUN = 'M12 3v2M12 19v2M3 12h2M19 12h2M5.6 5.6l1.4 1.4M17 17l1.4 1.4M18.4 5.6L17 7M7 17l-1.4 1.4M12 8a4 4 0 100 8 4 4 0 000-8z';
const ICON_MOON = 'M21 12.8A8.5 8.5 0 1111.2 3 6.6 6.6 0 0021 12.8z';

// Auto-generated tasks from rentals + equipment maintenance
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 <= 3) {
      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}` });
    }
    const dEnd = daysBetween(today, r.end) - 1;
    if (r.status === 'aktiv' && dEnd >= -3 && dEnd <= 1) {
      out.push({ key: 'check:' + r.id, icon: '🔍', text: 'Equipment nach Rückgabe prüfen', sub: `${r.tenantName} · ${eqName}` });
    }
  });
  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;
}

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

}

// ─── Unified Notifications section — merges tasks + upcoming dates into ONE
// homogeneous, editable list (no leading colored bars). Two sub-tabs:
//   • Zu erledigen — actionable tasks (auto + manual)
//   • Anstehend — calendar events from today onwards
// Tasks support: add, mark done, remove, set reminder date.
// ─────────────────────────────────────────────────────────────
function NotificationsSection({ rentals, equipment, events = [], tasks, setTasks, toast, go }) {
  const t = useTheme();
  const [tab, setTab] = useState('todo');
  const [range, setRange] = useState('week'); // today | week | month
  const [adding, setAdding] = useState(false);
  const [text, setText] = useState('');
  const [editingId, setEditingId] = useState(null);

  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 dismissAuto = (key) => {
    setTasks((prev) => ({ ...prev, autoDismissed: { ...(prev.autoDismissed || {}), [key]: true } }));
    toast && toast('Benachrichtigung gelöscht');
  };
  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 updateManual = (id, patch) => setTasks((prev) => ({ ...prev, items: (prev.items || []).map((x) => x.id === id ? { ...x, ...patch } : x) }));
  const addManual = () => {
    const v = text.trim();
    if (!v) {setAdding(false);return;}
    setTasks((prev) => ({ ...prev, items: [{ id: 'task-' + Date.now(), text: v, done: false, reminder: '' }, ...(prev.items || [])] }));
    setText('');setAdding(false);
    toast && toast('Aufgabe hinzugefügt');
  };

  const openCount = auto.filter((a) => !autoDone[a.key]).length + items.filter((i) => !i.done).length;

  // upcoming events — merge manual events + rentals
  const today = todayISO();
  const rentalEventList = (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: r.color || statusMeta(r.status).color
  }));
  const upcoming = [...events, ...rentalEventList].
  filter((e) => e.end >= today).
  sort((a, b) => a.start.localeCompare(b.start));

  // Apply Heute / Woche / Monat range filter
  const horizonISO = (() => {
    const d = fromISO(today);
    if (range === 'today') return today;
    if (range === 'week') {d.setDate(d.getDate() + 7);return fmtDateISO(d);}
    /* month */{d.setMonth(d.getMonth() + 1);return fmtDateISO(d);}
  })();
  const filteredUpcoming = upcoming.filter((e) => e.start <= horizonISO).slice(0, 12);

  const Bullet = ({ done, onClick }) =>
  <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 ? t.accent : 'transparent',
      display: 'flex', alignItems: 'center', justifyContent: 'center'
    }}>
        {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>;


  return (
    <>
      <div style={{ padding: '24px 20px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div>
          <div style={{ fontSize: 18, fontWeight: 600, color: t.text, letterSpacing: -0.3 }}>Benachrichtigungen</div>
          <div style={{ fontSize: 11, color: t.textSec, marginTop: 1 }}>Aufgaben & anstehende Termine</div>
        </div>
        <div style={{ ...{ fontSize: 13, color: openCount ? t.accent : t.textSec, fontWeight: 600 }, color: "rgb(55, 114, 255)" }}>{openCount} offen</div>
      </div>
      <div style={{ padding: '0 16px 8px' }}>
        <div style={{ display: 'flex', padding: 3, borderRadius: 10, background: t.chipStrong }}>
          {[
          ['todo', 'Zu erledigen', auto.filter((a) => !autoDone[a.key]).length + items.filter((i) => !i.done).length],
          ['cal', 'Anstehend', filteredUpcoming.length]].
          map(([id, label, count]) =>
          <Pressable key={id} onClick={() => setTab(id)} scale={0.96} style={{ flex: 1 }}>
              <div style={{
              padding: '7px 0', textAlign: 'center', borderRadius: 8, fontSize: 12, fontWeight: 600,
              background: tab === id ? t.dark ? t.cardAlt : '#fff' : 'transparent',
              color: tab === id ? t.text : t.textSec,
              boxShadow: tab === id ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5
            }}>
                {label}
                {count > 0 && <span style={{ fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 100, background: tab === id ? t.chip : 'transparent', color: tab === id ? t.text : t.textTer }}>{count}</span>}
              </div>
            </Pressable>
          )}
        </div>
      </div>

      <div style={{ padding: '0 16px' }}>
        <div style={{ background: t.card, borderRadius: 18, overflow: 'hidden', boxShadow: t.shadowCard }}>
          {tab === 'todo' &&
          <>
              {auto.length === 0 && items.length === 0 && !adding &&
            <div style={{ padding: '22px 16px', textAlign: 'center', color: t.textSec, fontSize: 13 }}>Alles erledigt ✓</div>
            }
              {auto.map((a, i) => {
              const done = !!autoDone[a.key];
              return (
                <div key={a.key} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderBottom: `0.5px solid ${t.sep}` }}>
                    <Bullet done={done} onClick={() => toggleAuto(a.key)} />
                    <Pressable onClick={() => toggleAuto(a.key)} scale={0.99} style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: done ? t.textTer : t.text, textDecoration: done ? 'line-through' : 'none', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.text}</div>
                      <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.sub}</div>
                    </Pressable>
                    <span style={{ fontSize: 9, color: t.textTer, fontWeight: 700, letterSpacing: 0.4, textTransform: 'uppercase' }}>AUTO</span>
                    <Pressable onClick={() => dismissAuto(a.key)} scale={0.8}>
                      <div style={{ width: 26, height: 26, borderRadius: 13, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke={t.textSec} strokeWidth="2" strokeLinecap="round"><path d="M3 3l6 6M9 3l-6 6" /></svg>
                      </div>
                    </Pressable>
                  </div>);

            })}
              {items.map((it, i) => {
              const isEditing = editingId === it.id;
              return (
                <div key={it.id} style={{ borderBottom: i < items.length - 1 || adding ? `0.5px solid ${t.sep}` : 'none' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px' }}>
                      <Bullet done={it.done} onClick={() => toggleManual(it.id)} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        {isEditing ?
                      <>
                            <input autoFocus value={it.text}
                        onChange={(e) => updateManual(it.id, { text: e.target.value })}
                        onKeyDown={(e) => {if (e.key === 'Enter' || e.key === 'Escape') setEditingId(null);}}
                        placeholder="Titel"
                        style={{ width: '100%', border: 'none', outline: 'none', background: 'transparent', fontSize: 14, fontWeight: 600, color: t.text, fontFamily: 'inherit' }} />
                            <input value={it.sub || ''}
                        onChange={(e) => updateManual(it.id, { sub: e.target.value })}
                        onBlur={() => setEditingId(null)}
                        onKeyDown={(e) => {if (e.key === 'Enter' || e.key === 'Escape') setEditingId(null);}}
                        placeholder="Notiz · optional"
                        style={{ width: '100%', border: 'none', outline: 'none', background: 'transparent', fontSize: 11, color: t.textSec, fontFamily: 'inherit', marginTop: 1 }} />
                          </> :

                      <Pressable onClick={() => setEditingId(it.id)} scale={0.99}>
                            <div style={{ fontSize: 14, fontWeight: 600, color: it.done ? t.textTer : t.text, textDecoration: it.done ? 'line-through' : 'none', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.text}</div>
                            {it.sub &&
                        <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.sub}</div>
                        }
                          </Pressable>
                      }
                      </div>
                      <Pressable onClick={() => removeManual(it.id)} scale={0.8}>
                        <div style={{ width: 26, height: 26, borderRadius: 13, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke={t.textSec} strokeWidth="2" strokeLinecap="round"><path d="M3 3l6 6M9 3l-6 6" /></svg>
                        </div>
                      </Pressable>
                    </div>
                  </div>);

            })}
              {adding ?
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px' }}>
                  <div style={{ width: 22, height: 22, borderRadius: 11, border: `1.5px dashed ${t.textTer}`, flexShrink: 0 }} />
                  <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: 14, fontWeight: 600, color: t.text, fontFamily: 'inherit' }} />
                </div> :

            <Pressable onClick={() => setAdding(true)} scale={0.99}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px' }}>
                    <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: 14, fontWeight: 600, color: t.accent }}>Aufgabe hinzufügen</div>
                  </div>
                </Pressable>
            }
            </>
          }

          {tab === 'cal' &&
          <>
              {/* Heute / Woche / Monat filter */}
              <div style={{ padding: '10px 12px 4px', display: 'flex', gap: 4 }}>
                {[['today', 'Heute'], ['week', '7 Tage'], ['month', '30 Tage']].map(([id, label]) =>
              <Pressable key={id} onClick={() => setRange(id)} scale={0.95} style={{ flex: 1 }}>
                    <div style={{
                  padding: '7px 0', textAlign: 'center', borderRadius: 100,
                  background: range === id ? t.accent : t.chip,
                  color: range === id ? '#fff' : t.text,
                  fontSize: 11.5, fontWeight: 600
                }}>{label}</div>
                  </Pressable>
              )}
              </div>
              {filteredUpcoming.length === 0 &&
            <div style={{ padding: '22px 16px', textAlign: 'center', color: t.textSec, fontSize: 13 }}>
                  Keine Termine in diesem Zeitraum.
                </div>
            }
              {filteredUpcoming.map((ev, i) => {
              const eq = equipment.find((e) => e.id === ev.equipmentId);
              const isRental = !!ev.fromRental;
              const isMultiDay = ev.start !== ev.end;
              return (
                <Pressable key={ev.id} onClick={() => isRental ? go('doc', { rentalId: ev.rentalId, origin: 'cal' }) : go('cal')} scale={0.99}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', borderBottom: i < filteredUpcoming.length - 1 ? `0.5px solid ${t.sep}` : 'none' }}>
                      {/* Icon — different for rentals vs general events */}
                      {isRental ?
                    <div style={{
                      width: 38, height: 38, borderRadius: 10, background: ev.color + '22', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0
                    }}>
                          <Icon d={icons.doc} color={ev.color} size={18} sw={1.9} />
                        </div> :

                    <div style={{
                      width: 38, height: 38, borderRadius: 10, background: ev.color + '22', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flexShrink: 0
                    }}>
                          <div style={{ fontSize: 8, color: ev.color, fontWeight: 700, lineHeight: 1, textTransform: 'uppercase', letterSpacing: 0.3 }}>{DE_MONTHS_SHORT[fromISO(ev.start).getMonth()]}</div>
                          <div style={{ fontSize: 15, color: ev.color, fontWeight: 700, lineHeight: 1.1 }}>{fromISO(ev.start).getDate()}</div>
                        </div>
                    }
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 14, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', display: 'flex', alignItems: 'center', gap: 5 }}>
                          {ev.title}
                          {isRental && <span style={{ fontSize: 8, fontWeight: 700, color: ev.color, background: ev.color + '22', padding: '1px 5px', borderRadius: 100, letterSpacing: 0.3 }}>MIETE</span>}
                        </div>
                        <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                          {eq ? eq.name + ' · ' : ''}{fmtRange(ev.start, ev.end)}
                        </div>
                        {isRental && (ev.startTime || ev.endTime) &&
                      <div style={{ fontSize: 11, color: t.text, fontWeight: 600, marginTop: 3, display: 'flex', alignItems: 'center', gap: 8, fontVariantNumeric: 'tabular-nums' }}>
                            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}>↑ Abholung <b>{ev.startTime || '–'}</b></span>
                            <span style={{ color: t.textTer }}>·</span>
                            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 3 }}>↓ Rückgabe <b>{ev.endTime || '–'}</b></span>
                          </div>
                      }
                      </div>
                      <Icon d={icons.chev} color={t.textTer} size={14} sw={2} />
                    </div>
                  </Pressable>);

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

}

// ── To-do list (auto + manual, checkable) ──────────────────
function TodoSection({ rentals, equipment, tasks, setTasks, toast }) {
  const t = useTheme();
  const [adding, setAdding] = useState(false);
  const [text, setText] = useState('');
  const items = tasks && tasks.items || [];
  const autoDone = tasks && tasks.autoDone || {};
  const auto = buildAutoTasks(rentals, equipment);

  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 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;

  const Row = ({ icon, title, sub, done, onToggle, onDelete, accentColor }) =>
  <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px' }}>
      <Pressable onClick={onToggle} scale={0.85}><Check done={done} color={accentColor} /></Pressable>
      <Pressable onClick={onToggle} scale={0.99} style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          {icon && <span style={{ fontSize: 15, opacity: done ? 0.5 : 1 }}>{icon}</span>}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: done ? t.textTer : t.text, textDecoration: done ? 'line-through' : 'none', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{title}</div>
            {sub && <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, textDecoration: done ? 'line-through' : 'none', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</div>}
          </div>
        </div>
      </Pressable>
      {onDelete &&
    <Pressable onClick={onDelete} scale={0.8}>
          <div style={{ width: 26, height: 26, borderRadius: 13, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke={t.textSec} strokeWidth="2" strokeLinecap="round"><path d="M3 3l6 6M9 3l-6 6" /></svg>
          </div>
        </Pressable>
    }
    </div>;


  return (
    <>
      <div style={{ padding: '24px 20px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div style={{ fontSize: 18, fontWeight: 600, color: t.text, letterSpacing: -0.3 }}>Zu erledigen</div>
        <div style={{ fontSize: 13, color: openCount ? t.accent : t.textSec, fontWeight: 600 }}>{openCount} offen</div>
      </div>
      <div style={{ padding: '0 16px' }}>
        <div style={{ background: t.card, borderRadius: 18, overflow: 'hidden', boxShadow: t.shadowCard }}>
          {auto.length === 0 && items.length === 0 && !adding &&
          <div style={{ padding: '22px 16px', textAlign: 'center', color: t.textSec, fontSize: 13 }}>Alles erledigt 🎉</div>
          }
          {auto.map((a, i) =>
          <div key={a.key} style={{ borderBottom: `0.5px solid ${t.sep}` }}>
              <Row icon={a.icon} title={a.text} sub={a.sub} done={!!autoDone[a.key]} onToggle={() => toggleAuto(a.key)} />
            </div>
          )}
          {items.map((it, i) =>
          <div key={it.id} style={{ borderBottom: i < items.length - 1 || adding ? `0.5px solid ${t.sep}` : 'none' }}>
              <Row title={it.text} done={it.done} onToggle={() => toggleManual(it.id)} onDelete={() => removeManual(it.id)} />
            </div>
          )}

          {/* Add manual task */}
          {adding ?
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '12px 14px' }}>
              <div style={{ width: 24, height: 24, borderRadius: 12, border: `2px dashed ${t.textTer}`, flexShrink: 0 }} />
              <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: 14, fontWeight: 600, color: t.text, fontFamily: 'inherit' }} />
            </div> :

          <Pressable onClick={() => setAdding(true)} scale={0.99}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px' }}>
                <div style={{ width: 24, height: 24, borderRadius: 12, background: t.accentSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <Icon d={icons.plus} color={t.accent} size={15} sw={2.6} />
                </div>
                <div style={{ fontSize: 14, fontWeight: 600, color: t.accent }}>Aufgabe hinzufügen</div>
              </div>
            </Pressable>
          }
        </div>
      </div>
    </>);

}

// ── Reminder banner (push-style) ────────────────────────────
function ReminderBanner({ rentals, equipment, go }) {
  const t = useTheme();
  const reminders = buildReminders(rentals, equipment);
  if (reminders.length === 0) return null;
  const tone = (u) => u === 'over' ? t.red : u === 'today' ? t.orange : u === 'soon' ? t.accent : t.textSec;
  return (
    <div style={{ padding: '16px 16px 0' }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {reminders.slice(0, 3).map((r) => {
          const c = tone(r.urgency);
          return (
            <Pressable key={r.id} onClick={() => go(r.id.startsWith('tuev') || r.id.startsWith('def') ? 'eq' : 'doc')} scale={0.98}>
              <div style={{
                background: t.card, borderRadius: 14, padding: '12px 14px',
                display: 'flex', alignItems: 'center', gap: 12,
                boxShadow: t.shadowCard, borderLeft: `3px solid ${c}`
              }}>
                <div style={{ width: 34, height: 34, borderRadius: 17, background: c + '20', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 17, flexShrink: 0 }}>{r.icon}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: t.text }}>{r.title}</div>
                  <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.sub}</div>
                </div>
                <Icon d={icons.chev} color={t.textTer} size={14} sw={2} />
              </div>
            </Pressable>);

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

}

// ─────────────────────────────────────────────────────────────
// SCREEN: Dashboard (Home) — Kontostand · aktive Mieten · Notifications
// Sections are reorderable + hideable via the "Sortieren" button.
// ─────────────────────────────────────────────────────────────
const DEFAULT_SECTIONS = ['notifications', 'stats', 'rentals', 'equipment'];

function ScreenDashboard({ go, equipment, categories, rentals = [], events = [], tasks, setTasks, transactions = [], installedAt, dark, toggleDark, onSearch, toast }) {
  const t = useTheme();

  const active = rentals.filter((r) => r.status === 'aktiv');

  // Money figures — read from the same source as Finanzen so they stay in sync.
  const totalAgg = fin_sumAgg(transactions);
  const CURRENT_BALANCE = totalAgg.profit;
  const curMonthKey = fin_monthKeyOf(new Date());
  const monthAgg = fin_sumAgg(fin_txInMonth(transactions, curMonthKey));
  const monthIncome = monthAgg.income;

  // Mini-Bars: one per active month
  const monthBars = fin_monthlyIncomeBars(transactions, installedAt, 12);
  const sparkMax = Math.max(...monthBars.map(b => b.income)) || 1;

  // Avg utilization across equipment (replaces the heavy utilization card on Equipment)
  const avgUtil = equipment.length ? Math.round(equipment.reduce((s, e) => s + (Number(e.util) || 0), 0) / equipment.length) : 0;

  // ── Section ordering + visibility (persisted) ──
  const [secState, setSecState] = useState(() => {
    try {
      const raw = localStorage.getItem('rf-home-sections');
      const s = raw ? JSON.parse(raw) : null;
      if (s && Array.isArray(s.order)) return { order: s.order, hidden: s.hidden || [] };
    } catch {}
    return { order: DEFAULT_SECTIONS, hidden: [] };
  });
  useEffect(() => {
    try {localStorage.setItem('rf-home-sections', JSON.stringify(secState));} catch {}
  }, [secState]);
  const [reorderOpen, setReorderOpen] = useState(false);

  const SECTION_META = {
    notifications: { label: 'Benachrichtigungen', sub: 'Aufgaben + anstehende Termine' },
    stats: { label: 'Kennzahlen', sub: 'Aktive Mieten + Auslastung' },
    rentals: { label: 'Aktive Mieten', sub: 'Kompakte Liste' },
    equipment: { label: 'Equipment Tipps', sub: 'Verfügbar / vermietet' }
  };
  const visible = secState.order.filter((id) => !secState.hidden.includes(id));

  const moveSection = (id, dir) => {
    setSecState((prev) => {
      const order = [...prev.order];
      const i = order.indexOf(id);
      const j = i + dir;
      if (i < 0 || j < 0 || j >= order.length) return prev;
      [order[i], order[j]] = [order[j], order[i]];
      return { ...prev, order };
    });
  };
  const toggleSection = (id) => {
    setSecState((prev) => ({
      ...prev,
      hidden: prev.hidden.includes(id) ? prev.hidden.filter((x) => x !== id) : [...prev.hidden, id]
    }));
  };

  return (
    <div style={{ paddingBottom: 100 }}>
      <div style={{ padding: '8px 20px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <div style={{ fontSize: 13, color: t.textSec, fontWeight: 500 }}>{(() => {
            const d = new Date();
            return `${DE_DAYS[d.getDay()]}, ${d.getDate()}. ${DE_MONTHS[d.getMonth()]}`;
          })()}</div>
          <div style={{ fontSize: 32, fontWeight: 700, color: t.text, letterSpacing: -0.8, marginTop: 2 }}>Übersicht</div>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
          <Pressable onClick={onSearch} scale={0.88}>
            <div style={{ width: 38, height: 38, borderRadius: 19, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon d={icons.search} color={t.text} size={19} sw={2} />
            </div>
          </Pressable>
          <Pressable onClick={() => setReorderOpen(true)} scale={0.88}>
            <div style={{ width: 38, height: 38, borderRadius: 19, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon d="M3 5h18M3 12h18M3 19h18" color={t.text} size={17} sw={2} />
            </div>
          </Pressable>
          <CompanyGear size={38} />
        </div>
      </div>

      {/* Hero — Kontostand + Einnahmen (replaces Umsatz hero) */}
      <div style={{ padding: '16px 16px 0' }}>
        <Pressable onClick={() => go('eur')} scale={0.99}>
          <div style={{ background: t.card, borderRadius: 22, padding: '20px 22px', boxShadow: t.shadowCard }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div>
                <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 1.0 }}>Kontostand</div>
                <div style={{ fontSize: 38, fontWeight: 600, color: t.text, letterSpacing: -1.3, marginTop: 4, fontVariantNumeric: 'tabular-nums' }}>
                  {CURRENT_BALANCE.toLocaleString('de-DE')} <span style={{ fontSize: 22, color: t.textSec, fontWeight: 500 }}>€</span>
                </div>
                <div style={{ fontSize: 11, color: t.textSec, marginTop: 4 }}>
                  Verfügbares Guthaben
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, height: 52 }}>
                {monthBars.map((b, i) =>
                <div key={b.key} title={`${b.short}: ${b.income} €`} style={{
                  width: monthBars.length === 1 ? 14 : 7,
                  height: Math.max(4, b.income / sparkMax * 52), borderRadius: 3,
                  background: i === monthBars.length - 1 ? t.green : t.green + '55'
                }} />
                )}
              </div>
            </div>
            <div style={{ marginTop: 16, paddingTop: 14, borderTop: `0.5px solid ${t.sep}`, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <div>
                <div style={{ fontSize: 10, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.8 }}>Einnahmen · {fin_fmtMonthLabel(curMonthKey)}</div>
                <div style={{ fontSize: 18, fontWeight: 600, color: t.text, marginTop: 3, fontVariantNumeric: 'tabular-nums' }}>
                  +{monthIncome.toLocaleString('de-DE')} <span style={{ fontSize: 13, color: t.textSec }}>€</span>
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 11, color: t.textSec, fontWeight: 600 }}>
                {monthAgg.expenses > 0
                  ? <><Icon d="M9 5l7 7-7 7" color={t.textSec} size={10} sw={2.4} /> −{monthAgg.expenses.toLocaleString('de-DE')} € Ausgaben</>
                  : <span>Keine Ausgaben</span>}
              </div>
            </div>
          </div>
        </Pressable>
      </div>

      {/* Quick action — Neuer Mietvorgang */}
      <div style={{ padding: '10px 16px 0' }}>
        <Pressable onClick={() => go('doc', { newRental: true })} scale={0.98}>
          <div style={{
            background: t.solidBg, color: t.solidFg, borderRadius: 16, padding: '14px 18px',
            display: 'flex', alignItems: 'center', gap: 12, boxShadow: '0 6px 16px rgba(0,0,0,0.22)'
          }}>
            <div style={{ width: 30, height: 30, borderRadius: 10, background: 'rgba(255,255,255,0.18)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: "rgb(255, 255, 255)" }}>
              <Icon d={icons.plus} color={t.solidFg} size={18} sw={2.6} />
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 15, fontWeight: 700 }}>Neuer Mietvorgang</div>
              <div style={{ fontSize: 11, opacity: 0.85, marginTop: 1 }}>Direkt einen Mieter anlegen</div>
            </div>
            <Icon d={icons.chev} color={t.solidFg} size={15} sw={2.4} />
          </div>
        </Pressable>
      </div>

      {/* Sections in user-selected order */}
      {visible.map((id) => {
        if (id === 'notifications') {
          return <NotificationsSection key={id} rentals={rentals} equipment={equipment} events={events} tasks={tasks} setTasks={setTasks} toast={toast} go={go} />;
        }
        if (id === 'stats') {
          return (
            <div key={id} style={{ padding: '20px 16px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              <Pressable onClick={() => go('doc')} scale={0.97}>
                <div style={{ background: t.card, borderRadius: 16, padding: '14px 14px', boxShadow: t.shadowCard }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div style={{ width: 6, height: 6, borderRadius: 3, background: t.green }} />
                    <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.6 }}>Aktive Mieten</div>
                  </div>
                  <div style={{ fontSize: 28, fontWeight: 700, color: t.text, letterSpacing: -0.6, marginTop: 4, fontVariantNumeric: 'tabular-nums' }}>{active.length}</div>
                  <div style={{ fontSize: 11, color: t.textSec, marginTop: 1 }}>laufend</div>
                </div>
              </Pressable>
              <Pressable onClick={() => go('eq')} scale={0.97}>
                <div style={{ background: t.card, borderRadius: 16, padding: '14px 14px', boxShadow: t.shadowCard }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    <div style={{ width: 6, height: 6, borderRadius: 3, background: t.accent }} />
                    <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.6 }}>Auslastung</div>
                  </div>
                  <div style={{ fontSize: 28, fontWeight: 700, color: t.text, letterSpacing: -0.6, marginTop: 4, fontVariantNumeric: 'tabular-nums' }}>{avgUtil}%</div>
                  <div style={{ fontSize: 11, color: t.textSec, marginTop: 1 }}>Ø {equipment.length} Geräte</div>
                </div>
              </Pressable>
            </div>);

        }
        if (id === 'rentals') {
          return (
            <React.Fragment key={id}>
              <div style={{ padding: '24px 20px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div style={{ fontSize: 18, fontWeight: 600, color: t.text, letterSpacing: -0.3 }}>Aktive Mieten</div>
                <Pressable onClick={() => go('doc')} scale={0.96}>
                  <div style={{ fontSize: 14, color: t.accent, fontWeight: 500 }}>Alle ›</div>
                </Pressable>
              </div>
              <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 6 }}>
                {active.length === 0 &&
                <div style={{ textAlign: 'center', padding: '24px 20px', color: t.textSec, fontSize: 13, background: t.card, borderRadius: 14, border: '1px dashed ' + t.sep }}>
                    Keine laufenden Mieten.
                  </div>
                }
                {active.map((r) => {
                  const eq = equipment.find((e) => e.id === r.equipmentId);
                  return (
                    <Pressable key={r.id} onClick={() => go('doc', { rentalId: r.id })} scale={0.98}>
                      <div style={{ background: t.card, borderRadius: 14, padding: '11px 14px', display: 'flex', gap: 12, alignItems: 'center', boxShadow: t.shadowCard }}>
                        <EqAvatar item={eq || {}} size={38} radius={9} />
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 14, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.tenantName}</div>
                          <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{eq ? eq.name : r.equipmentName} · bis {fmtDateDE(r.end).slice(0, -5)}</div>
                        </div>
                        <div style={{ fontSize: 13, fontWeight: 700, color: t.text, fontVariantNumeric: 'tabular-nums' }}>{rentalTotal(r)} €</div>
                      </div>
                    </Pressable>);
                })}
              </div>
            </React.Fragment>);

        }
        if (id === 'equipment') {
          const verfuegbar = equipment.reduce((s, e) => s + eqStock(e, rentals).verfuegbar, 0);
          const vermietet = equipment.reduce((s, e) => s + eqStock(e, rentals).vermietet, 0);
          return (
            <React.Fragment key={id}>
              <div style={{ padding: '24px 20px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
                <div style={{ fontSize: 18, fontWeight: 600, color: t.text, letterSpacing: -0.3 }}>Equipment</div>
                <Pressable onClick={() => go('eq')} scale={0.96}>
                  <div style={{ fontSize: 14, color: t.accent, fontWeight: 500 }}>Alle ›</div>
                </Pressable>
              </div>
              <div style={{ padding: '0 16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                <div style={{ background: t.card, borderRadius: 14, padding: '12px 14px', boxShadow: t.shadowCard }}>
                  <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.6 }}>Verfügbar</div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: t.text, marginTop: 3, fontVariantNumeric: 'tabular-nums' }}>{verfuegbar}</div>
                </div>
                <div style={{ background: t.card, borderRadius: 14, padding: '12px 14px', boxShadow: t.shadowCard }}>
                  <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.6 }}>Vermietet</div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: t.text, marginTop: 3, fontVariantNumeric: 'tabular-nums' }}>{vermietet}</div>
                </div>
              </div>
            </React.Fragment>);

        }
        return null;
      })}

      {/* Reorder / hide sections sheet */}
      <Sheet open={reorderOpen} onClose={() => setReorderOpen(false)}>
        <div style={{ padding: '4px 24px 24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div>
              <div style={{ fontSize: 22, fontWeight: 700, color: t.text, letterSpacing: -0.5 }}>Bereiche anpassen</div>
              <div style={{ fontSize: 13, color: t.textSec, marginTop: 4 }}>Reihenfolge ändern oder ausblenden</div>
            </div>
            <Pressable onClick={() => setReorderOpen(false)}><div style={{ fontSize: 14, color: t.textSec, fontWeight: 500 }}>Fertig</div></Pressable>
          </div>
          <div style={{ marginTop: 18, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {secState.order.map((id, i) => {
              const meta = SECTION_META[id] || { label: id };
              const hidden = secState.hidden.includes(id);
              return (
                <div key={id} style={{ background: t.card, borderRadius: 14, padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10, opacity: hidden ? 0.55 : 1 }}>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                    <Pressable onClick={() => moveSection(id, -1)} scale={0.8} disabled={i === 0}>
                      <div style={{ width: 26, height: 22, borderRadius: 7, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: i === 0 ? 0.4 : 1 }}>
                        <Icon d="M5 15l7-7 7 7" color={t.text} size={12} sw={2.4} />
                      </div>
                    </Pressable>
                    <Pressable onClick={() => moveSection(id, 1)} scale={0.8} disabled={i === secState.order.length - 1}>
                      <div style={{ width: 26, height: 22, borderRadius: 7, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: i === secState.order.length - 1 ? 0.4 : 1 }}>
                        <Icon d="M5 9l7 7 7-7" color={t.text} size={12} sw={2.4} />
                      </div>
                    </Pressable>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{meta.label}</div>
                    {meta.sub && <div style={{ fontSize: 11, color: t.textSec, marginTop: 1 }}>{meta.sub}</div>}
                  </div>
                  <Pressable onClick={() => toggleSection(id)} scale={0.9}>
                    <div style={{
                      padding: '7px 12px', borderRadius: 10, fontSize: 12, fontWeight: 600,
                      background: hidden ? t.chip : t.accentSoft, color: hidden ? t.textSec : t.accent
                    }}>{hidden ? 'Einblenden' : 'Ausblenden'}</div>
                  </Pressable>
                </div>);

            })}
          </div>
          <Pressable onClick={() => setSecState({ order: DEFAULT_SECTIONS, hidden: [] })} scale={0.97} style={{ marginTop: 18 }}>
            <div style={{
              padding: '13px 0', textAlign: 'center', borderRadius: 12,
              background: t.chip, color: t.text, fontSize: 13, fontWeight: 600
            }}>Standardreihenfolge wiederherstellen</div>
          </Pressable>
        </div>
      </Sheet>
    </div>);

}

// ─────────────────────────────────────────────────────────────
// Legacy ScreenDashboard kept for reference (renamed)
// ─────────────────────────────────────────────────────────────
function ScreenDashboardLegacy({ go, equipment, categories, rentals = [], events = [], tasks, setTasks, dark, toggleDark, onSearch, toast }) {
  const t = useTheme();

  const totalOf = (r) => rentalTotal(r);
  const active = rentals.filter((r) => r.status === 'aktiv');
  const reserved = rentals.filter((r) => r.status === 'reserviert');
  const liveRentals = [...active, ...reserved];

  // Revenue (consistent with Finanzen)
  const revenue = 0,revenuePrev = 0;
  const revPct = Math.round((revenue - revenuePrev) / revenuePrev * 100);

  // Mini sparkline — last days of the month
  const spark = [0, 180, 340, 180, 580, 760, 440];
  const sparkMax = Math.max(...spark);

  // Deposits currently held (status 'erhalten')
  const depositsHeld = rentals.filter((r) => r.depositStatus === 'erhalten').reduce((s, r) => s + (Number(r.deposit) || 0), 0);

  // Upcoming returns/pickups from events
  const upcoming = events.
  filter((e) => e.end >= todayISO()).
  sort((a, b) => a.start.localeCompare(b.start)).
  slice(0, 3);

  return (
    <div style={{ paddingBottom: 100 }}>
      <div style={{ padding: '8px 20px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div>
          <div style={{ fontSize: 13, color: t.textSec, fontWeight: 500 }}>Mittwoch, 20. Mai</div>
          <div style={{ fontSize: 32, fontWeight: 700, color: t.text, letterSpacing: -0.8, marginTop: 2 }}>Übersicht</div>
        </div>
        <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
          <Pressable onClick={onSearch} scale={0.88}>
            <div style={{ width: 38, height: 38, borderRadius: 19, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon d={icons.search} color={t.text} size={19} sw={2} />
            </div>
          </Pressable>
          <CompanyGear size={38} />
        </div>
      </div>

      {/* Reminders */}
      <ReminderBanner rentals={rentals} equipment={equipment} go={go} />

      {/* Revenue hero */}
      <div style={{ padding: '16px 16px 0' }}>
        <Pressable onClick={() => go('eur')} scale={0.99}>
          <div style={{ background: t.card, borderRadius: 22, padding: '20px 22px', boxShadow: t.shadowCard }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
              <div>
                <div style={{ fontSize: 12, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.6 }}>Umsatz · Mai 2026</div>
                <div style={{ fontSize: 40, fontWeight: 700, color: t.text, letterSpacing: -1.4, marginTop: 4 }}>{revenue.toLocaleString('de-DE')} €</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 2 }}>
                  <Icon d={revPct >= 0 ? 'M5 15l7-7 7 7' : 'M5 9l7 7 7-7'} size={12} sw={2.8} color={revPct >= 0 ? t.green : t.red} />
                  <span style={{ fontSize: 12, color: revPct >= 0 ? t.green : t.red, fontWeight: 600 }}>{Math.abs(revPct)}% vs. Vorjahr</span>
                </div>
              </div>
              <div style={{ display: 'flex', alignItems: 'flex-end', gap: 3, height: 52 }}>
                {spark.map((v, i) =>
                <div key={i} style={{
                  width: 7, height: Math.max(4, v / sparkMax * 52), borderRadius: 3,
                  background: i === spark.length - 1 ? t.accent : t.accentSoft
                }} />
                )}
              </div>
            </div>
          </div>
        </Pressable>
      </div>

      {/* Stat row */}
      <div style={{ padding: '10px 16px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        {[
        { label: 'Aktiv', val: active.length, color: t.green, to: 'doc' },
        { label: 'Reserviert', val: reserved.length, color: t.orange, to: 'doc' }].
        map((s) =>
        <Pressable key={s.label} onClick={() => go(s.to)} scale={0.97}>
            <div style={{ background: t.card, borderRadius: 16, padding: '12px 12px', boxShadow: t.shadowCard }}>
              <div style={{ fontSize: 11, color: t.textSec, fontWeight: 500 }}>{s.label}</div>
              <div style={{ fontSize: 24, fontWeight: 700, color: s.color, letterSpacing: -0.4, marginTop: 4 }}>{s.val}</div>
            </div>
          </Pressable>
        )}
      </div>

      {/* To-do list */}
      <TodoSection rentals={rentals} equipment={equipment} tasks={tasks} setTasks={setTasks} toast={toast} />

      {/* Active rentals */}
      <div style={{ padding: '24px 20px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div style={{ fontSize: 18, fontWeight: 600, color: t.text, letterSpacing: -0.3 }}>Aktive Mieten</div>
        <Pressable onClick={() => go('doc')} scale={0.96}>
          <div style={{ fontSize: 14, color: t.accent, fontWeight: 500 }}>Alle ›</div>
        </Pressable>
      </div>

      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {liveRentals.length === 0 &&
        <Pressable onClick={() => go('doc')}>
            <div style={{ textAlign: 'center', padding: '30px 20px', color: t.textSec, fontSize: 13, background: t.card, borderRadius: 16, border: '1px dashed ' + t.sep }}>
              Keine laufenden Mieten.<br />
              <span style={{ color: t.accent, fontWeight: 600 }}>+ Mieter anlegen</span>
            </div>
          </Pressable>
        }
        {liveRentals.map((r) => {
          const m = statusMeta(r.status);
          const dep = depositMeta(r.depositStatus);
          const eq = equipment.find((e) => e.id === r.equipmentId);
          return (
            <Pressable key={r.id} onClick={() => go('doc', { rentalId: r.id })} scale={0.98}>
              <div style={{ background: t.card, borderRadius: 16, padding: 12, display: 'flex', gap: 12, alignItems: 'center', boxShadow: t.shadowCard }}>
                <EqAvatar item={eq || {}} size={48} radius={11} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 15, fontWeight: 600, color: t.text, letterSpacing: -0.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.tenantName}</div>
                  <div style={{ fontSize: 12, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{eq ? eq.name : r.equipmentName} · {fmtRange(r.start, r.end)}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 4 }}>
                    <div style={{ width: 6, height: 6, borderRadius: 3, background: dep.color }} />
                    <span style={{ fontSize: 10, color: dep.color, fontWeight: 600 }}>{dep.label}</span>
                  </div>
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  <div style={{ fontSize: 9, fontWeight: 700, padding: '3px 7px', borderRadius: 100, background: m.color + '22', color: m.color, letterSpacing: 0.4 }}>● {m.label}</div>
                  <div style={{ fontSize: 13, fontWeight: 700, color: t.text, marginTop: 4 }}>{rentalTotal(r)} €</div>
                </div>
              </div>
            </Pressable>);

        })}
      </div>

      {/* Upcoming dates */}
      {upcoming.length > 0 &&
      <>
          <div style={{ padding: '24px 20px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontSize: 18, fontWeight: 600, color: t.text, letterSpacing: -0.3 }}>Anstehende Termine</div>
            <Pressable onClick={() => go('cal')} scale={0.96}>
              <div style={{ fontSize: 14, color: t.accent, fontWeight: 500 }}>Kalender ›</div>
            </Pressable>
          </div>
          <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 6 }}>
            {upcoming.map((ev) => {
            const eq = equipment.find((e) => e.id === ev.equipmentId);
            return (
              <Pressable key={ev.id} onClick={() => go('cal')} scale={0.98}>
                  <div style={{ background: t.card, borderRadius: 14, padding: '12px 14px', display: 'flex', gap: 12, alignItems: 'center', boxShadow: t.shadowCard }}>
                    <div style={{ width: 6, height: 34, background: ev.color, borderRadius: 3 }} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{ev.title}</div>
                      <div style={{ fontSize: 11, color: t.textSec, marginTop: 1 }}>{eq ? eq.name : '—'} · {fmtRange(ev.start, ev.end)}</div>
                    </div>
                    <Icon d={icons.chev} color={t.textTer} size={14} sw={2} />
                  </div>
                </Pressable>);

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

}

// ─────────────────────────────────────────────────────────────
// SCREEN: Detail
// ─────────────────────────────────────────────────────────────
function ScreenDetail({ id, go, equipment, rentals = [], toast }) {
  const t = useTheme();
  const e = equipment.find((x) => x.id === id) || equipment[0];
  if (!e) return <div style={{ padding: 40, textAlign: 'center', color: t.textSec }}>Nicht gefunden.</div>;
  const [fav, setFav] = useState(false);
  const stock = eqStock(e, rentals);
  const history = rentals.
  filter((r) => r.equipmentId === e.id).
  sort((a, b) => b.start.localeCompare(a.start));

  return (
    <>
      <div style={{
        height: 320, position: 'relative',
        background: e.photo ? '#1c1c1e' : 'linear-gradient(160deg, #1c1c1e 0%, #2c2c2e 50%, #48484a 100%)',
        marginTop: -47
      }}>
        {e.photo ?
        <img src={e.photo} alt="" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', opacity: 0.92 }} /> :

        <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {e.emoji ?
          <span style={{ fontSize: 110 }}>{e.emoji}</span> :
          <EqGlyph kind={e.ic} size={120} color="rgba(255,255,255,0.7)" />}
          </div>
        }

        <div style={{ position: 'absolute', top: 56, left: 16, right: 16, display: 'flex', justifyContent: 'space-between', zIndex: 10 }}>
          <Pressable onClick={() => go('home')} scale={0.88}>
            <Glass dark radius={22} padding="10px 12px">
              <Icon d={icons.back} color="#fff" size={20} sw={2.2} />
            </Glass>
          </Pressable>
          <div style={{ display: 'flex', gap: 8 }}>
            <Pressable onClick={() => {setFav(!fav);toast(fav ? 'Entfernt' : 'Favorit gespeichert');}} scale={0.88}>
              <Glass dark radius={22} padding="10px 12px">
                <Icon d={icons.star} color={fav ? '#FFD60A' : '#fff'} size={20} sw={1.8} fill={fav} />
              </Glass>
            </Pressable>
            <Pressable onClick={() => go('eq')} scale={0.88}>
              <Glass dark radius={22} padding="10px 12px">
                <Icon d={icons.edit} color="#fff" size={20} sw={2.0} />
              </Glass>
            </Pressable>
          </div>
        </div>
      </div>

      <div style={{ paddingBottom: 100, marginTop: -20, position: 'relative', background: t.bg, borderTopLeftRadius: 28, borderTopRightRadius: 28, zIndex: 5 }}>
        <div style={{ padding: '20px 20px 0' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontSize: 12, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.6 }}>{e.cat}</div>
            <div style={{
              fontSize: 11, fontWeight: 600, padding: '3px 8px', borderRadius: 10,
              color: stock.verfuegbar === 0 ? t.textSec : t.text,
              background: t.chip
            }}>{stock.verfuegbar} / {stock.total} verfügbar</div>
          </div>
          <div style={{ fontSize: 24, fontWeight: 700, color: t.text, letterSpacing: -0.5, marginTop: 4 }}>{e.name}</div>
          <div style={{ fontSize: 14, color: t.textSec, marginTop: 2 }}>{e.sub}</div>
        </div>

        <div style={{ padding: '20px 16px 0' }}>
          <div style={{ background: t.card, borderRadius: 16, padding: 4, display: 'flex', alignItems: 'stretch', boxShadow: t.shadowCard }}>
            {[
            ['Verfügbar', stock.verfuegbar, true],
            ['Vermietet', stock.vermietet, false],
            ['In Reparatur', stock.reparatur, false]].
            map(([k, v, strong], i) =>
            <React.Fragment key={k}>
                {i > 0 && <div style={{ width: '0.5px', background: t.sep, margin: '10px 0' }} />}
                <div style={{ flex: 1, textAlign: 'center', padding: '10px 4px' }}>
                  <div style={{ fontSize: 22, fontWeight: 700, color: strong ? t.text : t.textSec, letterSpacing: -0.4, fontVariantNumeric: 'tabular-nums' }}>{v}</div>
                  <div style={{ fontSize: 11, color: t.textSec, marginTop: 2 }}>{k}</div>
                </div>
              </React.Fragment>
            )}
          </div>
          <div style={{ marginTop: 8, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            {[['Tagespreis', e.price + ' €'], ['Einsätze', e.uses || 0]].map(([k, v]) =>
            <div key={k} style={{ background: t.card, borderRadius: 14, padding: 12, textAlign: 'center', boxShadow: t.shadowCard }}>
                <div style={{ fontSize: 18, fontWeight: 700, color: t.text, letterSpacing: -0.3 }}>{v}</div>
                <div style={{ fontSize: 11, color: t.textSec, marginTop: 2 }}>{k}</div>
              </div>
            )}
          </div>
        </div>

        <div style={{ padding: '20px 16px 0', display: 'flex', gap: 8 }}>
          <Pressable onClick={() => go('cal')} style={{ flex: 1 }}>
            <div style={{ background: t.solidBg, color: t.solidFg, borderRadius: 14, padding: '14px 0', textAlign: 'center', fontSize: 14, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
              <Icon d={icons.cal} color={t.solidFg} size={16} sw={2} />
              Termin anlegen
            </div>
          </Pressable>
          <Pressable onClick={() => go('eq')}>
            <div style={{ background: t.chip, borderRadius: 14, padding: '14px 18px', fontSize: 14, fontWeight: 600, color: t.text, display: 'flex', alignItems: 'center', gap: 6 }}>
              <Icon d={icons.edit} color={t.text} size={16} sw={2} />
              Bearbeiten
            </div>
          </Pressable>
        </div>

        {/* Maintenance summary */}
        {e.maint && e.maint.length > 0 &&
        <>
            <div style={{ padding: '20px 20px 8px', fontSize: 15, fontWeight: 600, color: t.text, letterSpacing: -0.3 }}>Wartung & Reparatur</div>
            <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 6 }}>
              {e.maint.map((m) => {
              const mm = maintMeta(m.type);
              return (
                <div key={m.id} style={{ background: t.card, borderRadius: 14, padding: '12px 14px', display: 'flex', gap: 12, alignItems: 'center', boxShadow: t.shadowCard }}>
                    <div style={{ width: 34, height: 34, borderRadius: 10, background: mm.color + '22', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16 }}>{mm.icon}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: t.text }}>{m.title}</div>
                      <div style={{ fontSize: 11, color: t.textSec, marginTop: 1 }}>{mm.label} · {fmtDateDE(m.date)}{m.note ? ' · ' + m.note : ''}</div>
                    </div>
                    <div style={{ fontSize: 10, fontWeight: 700, color: m.done ? t.green : mm.color }}>{m.done ? 'Erledigt' : 'Offen'}</div>
                  </div>);

            })}
            </div>
          </>
        }

        <div style={{ padding: '20px 20px 8px', fontSize: 15, fontWeight: 600, color: t.text, letterSpacing: -0.3 }}>Verlauf</div>
        <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 6 }}>
          {history.length === 0 &&
          <div style={{ background: t.card, borderRadius: 14, padding: '16px', textAlign: 'center', color: t.textSec, fontSize: 13, boxShadow: t.shadowCard }}>Noch keine Vermietungen.</div>
          }
          {history.map((r) =>
          <div key={r.id} style={{ background: t.card, borderRadius: 14, padding: '12px 14px', display: 'flex', justifyContent: 'space-between', boxShadow: t.shadowCard }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: t.text }}>{r.tenantName}</div>
                <div style={{ fontSize: 11, color: t.textSec, marginTop: 2 }}>{r.purpose || '—'} · {fmtRange(r.start, r.end)}</div>
              </div>
              <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{rentalTotal(r)} €</div>
            </div>
          )}
        </div>
      </div>
    </>);

}

Object.assign(window, { ScreenDashboard, ScreenDetail });