// Equipment management screen — list / add / edit / delete
const { useState, useEffect, useRef } = React;

// ─── Row: tap → preview, long-press → menu ───
function EqRow({ item, t, rentals, onOpen, onEdit, onDelete }) {
  const startX = React.useRef(0);
  const startY = React.useRef(0);
  const moved    = React.useRef(false);
  const longTimer = React.useRef(null);
  const longFired = React.useRef(false);
  const rowRef = React.useRef(null);
  const [menu, setMenu] = React.useState(null); // { x, y } | null

  const { total, verfuegbar: verf } = eqStock(item, rentals);

  const cancelLong = () => { if (longTimer.current) { clearTimeout(longTimer.current); longTimer.current = null; } };

  const onPointerDown = (ev) => {
    if (ev.pointerType === 'mouse' && ev.button !== 0) return;
    startX.current = ev.clientX;
    startY.current = ev.clientY;
    moved.current = false;
    longFired.current = false;
    cancelLong();
    longTimer.current = setTimeout(() => {
      longFired.current = true;
      const rect = rowRef.current && rowRef.current.getBoundingClientRect();
      if (rect) setMenu({ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 });
    }, 480);
    try { ev.currentTarget.setPointerCapture(ev.pointerId); } catch {}
  };

  const onPointerMove = (ev) => {
    const adx = ev.clientX - startX.current;
    const ady = ev.clientY - startY.current;
    if (!moved.current && (Math.abs(adx) > 5 || Math.abs(ady) > 5)) {
      moved.current = true;
      cancelLong();
    }
  };

  const settle = () => {
    cancelLong();
    if (longFired.current) return;       // menu shown, no tap
    if (moved.current) return;            // user scrolled, no tap
    onOpen();
  };

  return (
    <div style={{ position: 'relative', borderRadius: 18 }}>
      <div ref={rowRef}
        onPointerDown={onPointerDown}
        onPointerMove={onPointerMove}
        onPointerUp={settle}
        onPointerCancel={cancelLong}
        style={{
          background: t.card, borderRadius: 18, padding: 12,
          display: 'flex', gap: 12, alignItems: 'center',
          boxShadow: '0 1px 2px rgba(0,0,0,0.04)',
          touchAction: 'pan-y', cursor: 'pointer',
          position: 'relative', zIndex: 1, userSelect: 'none',
        }}>
        <EqAvatar item={item} size={54} radius={12}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 15, fontWeight: 600, color: t.text, letterSpacing: -0.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.name}</div>
          <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.cat}</div>

          <div style={{ display: 'flex', gap: 6, marginTop: 7, flexWrap: 'wrap' }}>
            <div style={{ display: 'inline-flex', alignItems: 'baseline', gap: 3, padding: '4px 9px', borderRadius: 8, background: t.chipStrong, fontVariantNumeric: 'tabular-nums' }}>
              <span style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{item.price}</span>
              <span style={{ fontSize: 10, fontWeight: 600, color: t.textSec }}>€/Tag</span>
            </div>
            <div style={{ display: 'inline-flex', alignItems: 'baseline', gap: 3, padding: '4px 9px', borderRadius: 8, background: t.chipStrong, fontVariantNumeric: 'tabular-nums' }}>
              <span style={{ fontSize: 14, fontWeight: 700, color: verf === 0 ? t.textSec : t.text }}>{verf}<span style={{ color: t.textSec, fontWeight: 600 }}>/{total}</span></span>
              <span style={{ fontSize: 10, fontWeight: 600, color: t.textSec }}>verfügbar</span>
            </div>
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6, flexWrap: 'wrap' }}>
            {(item.accessories || []).length > 0 && (
              <div style={{ fontSize: 10, fontWeight: 700, color: t.accent, background: t.accentSoft, padding: '2px 7px', borderRadius: 100 }}>+ {item.accessories.length} Zubehör</div>
            )}
            {(item.maint || []).filter(m => !m.done).map(m => {
              const mm = maintMeta(m.type);
              const label = m.type === 'tuev' ? `TÜV ${fmtDateDE(m.date).slice(0, 6)}` : mm.label;
              return (
                <div key={m.id} style={{ fontSize: 10, fontWeight: 700, color: mm.color, background: mm.color + '20', padding: '2px 7px', borderRadius: 100, whiteSpace: 'nowrap' }}>{mm.icon} {label}</div>
              );
            })}
          </div>
        </div>
        <Icon d="M9 18l6-6-6-6" color={t.textTer} size={14} sw={2.2}/>
      </div>

      {menu && <EqContextMenu pos={menu} t={t}
        onClose={() => setMenu(null)}
        onEdit={() => { setMenu(null); onEdit(); }}
        onDelete={() => { setMenu(null); onDelete(); }}/>}
    </div>
  );
}

// Floating two-action menu shown after a long-press on a row.
function EqContextMenu({ pos, t, onClose, onEdit, onDelete }) {
  // Clamp menu within viewport.
  const W = 220, H = 110;
  const vw = typeof window !== 'undefined' ? window.innerWidth  : 360;
  const vh = typeof window !== 'undefined' ? window.innerHeight : 720;
  const left = Math.max(12, Math.min(vw - W - 12, pos.x - W / 2));
  const top  = Math.max(12, Math.min(vh - H - 12, pos.y - H / 2));
  return (
    <React.Fragment>
      <div onClick={onClose} onPointerDown={(e) => e.stopPropagation()}
        style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(0,0,0,0.25)', backdropFilter: 'blur(2px)', WebkitBackdropFilter: 'blur(2px)' }}/>
      <div style={{
        position: 'fixed', left, top, width: W, zIndex: 201,
        background: t.card, borderRadius: 14,
        boxShadow: '0 16px 40px rgba(0,0,0,0.35)',
        overflow: 'hidden',
        animation: 'eq-pop 0.16s cubic-bezier(.2,.8,.2,1.05)',
      }}>
        <Pressable onClick={onEdit} scale={1}>
          <div style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: `0.5px solid ${t.sep}` }}>
            <span style={{ fontSize: 15, color: t.text, fontWeight: 500 }}>Bearbeiten</span>
            <Icon d={icons.edit} color={t.text} size={16} sw={1.8}/>
          </div>
        </Pressable>
        <Pressable onClick={onDelete} scale={1}>
          <div style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <span style={{ fontSize: 15, color: t.red, fontWeight: 500 }}>Löschen</span>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke={t.red} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18M8 6V4a2 2 0 012-2h4a2 2 0 012 2v2M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/></svg>
          </div>
        </Pressable>
      </div>
      <style>{`@keyframes eq-pop { from { opacity: 0; transform: scale(0.92); } to { opacity: 1; transform: scale(1); } }`}</style>
    </React.Fragment>
  );
}

// ─── Read-only preview sheet — opens when tapping a row ───
function EqPreviewSheet({ open, onClose, item, rentals, setEquipment, onEdit, onDelete }) {
  const t = useTheme();
  if (!item) return <Sheet open={open} onClose={onClose}><div/></Sheet>;
  const { total, verfuegbar: verf, vermietet, reparatur } = eqStock(item, rentals);

  const patch = (changes) => setEquipment(prev => prev.map(p => p.id === item.id ? { ...p, ...changes } : p));
  const setQty = (q) => {
    const next = Math.max(1, Number(q) || 1);
    // Don't let qty drop below what's currently rented out
    const min = vermietet + reparatur;
    patch({ qty: Math.max(min, next) });
  };

  const Cell = ({ label, value, strong, accent }) => (
    <div style={{ flex: 1, textAlign: 'center', padding: '12px 4px' }}>
      <div style={{ fontSize: 19, fontWeight: 700, color: accent || (strong ? t.text : t.textSec), letterSpacing: -0.4, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
      <div style={{ fontSize: 10.5, color: t.textSec, fontWeight: 600, marginTop: 2 }}>{label}</div>
    </div>
  );

  const StepBtn = ({ sign, onClick, disabled }) => (
    <Pressable onClick={() => !disabled && onClick()} scale={0.88} disabled={disabled}>
      <div style={{ width: 36, height: 36, borderRadius: 11, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: disabled ? 0.4 : 1 }}>
        <Icon d={sign > 0 ? 'M12 5v14M5 12h14' : 'M5 12h14'} color={t.text} size={17} sw={2.4}/>
      </div>
    </Pressable>
  );

  return (
    <Sheet open={open} onClose={onClose} maxHeight="92%">
      <div style={{ padding: '4px 0 24px' }}>
        {/* Hero */}
        <div style={{ padding: '6px 24px 0', display: 'flex', alignItems: 'flex-start', gap: 16 }}>
          <EqAvatar item={item} size={84} radius={20}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 22, fontWeight: 700, color: t.text, letterSpacing: -0.5, lineHeight: 1.15 }}>{item.name}</div>
            <div style={{ fontSize: 13, color: t.textSec, marginTop: 4 }}>{item.cat}{item.sub ? ' · ' + item.sub : ''}</div>
            {item.kind && (
              <div style={{ display: 'inline-block', fontSize: 10.5, fontWeight: 700, color: t.accent, background: t.accentSoft, padding: '3px 9px', borderRadius: 100, marginTop: 8, textTransform: 'uppercase', letterSpacing: 0.4 }}>{item.kind}</div>
            )}
          </div>
        </div>

        {/* Stats */}
        <div style={{ padding: '20px 16px 0' }}>
          <div style={{ background: t.cardAlt, borderRadius: 14, padding: 4, display: 'flex', alignItems: 'stretch' }}>
            <Cell label="€/Tag" value={item.price || 0} strong/>
            <div style={{ width: 0.5, background: t.sep, margin: '10px 0' }}/>
            <Cell label="Verfügbar" value={`${verf}/${total}`} accent={verf === 0 ? t.red : t.green}/>
            <div style={{ width: 0.5, background: t.sep, margin: '10px 0' }}/>
            <Cell label="Einsätze" value={item.uses || 0}/>
          </div>
        </div>

        {/* Anzahl stepper */}
        <div style={{ padding: '18px 24px 0' }}>
          <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>Bestand</div>
          <div style={{ background: t.cardAlt, borderRadius: 12, padding: '12px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontSize: 14, color: t.text, fontWeight: 500 }}>Anzahl im Inventar</div>
              <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 2 }}>
                {vermietet > 0 ? `${vermietet} vermietet` : 'Nichts vermietet'}
                {reparatur > 0 ? ` · ${reparatur} in Reparatur` : ''}
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <StepBtn sign={-1} disabled={(item.qty || 1) <= Math.max(1, vermietet + reparatur)} onClick={() => setQty((item.qty || 1) - 1)}/>
              <div style={{ minWidth: 26, textAlign: 'center', fontSize: 19, fontWeight: 700, color: t.text, fontVariantNumeric: 'tabular-nums' }}>{item.qty || 1}</div>
              <StepBtn sign={1} onClick={() => setQty((item.qty || 1) + 1)}/>
            </div>
          </div>
        </div>

        {/* Wartung — direkt editierbar */}
        <div style={{ padding: '18px 24px 0' }}>
          <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>Wartung & Reparatur</div>
          <MaintEditor value={item.maint || []} onChange={v => patch({ maint: v })}/>
        </div>

        {/* Zubehör — read only */}
        {(item.accessories || []).length > 0 && (
          <div style={{ padding: '18px 24px 0' }}>
            <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 8 }}>Zubehör · gehört dazu</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {item.accessories.map(s => (
                <div key={s} style={{ padding: '6px 11px', borderRadius: 9, background: t.chip, color: t.text, fontSize: 12.5, fontWeight: 600 }}>{s}</div>
              ))}
            </div>
          </div>
        )}

        {/* Actions */}
        <div style={{ padding: '24px 24px 0', display: 'flex', gap: 10 }}>
          <Pressable onClick={onEdit} scale={0.97} style={{ flex: 1 }}>
            <div style={{ padding: '15px 0', textAlign: 'center', borderRadius: 14, background: t.solidBg, color: t.solidFg, fontSize: 15, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, boxShadow: '0 6px 16px rgba(0,0,0,0.22)' }}>
              <Icon d={icons.edit} color={t.solidFg} size={15} sw={1.8}/>
              Bearbeiten
            </div>
          </Pressable>
          <Pressable onClick={onDelete} scale={0.97}>
            <div style={{ padding: '15px 20px', borderRadius: 14, background: t.redSoft, color: t.red, fontSize: 15, fontWeight: 600 }}>
              Löschen
            </div>
          </Pressable>
        </div>
      </div>
    </Sheet>
  );
}

const EQ_KIND_OPTIONS = ['Tontechnik', 'Anhänger', 'Kabel'];

// Suggest accessories based on equipment type / name keywords. Returns deduped list of strings.
function suggestAccessories(eq) {
  if (!eq) return [];
  const key = ((eq.name || '') + ' ' + (eq.cat || '') + ' ' + (eq.kind || '')).toLowerCase();
  const out = [];
  if (/mikr|mic|sm5|ew\d|sennheis|shure|funkmik|ges/.test(key)) {
    out.push('XLR-Kabel 5m', 'Mikrofonständer');
  }
  if (/sm5|gesang/.test(key)) out.push('Popschutz');
  if (/funk/.test(key)) out.push('Ersatz-Batterien (AA ×4)');
  if (/lautsprech|aktivlaut|jbl|prx|eon|pa|box/.test(key)) {
    out.push('Boxenständer', 'Stromkabel 5m', 'Speakon-Kabel');
  }
  if (/misch|mixer|mg10|yamaha|pult/.test(key)) {
    out.push('USB-Kabel', 'Klinke-Klinke 3m');
  }
  if (/anhäng|trailer/.test(key)) {
    out.push('Spanngurte (4×)', 'Sicherungsnetz', 'Adapter 7→13-polig');
  }
  if (/kabel|verläng|trommel/.test(key)) out.push('Kabeltrommel 25m');
  return [...new Set(out)];
}

// ─── Utilization stats card (Auslastung) ──────────────────────
// ─── Top Performance card — % of total rentals per item ──────
// Replaces the old generic utilization chart. Shows which products
// drive the most rentals as a clear percentage of total bookings.
function UtilizationCard({ equipment, onSelect }) {
  const t = useTheme();
  const [open, setOpen] = useState(false);
  if (equipment.length === 0) return null;

  const totalUses = equipment.reduce((s, e) => s + (Number(e.uses) || 0), 0) || 1;
  const ranked = [...equipment]
    .map(e => ({ ...e, pct: Math.round(((Number(e.uses) || 0) / totalUses) * 100) }))
    .sort((a, b) => b.pct - a.pct);
  const topPct = ranked[0] ? ranked[0].pct : 0;
  const visible = open ? ranked : ranked.slice(0, 3);

  const barColor = (p) => p >= 25 ? t.green : p >= 12 ? t.accent : p >= 5 ? t.orange : t.textTer;

  const Bar = ({ pct, color }) => (
    <div style={{ height: 8, background: t.chip, borderRadius: 4, overflow: 'hidden' }}>
      <div style={{ width: `${Math.min(100, Math.max(0, pct))}%`, height: '100%', background: color, borderRadius: 4, transition: 'width 0.4s' }}/>
    </div>
  );

  return (
    <div style={{ padding: '0 16px', marginTop: 12 }}>
      <div style={{ background: t.card, borderRadius: 18, padding: '16px 16px', boxShadow: t.shadowCard }}>
        <Pressable onClick={() => setOpen(o => !o)} scale={0.99}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <div>
              <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.6 }}>Beliebteste Produkte</div>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginTop: 4 }}>
                <div style={{ fontSize: 13, color: t.textSec, fontWeight: 500 }}>Spitzenreiter:</div>
                <div style={{ fontSize: 20, fontWeight: 700, color: t.text, letterSpacing: -0.4 }}>{ranked[0] ? ranked[0].name : '—'}</div>
                <div style={{ fontSize: 16, fontWeight: 700, color: t.green, marginLeft: 'auto', fontVariantNumeric: 'tabular-nums' }}>{topPct}%</div>
              </div>
            </div>
            <Icon d={open ? 'M5 15l7-7 7 7' : 'M5 9l7 7 7-7'} color={t.textSec} size={15} sw={2}/>
          </div>
        </Pressable>

        <div style={{ marginTop: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
          {visible.map((e, i) => (
            <Pressable key={e.id} onClick={() => onSelect && onSelect(e)} scale={0.99}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <div style={{
                  width: 22, textAlign: 'center', fontSize: 10, fontWeight: 700,
                  color: i === 0 ? t.green : i === 1 ? t.accent : i === 2 ? t.orange : t.textTer,
                }}>#{i + 1}</div>
                <EqAvatar item={e} size={32} radius={8}/>
                <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={{ marginTop: 4 }}><Bar pct={e.pct} color={barColor(e.pct)}/></div>
                </div>
                <div style={{ textAlign: 'right', minWidth: 56 }}>
                  <div style={{ fontSize: 14, fontWeight: 700, color: t.text, fontVariantNumeric: 'tabular-nums' }}>{e.pct}%</div>
                  <div style={{ fontSize: 10, color: t.textSec, marginTop: 1 }}>{e.uses || 0} ×</div>
                </div>
              </div>
            </Pressable>
          ))}
        </div>

        {!open && ranked.length > 3 && (
          <Pressable onClick={() => setOpen(true)} scale={0.99} style={{ marginTop: 10 }}>
            <div style={{ textAlign: 'center', fontSize: 12, fontWeight: 600, color: t.accent }}>
              Alle {ranked.length} Geräte anzeigen ›
            </div>
          </Pressable>
        )}
      </div>
    </div>
  );
}

// ─── Accessory editor (used inside the equipment sheet) ───
function AccessoryEditor({ value = [], onChange, suggestions = [] }) {
  const t = useTheme();
  const [text, setText] = useState('');
  const items = value || [];
  const open = suggestions.filter(s => !items.includes(s));

  const add = (v) => {
    const s = (v || text).trim();
    if (!s) return;
    if (items.includes(s)) { setText(''); return; }
    onChange([...items, s]);
    setText('');
  };
  const remove = (s) => onChange(items.filter(x => x !== s));
  const addAll = () => onChange([...items, ...open]);

  const inpStyle = {
    flex: 1, minWidth: 0, width: 0, padding: '10px 12px', borderRadius: 10,
    border: `0.5px solid ${t.inputBorder}`, background: t.inputBg,
    fontSize: 14, color: t.text, outline: 'none', fontFamily: 'inherit', boxSizing: 'border-box',
  };

  return (
    <div>
      {/* Selected accessories */}
      {items.length > 0 && (
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 8 }}>
          {items.map(s => (
            <div key={s} style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '6px 8px 6px 12px', borderRadius: 9, background: t.accentSoft, color: t.accent, fontSize: 12, fontWeight: 600 }}>
              <span>{s}</span>
              <Pressable onClick={() => remove(s)} scale={0.85}>
                <div style={{ width: 18, height: 18, borderRadius: 9, background: t.dark ? 'rgba(255,255,255,0.18)' : 'rgba(0,0,0,0.08)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <svg width="8" height="8" viewBox="0 0 12 12" fill="none" stroke={t.accent} strokeWidth="2.4" strokeLinecap="round"><path d="M3 3l6 6M9 3l-6 6"/></svg>
                </div>
              </Pressable>
            </div>
          ))}
        </div>
      )}

      {/* Add custom */}
      <div style={{ display: 'flex', gap: 8 }}>
        <input value={text} onChange={e => setText(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); add(); } }}
          placeholder="z.B. DI-Box, Adapter, Trolley…" style={inpStyle}/>
        <Pressable onClick={() => add()} scale={0.94}>
          <div style={{ padding: '10px 14px', borderRadius: 10, background: t.solidBg, color: t.solidFg, fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap' }}>+ Zubehör</div>
        </Pressable>
      </div>

      {/* Suggestions */}
      {open.length > 0 && (
        <div style={{ marginTop: 12, padding: 12, background: t.cardAlt, borderRadius: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
            <div style={{ fontSize: 10, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.6 }}>💡 Auto-Vorschläge</div>
            <Pressable onClick={addAll} scale={0.94}>
              <div style={{ fontSize: 11, color: t.accent, fontWeight: 700 }}>Alle übernehmen</div>
            </Pressable>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {open.map(s => (
              <Pressable key={s} onClick={() => add(s)} scale={0.95}>
                <div style={{ padding: '6px 10px', borderRadius: 9, background: t.card, color: t.text, fontSize: 12, fontWeight: 600, border: `1px dashed ${t.sep}` }}>+ {s}</div>
              </Pressable>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Maintenance / repair editor (used inside the equipment sheet) ───
function MaintEditor({ value = [], onChange }) {
  const t = useTheme();
  const [adding, setAdding] = useState(false);
  const blank = { type: 'check', title: '', date: todayISO(), note: '' };
  const [draft, setDraft] = useState(blank);

  const dInp = {
    width: '100%', padding: '10px 12px', borderRadius: 10,
    border: `0.5px solid ${t.inputBorder}`, background: t.inputBg,
    fontSize: 14, color: t.text, outline: 'none', fontFamily: 'inherit', boxSizing: 'border-box',
  };

  const add = () => {
    if (!draft.title.trim()) return;
    onChange([...value, { ...draft, id: 'm-' + Date.now(), done: false }]);
    setDraft(blank); setAdding(false);
  };
  const toggle = (id) => onChange(value.map(m => m.id === id ? { ...m, done: !m.done } : m));
  const remove = (id) => onChange(value.filter(m => m.id !== id));

  return (
    <div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
        {value.map(m => {
          const mm = maintMeta(m.type);
          return (
            <div key={m.id} style={{ background: t.cardAlt, borderRadius: 12, padding: '10px 12px', display: 'flex', alignItems: 'center', gap: 10 }}>
              <Pressable onClick={() => toggle(m.id)} scale={0.85}>
                <div style={{
                  width: 22, height: 22, borderRadius: 11, flexShrink: 0,
                  border: m.done ? 'none' : `2px solid ${t.textTer}`,
                  background: m.done ? t.green : 'transparent',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {m.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>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600, color: m.done ? t.textTer : t.text, textDecoration: m.done ? 'line-through' : 'none' }}>{mm.icon} {m.title}</div>
                <div style={{ fontSize: 11, color: t.textSec, marginTop: 1 }}>{mm.label} · {fmtDateDE(m.date)}{m.note ? ' · ' + m.note : ''}</div>
              </div>
              <Pressable onClick={() => remove(m.id)} scale={0.8}>
                <div style={{ width: 26, height: 26, borderRadius: 13, background: t.redSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke={t.red} strokeWidth="2.2" strokeLinecap="round"><path d="M3 3l6 6M9 3l-6 6"/></svg>
                </div>
              </Pressable>
            </div>
          );
        })}
      </div>

      {adding ? (
        <div style={{ marginTop: 8, padding: 12, background: t.cardAlt, borderRadius: 12 }}>
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
            {MAINT_TYPES.map(ty => {
              const mm = maintMeta(ty);
              const sel = draft.type === ty;
              return (
                <Pressable key={ty} onClick={() => setDraft(d => ({ ...d, type: ty }))} scale={0.94}>
                  <div style={{
                    padding: '6px 10px', borderRadius: 9, fontSize: 12, fontWeight: 600,
                    background: sel ? mm.color : t.chip, color: sel ? '#fff' : t.text,
                  }}>{mm.icon} {mm.label}</div>
                </Pressable>
              );
            })}
          </div>
          <input value={draft.title} onChange={e => setDraft(d => ({ ...d, title: e.target.value }))} placeholder="z.B. Nächster TÜV / HU" style={dInp}/>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 8 }}>
            <input type="date" value={draft.date} onChange={e => setDraft(d => ({ ...d, date: e.target.value }))} style={dInp}/>
            <input value={draft.note} onChange={e => setDraft(d => ({ ...d, note: e.target.value }))} placeholder="Notiz" style={dInp}/>
          </div>
          <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
            <Pressable onClick={add} scale={0.96} style={{ flex: 1 }}>
              <div style={{ padding: '10px 0', textAlign: 'center', borderRadius: 10, background: t.solidBg, color: t.solidFg, fontSize: 13, fontWeight: 600 }}>Hinzufügen</div>
            </Pressable>
            <Pressable onClick={() => { setDraft(blank); setAdding(false); }} scale={0.96}>
              <div style={{ padding: '10px 16px', textAlign: 'center', borderRadius: 10, background: t.chip, color: t.text, fontSize: 13, fontWeight: 600 }}>Abbrechen</div>
            </Pressable>
          </div>
        </div>
      ) : (
        <Pressable onClick={() => setAdding(true)} scale={0.98} style={{ marginTop: 8 }}>
          <div style={{ padding: '11px 0', textAlign: 'center', borderRadius: 12, background: t.accentSoft, color: t.accent, fontSize: 13, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
            <Icon d={icons.plus} color={t.accent} size={14} sw={2.6}/>
            Wartung / Defekt / TÜV erfassen
          </div>
        </Pressable>
      )}
    </div>
  );
}

// ─── Edit / Add equipment sheet ─────────────────────────────
function EquipmentSheet({ open, onClose, initial, onSave, categories, rentals = [] }) {
  const t = useTheme();
  const isEdit = !!initial;
  const blank = { id: '', name: '', cat: '', sub: '', kind: categories[0] || 'Tontechnik',
                  repairQty: 0, price: 0, qty: 1, uses: 0, ic: 'speaker', emoji: '', photo: '', until: '', maint: [], accessories: [] };
  const [form, setForm] = useState(blank);
  const [uploading, setUploading] = useState(false);
  const fileRef = useRef(null);

  useEffect(() => {
    if (open) setForm(initial ? { ...blank, ...initial } : blank);
  }, [open, initial]);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const valid = form.name.trim() && form.cat.trim();

  const save = () => {
    if (!valid) return;
    const out = {
      ...form,
      id: form.id || ('eq-' + Date.now()),
      price: Number(form.price) || 0,
      qty:   Math.max(1, Number(form.qty) || 1),
      repairQty: Math.max(0, Math.min(Math.max(1, Number(form.qty) || 1), Number(form.repairQty) || 0)),
      uses:  Number(form.uses)  || 0,
    };
    onSave(out);
    onClose();
  };

  return (
    <Sheet open={open} onClose={onClose}>
      <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 }}>{isEdit ? 'Equipment bearbeiten' : 'Neues Equipment'}</div>
            <div style={{ fontSize: 13, color: t.textSec, marginTop: 4 }}>{isEdit ? 'Felder anpassen' : 'Lege ein neues Mietobjekt an.'}</div>
          </div>
          <Pressable onClick={onClose}>
            <div style={{ fontSize: 14, color: t.textSec, fontWeight: 500 }}>Abbrechen</div>
          </Pressable>
        </div>

        <FormGroup label="Bezeichnung" required>
          <input value={form.name} onChange={e => set('name', e.target.value)} placeholder="z.B. JBL PRX-815" style={inp(t)}/>
        </FormGroup>

        <FormGroup label="Kategorie / Bauart" required>
          <input value={form.cat} onChange={e => set('cat', e.target.value)} placeholder="z.B. Aktivlautsprecher" style={inp(t)}/>
        </FormGroup>

        <FormGroup label="Spezifikation">
          <input value={form.sub} onChange={e => set('sub', e.target.value)} placeholder="z.B. 1.300 W · 12″ · Bluetooth" style={inp(t)}/>
        </FormGroup>

        <FormGroup label="Typ">
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
            {categories.map(k => (
              <Pressable key={k} onClick={() => set('kind', k)} scale={0.95}>
                <div style={{
                  padding: '8px 14px', borderRadius: 10,
                  background: form.kind === k ? t.solidBg : t.chip,
                  color: form.kind === k ? t.solidFg : t.text,
                  fontSize: 13, fontWeight: 600,
                }}>{k}</div>
              </Pressable>
            ))}
          </div>
        </FormGroup>

        <FormGroup label="Bild / Symbol">
          <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            {/* Live preview */}
            <div style={{ position: 'relative', flexShrink: 0 }}>
              <EqAvatar item={form} size={72} radius={16}/>
              {form.photo && (
                <Pressable onClick={() => set('photo', '')} scale={0.85} style={{ position: 'absolute', top: -6, right: -6 }}>
                  <div style={{ width: 22, height: 22, borderRadius: 11, background: t.red, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 2px 6px rgba(0,0,0,0.2)' }}>
                    <svg width="10" height="10" viewBox="0 0 12 12" fill="none" stroke="#fff" strokeWidth="2.4" strokeLinecap="round"><path d="M3 3l6 6M9 3l-6 6"/></svg>
                  </div>
                </Pressable>
              )}
            </div>
            {/* Upload button */}
            <div style={{ flex: 1 }}>
              <input ref={fileRef} type="file" accept="image/*" style={{ display: 'none' }}
                onChange={async (e) => {
                  const file = e.target.files && e.target.files[0];
                  if (!file) return;
                  setUploading(true);
                  try { const url = await compressImage(file); setForm(f => ({ ...f, photo: url })); }
                  catch { /* ignore */ }
                  setUploading(false);
                  e.target.value = '';
                }}/>
              <Pressable onClick={() => fileRef.current && fileRef.current.click()} scale={0.97}>
                <div style={{
                  padding: '14px 0', textAlign: 'center', borderRadius: 12,
                  background: 'rgba(0,122,255,0.10)', color: t.accent,
                  fontSize: 14, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                }}>
                  <Icon d={icons.camera} color={t.accent} size={17} sw={1.8}/>
                  {uploading ? 'Lädt…' : (form.photo ? 'Foto ändern' : 'Eigenes Foto hochladen')}
                </div>
              </Pressable>
              <div style={{ fontSize: 11, color: t.textSec, marginTop: 6, lineHeight: 1.4 }}>
                Eigenes Bild aufnehmen oder wählen – oder unten ein Symbol/Emoji.
              </div>
            </div>
          </div>

          {/* Glyph row — only the first 3 symbols */}
          <div style={{ marginTop: 12, fontSize: 10, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>Symbole</div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {EQ_GLYPHS.slice(0, 3).map(g => {
              const sel = !form.photo && !form.emoji && form.ic === g;
              return (
                <Pressable key={g} onClick={() => setForm(f => ({ ...f, ic: g, emoji: '', photo: '' }))} scale={0.9}>
                  <div style={{
                    width: 46, height: 46, borderRadius: 12,
                    background: sel ? t.accentSoft : t.chip,
                    border: sel ? `1.5px solid ${t.accent}` : '1.5px solid transparent',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>
                    <EqGlyph kind={g} size={24} color={sel ? t.accent : '#1c1c1e'}/>
                  </div>
                </Pressable>
              );
            })}
          </div>

          {/* Custom emoji input — type your own */}
          <div style={{ marginTop: 12, fontSize: 10, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>Eigenes Emoji</div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <div style={{
              width: 46, height: 46, borderRadius: 12, background: form.emoji ? t.accentSoft : t.chip,
              border: form.emoji ? `1.5px solid ${t.accent}` : '1.5px solid transparent',
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24, flexShrink: 0,
            }}>{form.emoji || '?'}</div>
            <input value={form.emoji || ''}
              onChange={(e) => {
                // grab the first visible glyph from the input
                const v = e.target.value;
                const seg = v ? [...v] : [];
                const ch = seg[seg.length - 1] || '';
                setForm(f => ({ ...f, emoji: ch, photo: '' }));
              }}
              placeholder="Emoji eingeben …"
              maxLength={4}
              style={{ flex: 1, padding: '12px 14px', borderRadius: 12, border: `0.5px solid ${t.inputBorder}`, background: t.inputBg, fontSize: 18, color: t.text, outline: 'none', fontFamily: 'inherit', boxSizing: 'border-box' }}/>
            {form.emoji && (
              <Pressable onClick={() => setForm(f => ({ ...f, emoji: '' }))} scale={0.85}>
                <div style={{ padding: '8px 12px', borderRadius: 10, background: t.chip, fontSize: 12, fontWeight: 600, color: t.text }}>Löschen</div>
              </Pressable>
            )}
          </div>
        </FormGroup>

        {/* Verfügbarkeit — abgeleitet aus Anzahl, aktiven Vermietungen und Reparatur */}
        {(() => {
          const stockTotal = Math.max(1, Number(form.qty) || 1);
          const vermietet = rentals
            .filter(r => r.equipmentId === form.id && r.status === 'aktiv')
            .reduce((s, r) => s + (Number(r.quantity) || 1), 0);
          const maxRepair = Math.max(0, stockTotal - vermietet);
          const reparatur = Math.max(0, Math.min(maxRepair, Number(form.repairQty) || 0));
          const verfuegbar = Math.max(0, stockTotal - vermietet - reparatur);
          const StepBtn = ({ sign, disabled }) => (
            <Pressable onClick={() => !disabled && set('repairQty', Math.max(0, Math.min(maxRepair, reparatur + sign)))} scale={0.88} disabled={disabled}>
              <div style={{
                width: 34, height: 34, borderRadius: 10, background: t.chip,
                display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: disabled ? 0.4 : 1,
              }}>
                <Icon d={sign > 0 ? 'M12 5v14M5 12h14' : 'M5 12h14'} color={t.text} size={16} sw={2.4}/>
              </div>
            </Pressable>
          );
          const Cell = ({ label, value, strong }) => (
            <div style={{ flex: 1, textAlign: 'center', padding: '10px 4px' }}>
              <div style={{ fontSize: 20, fontWeight: 700, color: strong ? t.text : t.textSec, letterSpacing: -0.4, fontVariantNumeric: 'tabular-nums' }}>{value}</div>
              <div style={{ fontSize: 10.5, color: t.textSec, fontWeight: 600, marginTop: 2 }}>{label}</div>
            </div>
          );
          return (
            <FormGroup label="Verfügbarkeit">
              <div style={{ background: t.cardAlt, borderRadius: 12, padding: 4, display: 'flex', alignItems: 'stretch' }}>
                <Cell label="Verfügbar" value={verfuegbar} strong/>
                <div style={{ width: '0.5px', background: t.sep, margin: '8px 0' }}/>
                <Cell label="Vermietet" value={vermietet}/>
                <div style={{ width: '0.5px', background: t.sep, margin: '8px 0' }}/>
                <Cell label="In Reparatur" value={reparatur}/>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8, padding: '4px 2px' }}>
                <div style={{ fontSize: 13, color: t.text, fontWeight: 500 }}>Für Reparatur / Wartung rausnehmen</div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <StepBtn sign={-1} disabled={reparatur <= 0}/>
                  <div style={{ minWidth: 18, textAlign: 'center', fontSize: 17, fontWeight: 700, color: t.text, fontVariantNumeric: 'tabular-nums' }}>{reparatur}</div>
                  <StepBtn sign={1} disabled={reparatur >= maxRepair}/>
                </div>
              </div>
              <div style={{ fontSize: 11, color: t.textSec, marginTop: 4, lineHeight: 1.4 }}>
                Reduziert automatisch die verfügbare Menge.
              </div>
            </FormGroup>
          );
        })()}

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginTop: 14, alignItems: 'start' }}>
          <FormGroup label="Tagespreis €" tight>
            <input type="number" value={form.price} onChange={e => set('price', e.target.value)} style={inp(t)}/>
          </FormGroup>
          <FormGroup label="Anzahl" tight>
            <input type="number" min="1" value={form.qty} onChange={e => set('qty', e.target.value)} style={inp(t)}/>
          </FormGroup>
          <FormGroup label="Einsätze" tight>
            <input type="number" value={form.uses} onChange={e => set('uses', e.target.value)} style={inp(t)}/>
          </FormGroup>
        </div>

        <FormGroup label="Wartung & Reparatur">
          <MaintEditor value={form.maint || []} onChange={v => set('maint', v)}/>
        </FormGroup>

        <FormGroup label="Zubehör · gehört dazu">
          <AccessoryEditor
            value={form.accessories || []}
            onChange={v => set('accessories', v)}
            suggestions={suggestAccessories(form)}/>
        </FormGroup>

        <Pressable onClick={save} scale={0.97} disabled={!valid} style={{ marginTop: 22 }}>
          <div style={{
            padding: '15px 0', textAlign: 'center', borderRadius: 14,
            background: valid ? t.solidBg : t.chip,
            color: t.solidFg, fontSize: 16, fontWeight: 600,
            boxShadow: valid ? '0 6px 16px rgba(0,0,0,0.28)' : 'none',
          }}>{isEdit ? 'Änderungen speichern' : 'Equipment hinzufügen'}</div>
        </Pressable>
      </div>
    </Sheet>
  );
}

const inp = (t) => ({
  width: '100%', padding: '12px 14px', borderRadius: 12,
  border: `0.5px solid ${t.inputBorder}`, background: t.inputBg,
  fontSize: 15, color: t.text, outline: 'none', fontFamily: 'inherit',
  boxSizing: 'border-box',
});

function FormGroup({ label, children, required, tight }) {
  const t = useTheme();
  return (
    <div style={{ marginTop: tight ? 0 : 14 }}>
      <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>
        {label}{required && <span style={{ color: t.red, marginLeft: 4 }}>*</span>}
      </div>
      {children}
    </div>
  );
}

// ─── Categories sheet (re-implemented for this tab) ─────────
function CategoriesSheet({ open, onClose, categories, setCategories, toast, equipment }) {
  const t = useTheme();
  const [newName, setNewName] = useState('');
  const [editingIdx, setEditingIdx] = useState(-1);
  const [editName, setEditName] = useState('');

  const add = () => {
    const v = newName.trim();
    if (!v) return;
    if (categories.includes(v)) { toast('Kategorie existiert bereits'); return; }
    setCategories([...categories, v]); setNewName('');
    toast(`„${v}“ hinzugefügt`);
  };

  const remove = (idx) => {
    const v = categories[idx];
    setCategories(categories.filter((_, i) => i !== idx));
    toast(`„${v}“ entfernt`);
  };

  const startEdit = (idx) => { setEditingIdx(idx); setEditName(categories[idx]); };
  const commitEdit = () => {
    const v = editName.trim();
    if (!v || editingIdx < 0) { setEditingIdx(-1); return; }
    if (v === categories[editingIdx]) { setEditingIdx(-1); return; }
    const next = categories.slice(); next[editingIdx] = v;
    setCategories(next); setEditingIdx(-1);
    toast('Umbenannt');
  };

  return (
    <Sheet open={open} onClose={onClose}>
      <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 }}>Kategorien</div>
            <div style={{ fontSize: 13, color: t.textSec, marginTop: 4 }}>Hinzufügen, umbenennen, löschen.</div>
          </div>
          <Pressable onClick={onClose}><div style={{ fontSize: 14, color: t.accent, fontWeight: 600 }}>Fertig</div></Pressable>
        </div>

        <div style={{ display: 'flex', gap: 8, marginTop: 18 }}>
          <input value={newName} onChange={e => setNewName(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') add(); }}
            placeholder="Neue Kategorie…" style={inp(t)}/>
          <Pressable onClick={add} scale={0.94}>
            <div style={{ padding: '12px 18px', borderRadius: 12, background: t.solidBg, color: t.solidFg, fontSize: 14, fontWeight: 600, whiteSpace: 'nowrap' }}>+ Neu</div>
          </Pressable>
        </div>

        <div style={{ marginTop: 16, background: t.card, borderRadius: 14, overflow: 'hidden' }}>
          {categories.map((c, i) => (
            <div key={i} style={{
              display: 'flex', alignItems: 'center', gap: 10, padding: '10px 12px',
              borderBottom: i < categories.length - 1 ? `0.5px solid ${t.sep}` : 'none',
            }}>
              {editingIdx === i ? (
                <input autoFocus value={editName} onChange={e => setEditName(e.target.value)}
                  onBlur={commitEdit}
                  onKeyDown={e => { if (e.key === 'Enter') commitEdit(); if (e.key === 'Escape') setEditingIdx(-1); }}
                  style={{ flex: 1, padding: '8px 10px', borderRadius: 8, border: `1px solid ${t.accent}`, background: t.card, fontSize: 15, color: t.text, outline: 'none', fontFamily: 'inherit' }}/>
              ) : (
                <Pressable onClick={() => startEdit(i)} scale={0.98} style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 500, color: t.text, padding: '8px 0' }}>{c}</div>
                </Pressable>
              )}
              <div style={{ fontSize: 11, color: t.textSec, fontWeight: 500 }}>{equipment.filter(e => e.kind === c).length}</div>
              <Pressable onClick={() => remove(i)} scale={0.85}>
                <div style={{ width: 28, height: 28, borderRadius: 14, background: t.redSoft, color: t.red, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                  <svg width="12" height="12" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M3 3l6 6M9 3l-6 6"/></svg>
                </div>
              </Pressable>
            </div>
          ))}
        </div>
        <div style={{ fontSize: 11, color: t.textSec, marginTop: 12, lineHeight: 1.4 }}>
          Tipp: Auf einen Namen tippen, um umzubenennen.
        </div>
      </div>
    </Sheet>
  );
}

// ─── Main Equipment screen ─────────────────────────────────
function ScreenEquipment({ equipment, setEquipment, categories, setCategories, rentals = [], setRentals, logistik, setLogistik, initialArea = 'equipment', toast, go }) {
  const t = useTheme();
  const [area, setArea] = useState(initialArea);
  useEffect(() => { setArea(initialArea); }, [initialArea]);
  const [filter, setFilter] = useState('Alle');
  const [editing, setEditing] = useState(null);  // equipment object or null
  const [sheetOpen, setSheetOpen] = useState(false);
  const [previewItem, setPreviewItem] = useState(null);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [catsOpen, setCatsOpen] = useState(false);
  const [confirmId, setConfirmId] = useState(null);
  const [logistikSettingsOpen, setLogistikSettingsOpen] = useState(false);

  useEffect(() => {
    if (filter !== 'Alle' && !categories.includes(filter)) setFilter('Alle');
  }, [categories, filter]);

  const filters = ['Alle', ...categories];
  const filtered = filter === 'Alle' ? equipment : equipment.filter(e => e.kind === filter);

  const openNew = () => { setEditing(null); setSheetOpen(true); };
  const openEdit = (eq) => { setEditing(eq); setSheetOpen(true); };
  const openPreview = (eq) => { setPreviewItem(eq); setPreviewOpen(true); };
  const editFromPreview = () => {
    setPreviewOpen(false);
    // Tiny delay so the preview sheet visually closes before the edit sheet appears.
    setTimeout(() => { setEditing(previewItem); setSheetOpen(true); }, 180);
  };
  // Live-sync preview with latest equipment state (Anzahl/Wartung edits in preview).
  const livePreviewItem = previewItem ? (equipment.find(p => p.id === previewItem.id) || previewItem) : null;

  const onSave = (eq) => {
    setEquipment(prev => {
      const exists = prev.find(p => p.id === eq.id);
      if (exists) return prev.map(p => p.id === eq.id ? eq : p);
      return [eq, ...prev];
    });
    toast(editing ? 'Gespeichert' : `„${eq.name}“ hinzugefügt`);
  };

  const doDelete = () => {
    const e = equipment.find(x => x.id === confirmId);
    setEquipment(prev => prev.filter(p => p.id !== confirmId));
    toast(`„${e ? e.name : 'Equipment'}“ gelöscht`);
    setConfirmId(null);
  };

  return (
    <div style={{ paddingBottom: 100 }}>
      <div style={{ padding: '8px 20px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div style={{ fontSize: 13, color: t.textSec, fontWeight: 500 }}>
            {area === 'equipment' ? `${equipment.length} Objekte` : 'Lieferpreis · Routen'}
          </div>
          <div style={{ fontSize: 32, fontWeight: 700, color: t.text, letterSpacing: -0.8, marginTop: 2 }}>
            {area === 'equipment' ? 'Equipment' : 'Logistik'}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          {area === 'equipment' ? (
            <Pressable onClick={openNew} scale={0.88}>
              <div style={{
                width: 38, height: 38, borderRadius: 19, background: t.solidBg,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: '0 4px 14px rgba(0,0,0,0.28)',
              }}>
                <Icon d={icons.plus} color={t.solidFg} size={20} sw={2.6}/>
              </div>
            </Pressable>
          ) : (
            <Pressable onClick={() => setLogistikSettingsOpen(true)} scale={0.88}>
              <div style={{ width: 38, height: 38, borderRadius: 19, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon d="M12 15a3 3 0 100-6 3 3 0 000 6zM19.4 15a1.7 1.7 0 00.3 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.8-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 11-4 0v-.1a1.7 1.7 0 00-1-1.5 1.7 1.7 0 00-1.8.3l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.8 1.7 1.7 0 00-1.5-1H3a2 2 0 110-4h.1a1.7 1.7 0 001.5-1 1.7 1.7 0 00-.3-1.8l-.1-.1a2 2 0 112.8-2.8l.1.1a1.7 1.7 0 001.8.3h0a1.7 1.7 0 001-1.5V3a2 2 0 114 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.8-.3l.1-.1a2 2 0 112.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.8v0a1.7 1.7 0 001.5 1H21a2 2 0 110 4h-.1a1.7 1.7 0 00-1.5 1z" color={t.text} size={18} sw={1.6}/>
              </div>
            </Pressable>
          )}
          <CompanyGear size={38} />
        </div>
      </div>

      {/* Sub-area switch — Equipment / Logistik */}
      <div style={{ padding: '14px 16px 0' }}>
        <div style={{ display: 'flex', padding: 3, borderRadius: 12, background: t.chipStrong }}>
          {[
            ['equipment', 'Equipment', IMG_ICONS.lager],
            ['logistik',  'Logistik',  IMG_ICONS.lieferwagen],
          ].map(([id, label, img]) => (
            <Pressable key={id} onClick={() => setArea(id)} scale={0.96} style={{ flex: 1 }}>
              <div style={{
                padding: '8px 0', textAlign: 'center', borderRadius: 9,
                background: area === id ? (t.dark ? '#48484A' : '#fff') : 'transparent',
                color: area === id ? t.text : t.textSec,
                fontSize: 13, fontWeight: 600,
                boxShadow: area === id ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              }}>
                {(() => {
                  const isActive = area === id;
                  const isLineArt = !!img.invertDark;
                  let filter = 'none';
                  if (isLineArt) {
                    const px = isActive ? 0.7 : 0.4;
                    const shadow = [
                      `drop-shadow(${px}px 0 0 #000)`,
                      `drop-shadow(-${px}px 0 0 #000)`,
                      `drop-shadow(0 ${px}px 0 #000)`,
                      `drop-shadow(0 -${px}px 0 #000)`,
                    ].join(' ');
                    filter = t.dark ? `${shadow} invert(1)` : shadow;
                  }
                  return (
                    <ImgIcon light={img.light} dark={img.dark} size={18}
                      style={{ opacity: isActive ? 1 : 0.6, filter }}/>
                  );
                })()}
                {label}
              </div>
            </Pressable>
          ))}
        </div>
      </div>

      {area === 'logistik' && (
        <ScreenLogistik
          rentals={rentals} setRentals={setRentals}
          logistik={logistik} setLogistik={setLogistik}
          equipment={equipment}
          toast={toast} go={go}
          embedded settingsOpen={logistikSettingsOpen} onSettingsClose={() => setLogistikSettingsOpen(false)}
        />
      )}

      {area === 'equipment' && <>

      {/* Utilization stats */}
      <UtilizationCard equipment={equipment} onSelect={openEdit}/>

      {/* Filter chips + manage categories */}
      <div style={{ padding: '14px 16px 0', display: 'flex', gap: 8, overflowX: 'auto', alignItems: 'center' }}>
        {filters.map(label => (
          <Pressable key={label} onClick={() => setFilter(label)} scale={0.94}>
            <div style={{
              padding: '7px 14px', borderRadius: 100, fontSize: 13, fontWeight: 600,
              background: filter === label ? t.solidBg : t.chip,
              color: filter === label ? t.solidFg : t.text, whiteSpace: 'nowrap',
            }}>{label}</div>
          </Pressable>
        ))}
        <Pressable onClick={() => setCatsOpen(true)} scale={0.9}>
          <div style={{
            width: 32, height: 32, borderRadius: 16, background: t.chip,
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>
            <Icon d={icons.edit} color={t.text} size={14} sw={2}/>
          </div>
        </Pressable>
      </div>

      {/* List */}
      <div style={{ padding: '14px 16px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
        {filtered.map(e => (
          <EqRow key={e.id} item={e} t={t} rentals={rentals}
            onOpen={() => openPreview(e)}
            onEdit={() => openEdit(e)}
            onDelete={() => setConfirmId(e.id)}/>
        ))}
        {filtered.length === 0 && (
          <Pressable onClick={openNew}>
            <div style={{
              textAlign: 'center', padding: '40px 20px', color: t.textSec, fontSize: 13,
              background: t.card, borderRadius: 16, border: '1px dashed ' + t.sep,
            }}>
              Keine Objekte.<br/>
              <span style={{ color: t.accent, fontWeight: 600 }}>+ Erstes Objekt anlegen</span>
            </div>
          </Pressable>
        )}
      </div>
      </>}

      <EqPreviewSheet open={previewOpen} onClose={() => setPreviewOpen(false)}
        item={livePreviewItem} rentals={rentals} setEquipment={setEquipment}
        onEdit={editFromPreview}
        onDelete={() => { setPreviewOpen(false); if (livePreviewItem) setConfirmId(livePreviewItem.id); }}/>

      <EquipmentSheet open={sheetOpen} onClose={() => setSheetOpen(false)} initial={editing} onSave={onSave} categories={categories} rentals={rentals}/>
      <CategoriesSheet open={catsOpen} onClose={() => setCatsOpen(false)} categories={categories} setCategories={setCategories} toast={toast} equipment={equipment}/>
      <Confirm open={!!confirmId} title="Equipment löschen?"
        message="Das Objekt wird dauerhaft entfernt."
        onCancel={() => setConfirmId(null)} onConfirm={doDelete}/>
    </div>
  );
}

Object.assign(window, { ScreenEquipment });
