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

// ─── Row: tap → preview, long-press → menu ───
// Grapheme-aware: returns the last visible character (keeps multi-codepoint emoji intact).
function lastGrapheme(str) {
  const s = String(str || '');
  if (!s) return '';
  try {
    if (typeof Intl !== 'undefined' && Intl.Segmenter) {
      const segs = [...new Intl.Segmenter().segment(s)];
      return segs.length ? segs[segs.length - 1].segment : '';
    }
  } catch (e) {}
  const cp = [...s];
  return cp[cp.length - 1] || '';
}
function EqRow({ item, t, rentals, onOpen, onEdit, onDelete, view = 'card', showIcons = true }) {
  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 (long-press)
  const [dd, setDd] = React.useState(false);    // three-dot dropdown

  const { total, verfuegbar: verf } = eqStock(item, rentals);
  const low = verf === 0 || (total > 0 && verf <= Math.max(1, Math.floor(total * 0.2)));

  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();
  };

  const compact = view === 'compact' || view === 'table';
  return (
    <div style={{ position: 'relative', borderRadius: compact ? 12 : 14 }}>
      <div ref={rowRef}
        onPointerDown={onPointerDown}
        onPointerMove={onPointerMove}
        onPointerUp={settle}
        onPointerCancel={cancelLong}
        style={{
          background: t.card, borderRadius: compact ? 12 : 14, padding: compact ? '10px 12px' : '12px 14px',
          display: 'flex', gap: compact ? 10 : 12, alignItems: 'center',
          boxShadow: t.shadowCard,
          border: compact ? `0.5px solid ${t.sep}` : 'none',
          touchAction: 'pan-y', cursor: 'pointer',
          position: 'relative', zIndex: 1, userSelect: 'none',
        }}>
        {showIcons && <EqAvatar item={item} size={compact ? 34 : 42} radius={compact ? 8 : 11}/>}
        {compact ? (
          <>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: t.text, letterSpacing: -0.2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.name}</div>
              <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.cat}</div>
            </div>
            <div style={{ textAlign: 'right', flexShrink: 0, fontVariantNumeric: 'tabular-nums', minWidth: 62 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: low ? t.orange : t.text }}>{verf}<span style={{ color: t.textSec, fontWeight: 600 }}>/{total}</span></div>
              <div style={{ fontSize: 10, fontWeight: 600, color: t.textSec, marginTop: 1 }}>frei</div>
            </div>
          </>
        ) : (
        <>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 14.5, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.name}</div>
          <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 2, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.cat}</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>
        <div style={{ textAlign: 'right', flexShrink: 0 }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: low ? t.orange : t.text, fontVariantNumeric: 'tabular-nums' }}>
            {verf}<span style={{ color: t.textSec, fontWeight: 600 }}>/{total}</span>
          </div>
          <div style={{ fontSize: 10, color: t.textSec, marginTop: 1 }}>verfügbar</div>
        </div>
        <div role="button" onPointerDown={(e) => e.stopPropagation()} onPointerUp={(e) => e.stopPropagation()}
          onClick={(e) => { e.stopPropagation(); setDd(m => !m); }}
          style={{ width: 28, height: 28, borderRadius: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', flexShrink: 0 }}>
          <Icon d="M12 5h.01M12 12h.01M12 19h.01" color={t.textSec} size={18} sw={2.4}/>
        </div>
        </>
        )}
      </div>

      {dd && (
        <>
          <div onClick={() => setDd(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }}/>
          <div style={{ position: 'absolute', right: 12, top: 46, zIndex: 41, background: t.sheetBg || t.card, borderRadius: 12, boxShadow: '0 8px 30px rgba(0,0,0,0.25)', overflow: 'hidden', minWidth: 140 }}>
            <Pressable onClick={() => { setDd(false); onEdit(); }} scale={0.98}>
              <div style={{ padding: '11px 16px', fontSize: 14, color: t.text, fontWeight: 500 }}>Bearbeiten</div>
            </Pressable>
            <div style={{ height: 0.5, background: t.sep }}/>
            <Pressable onClick={() => { setDd(false); onDelete(); }} scale={0.98}>
              <div style={{ padding: '11px 16px', fontSize: 14, color: t.red, fontWeight: 500 }}>Löschen</div>
            </Pressable>
          </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 setPrice = (v) => patch({ price: v === '' ? '' : Math.max(0, Number(v) || 0) });
  const maxRepair = Math.max(0, total - vermietet);
  const setRepair = (n) => patch({ repairQty: Math.max(0, Math.min(maxRepair, Number(n) || 0)) });

  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.85} disabled={disabled}>
      <div style={{ width: 34, height: 34, borderRadius: 17, background: sign > 0 ? t.solidBg : t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: disabled ? 0.4 : 1 }}>
        <Icon d={sign > 0 ? 'M12 5v14M5 12h14' : 'M5 12h14'} color={sign > 0 ? t.solidFg : t.text} size={15} 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: 'center', gap: 14 }}>
          <EqAvatar item={item} size={56} radius={14}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 19, fontWeight: 700, color: t.text, letterSpacing: -0.4, lineHeight: 1.15, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{item.name}</div>
            <div style={{ fontSize: 12.5, color: t.textSec, marginTop: 3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
              {item.cat}{item.sub ? ' · ' + item.sub : ''}{item.kind ? ` · ${item.kind}` : ''}
            </div>
          </div>
        </div>

        {/* Verfügbarkeit — Übersicht */}
        <div style={{ padding: '14px 24px 0' }}>
          <div style={{ background: t.card, borderRadius: 14, padding: 4, display: 'flex', alignItems: 'stretch', boxShadow: t.shadowCard }}>
            <Cell label="Verfügbar" value={verf} strong accent={verf === 0 ? t.red : t.green}/>
            <div style={{ width: 0.5, background: t.sep, margin: '10px 0' }}/>
            <Cell label="Vermietet" value={vermietet}/>
            <div style={{ width: 0.5, background: t.sep, margin: '10px 0' }}/>
            <Cell label="In Reparatur" value={reparatur}/>
          </div>
        </div>

        {/* Schnell anpassen — Tagespreis · Anzahl · Reparatur ohne vollen Bearbeiten-Modus */}
        <div style={{ padding: '18px 24px 0' }}>
          {/* Schnell anpassen — als Liste (Label links, Stepper rechts) */}
          <div style={{ background: t.cardAlt, borderRadius: 12, overflow: 'hidden' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '9px 14px' }}>
              <div style={{ fontSize: 13.5, color: t.text, fontWeight: 600 }}>Anzahl im Inventar</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: 22, textAlign: 'center', fontSize: 17, fontWeight: 700, color: t.text, fontVariantNumeric: 'tabular-nums' }}>{item.qty || 1}</div>
                <StepBtn sign={1} onClick={() => setQty((item.qty || 1) + 1)}/>
              </div>
            </div>
            <div style={{ height: 0.5, background: t.sep, marginLeft: 14 }}/>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '9px 14px' }}>
              <div style={{ fontSize: 13.5, color: t.text, fontWeight: 600 }}>Für Reparatur</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <StepBtn sign={-1} disabled={reparatur <= 0} onClick={() => setRepair(reparatur - 1)}/>
                <div style={{ minWidth: 22, textAlign: 'center', fontSize: 17, fontWeight: 700, color: t.text, fontVariantNumeric: 'tabular-nums' }}>{reparatur}</div>
                <StepBtn sign={1} disabled={reparatur >= maxRepair} onClick={() => setRepair(reparatur + 1)}/>
              </div>
            </div>
            <div style={{ height: 0.5, background: t.sep, marginLeft: 14 }}/>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '9px 14px' }}>
              <div style={{ fontSize: 13.5, color: t.text, fontWeight: 600 }}>Tagespreis €</div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <StepBtn sign={-1} disabled={(Number(item.price) || 0) <= 0} onClick={() => setPrice((Number(item.price) || 0) - 5)}/>
                <input
                  type="number" inputMode="decimal" min="0" value={item.price}
                  onChange={(e) => setPrice(e.target.value)}
                  onBlur={(e) => setPrice(String(Math.max(0, Number(e.target.value) || 0)))}
                  style={{ width: 64, textAlign: 'center', padding: '6px 4px', borderRadius: 10, border: `0.5px solid ${t.inputBorder}`, background: t.inputBg, fontSize: 17, fontWeight: 700, color: t.text, fontVariantNumeric: 'tabular-nums', outline: 'none', fontFamily: 'inherit', MozAppearance: 'textfield' }}/>
                <StepBtn sign={1} onClick={() => setPrice((Number(item.price) || 0) + 5)}/>
              </div>
            </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: '9px 0', textAlign: 'center', borderRadius: 10, background: 'transparent', color: t.text, fontSize: 12.5, fontWeight: 600, border: `1px dashed ${t.textTer}`, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5 }}>
            <Icon d={icons.plus} color={t.text} size={13} sw={2.6}/>
            Wartung / Defekt / TÜV erfassen
          </div>
        </Pressable>
      )}
    </div>
  );
}

// ─── Edit / Add equipment sheet ─────────────────────────────
function EquipmentSheet({ open, onClose, initial, onSave, categories, setCategories, rentals = [] }) {
  const t = useTheme();
  const isEdit = !!initial;
  const blank = { id: '', name: '', cat: '', sub: '', kind: '',
                  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 [newCat, setNewCat] = useState('');
  const [addingCat, setAddingCat] = useState(false);
  const fileRef = useRef(null);

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

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const commitNewCat = () => {
    const c = newCat.trim();
    if (!c) { setAddingCat(false); return; }
    if (setCategories && !categories.includes(c)) setCategories(prev => [...prev, c]);
    set('kind', c);
    setNewCat(''); setAddingCat(false);
  };
  const valid = form.name.trim() && form.cat.trim();

  // Reusable +/- stepper (matches the Reparatur stepper). `editable` lets the
  // user tap the number and type an exact value, still nudgeable with +/-.
  const Stepper = ({ value, onChange, min = 0, step = 1, editable = false, suffix = '' }) => {
    const num = Number(value) || 0;
    const Btn = ({ sign, disabled }) => (
      <Pressable onClick={() => !disabled && onChange(String(Math.max(min, num + sign * step)))} scale={0.85} disabled={disabled}>
        <div style={{
          width: 34, height: 34, borderRadius: 17, background: sign > 0 ? t.solidBg : t.chip,
          display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: disabled ? 0.4 : 1,
        }}>
          <Icon d={sign > 0 ? 'M12 5v14M5 12h14' : 'M5 12h14'} color={sign > 0 ? t.solidFg : t.text} size={15} sw={2.4}/>
        </div>
      </Pressable>
    );
    return (
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <Btn sign={-1} disabled={num <= min}/>
        {editable ? (
          <input
            type="number" inputMode="decimal" min={min} value={value}
            onChange={(e) => onChange(e.target.value)}
            onBlur={(e) => onChange(String(Math.max(min, Number(e.target.value) || 0)))}
            style={{
              width: 64, textAlign: 'center', padding: '7px 4px', borderRadius: 10,
              border: `0.5px solid ${t.inputBorder}`, background: t.inputBg,
              fontSize: 17, fontWeight: 700, color: t.text, fontVariantNumeric: 'tabular-nums',
              outline: 'none', fontFamily: 'inherit', MozAppearance: 'textfield',
            }}/>
        ) : (
          <div style={{ minWidth: 40, textAlign: 'center', fontSize: 17, fontWeight: 700, color: t.text, fontVariantNumeric: 'tabular-nums' }}>{num}{suffix}</div>
        )}
        <Btn sign={1} disabled={false}/>
      </div>
    );
  };

  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>

        {/* Icon — Foto oder Emoji, kompakt ganz oben (wie Zubehör) */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 10, marginBottom: 4 }}>
          <div style={{ position: 'relative', flexShrink: 0 }}>
            <EqAvatar item={form} size={64} 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>
          <div style={{ flex: 1, minWidth: 0 }}>
            <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: '10px 14px', borderRadius: 12, background: t.accentSoft, color: t.accent, fontSize: 13.5, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
                <Icon d={icons.camera} color={t.accent} size={16} sw={1.8}/>
                {uploading ? 'Lädt…' : (form.photo ? 'Foto ändern' : 'Foto hochladen')}
              </div>
            </Pressable>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 }}>
              <input value={form.emoji || ''}
                onChange={(e) => setForm(f => ({ ...f, emoji: e.target.value, photo: e.target.value ? '' : f.photo }))}
                placeholder="oder Emoji / Buchstabe …" maxLength={8}
                style={{ ...inp(t), flex: 1, fontFamily: 'inherit' }}/>
              {form.emoji && (
                <Pressable onClick={() => setForm(f => ({ ...f, emoji: '' }))} scale={0.85}>
                  <div style={{ padding: '9px 12px', borderRadius: 10, background: t.chip, fontSize: 12, fontWeight: 600, color: t.text }}>Zurück</div>
                </Pressable>
              )}
            </div>
          </div>
        </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="Kategorie">
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, alignItems: 'center' }}>
            {categories.map(k => {
              const on = form.kind === k;
              return (
                <Pressable key={k} onClick={() => set('kind', k)} scale={0.95}>
                  <div style={{ padding: '8px 13px', borderRadius: 100, fontSize: 13, fontWeight: 600, background: on ? t.solidBg : t.chip, color: on ? t.solidFg : t.text }}>{k}</div>
                </Pressable>
              );
            })}
            {addingCat ? (
              <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                <input value={newCat} onChange={e => setNewCat(e.target.value)} autoFocus
                  onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); commitNewCat(); } }}
                  placeholder="Neue Kategorie" style={{ ...inp(t), width: 150, padding: '7px 11px', fontSize: 13 }}/>
                <Pressable onClick={commitNewCat} scale={0.9}>
                  <div style={{ width: 32, height: 32, borderRadius: 16, background: t.solidBg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <Icon d="M5 12l5 5L20 7" color={t.solidFg} size={15} sw={2.6}/>
                  </div>
                </Pressable>
              </div>
            ) : (
              <Pressable onClick={() => { setAddingCat(true); setNewCat(''); }} scale={0.9}>
                <div style={{ padding: '8px 12px', borderRadius: 100, fontSize: 13, fontWeight: 600, background: t.chip, color: t.textSec, display: 'flex', alignItems: 'center', gap: 5, border: `1px dashed ${t.sep}` }}>
                  <Icon d={icons.edit} color={t.textSec} size={13} sw={2}/> Kategorie
                </div>
              </Pressable>
            )}
          </div>
          {categories.length === 0 && !addingCat && null}
        </FormGroup>

        <FormGroup label="Preis & Anzahl">
          <div style={{ background: t.cardAlt, borderRadius: 12, overflow: 'hidden' }}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '7px 14px' }}>
              <div style={{ fontSize: 13.5, color: t.text, fontWeight: 600 }}>Tagespreis €</div>
              <Stepper value={form.price} onChange={(v) => set('price', v)} min={0} step={5} editable/>
            </div>
            <div style={{ height: 0.5, background: t.sep, marginLeft: 14 }}/>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '7px 14px' }}>
              <div style={{ fontSize: 13.5, color: t.text, fontWeight: 600 }}>Anzahl</div>
              <Stepper value={form.qty} onChange={(v) => set('qty', v)} min={1} step={1} editable/>
            </div>
            <div style={{ height: 0.5, background: t.sep, marginLeft: 14 }}/>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '7px 14px' }}>
              <div style={{ fontSize: 13.5, color: t.text, fontWeight: 600 }}>Einsätze</div>
              <Stepper value={form.uses} onChange={(v) => set('uses', v)} min={0} step={1} editable/>
            </div>
            <div style={{ height: 0.5, background: t.sep, marginLeft: 14 }}/>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '7px 14px' }}>
              <div style={{ fontSize: 13.5, color: t.text, fontWeight: 600 }}>In Reparatur</div>
              <Stepper value={form.repairQty} onChange={(v) => set('repairQty', Math.min(Number(v) || 0, Number(form.qty) || 1))} min={0} step={1} editable/>
            </div>
          </div>
        </FormGroup>

        {/* Verfügbarkeit & Reparatur werden in der Detail-/Info-Ansicht gepflegt,
           nicht im Bearbeiten-Modus. */}

        <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: '#FF3B30', 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, accessories = [], setAccessories, accCats = [], setAccCats, categories, setCategories, rentals = [], setRentals, logistik, setLogistik, tabSettings = {}, setTabSettings, initialArea = 'equipment', toast, go }) {
  const t = useTheme();
  const [area, setArea] = useState(initialArea);
  const [zubNonce, setZubNonce] = useState(0);
  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: '18px 22px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 34, fontWeight: 700, color: t.text, letterSpacing: -1, lineHeight: 1.05 }}>
            {area === 'equipment' ? 'Equipment' : area === 'zubehoer' ? 'Zubehör' : 'Logistik'}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          {area === 'equipment' ? (
            <Pressable onClick={openNew} scale={0.9}>
              <div style={{ width: 40, height: 40, borderRadius: 999, background: t.solidBg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon d={icons.plus} color={t.solidFg} size={19} sw={2.4}/>
              </div>
            </Pressable>
          ) : area === 'zubehoer' ? (
            <Pressable onClick={() => setZubNonce(n => n + 1)} scale={0.9}>
              <div style={{ width: 40, height: 40, borderRadius: 999, background: t.solidBg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon d={icons.plus} color={t.solidFg} size={19} sw={2.4}/>
              </div>
            </Pressable>
          ) : null}
          <CompanyGear size={40} />
        </div>
      </div>

      {/* Sub-area switch — underline tabs (AudioFlow-Stil) */}
      <div style={{ padding: '10px 20px 0' }}>
        <div style={{ display: 'flex', gap: 26, borderBottom: `1px solid ${t.sep}` }}>
          {[
            ['equipment', 'Equipment', 'M3 7l9-4 9 4v10l-9 4-9-4V7zM3 7l9 4 9-4M12 11v10'],
            ['zubehoer',  'Zubehör',   'M20.5 7.3l-8-4.5a1 1 0 00-1 0l-8 4.5A1 1 0 003 8.2v7.6a1 1 0 00.5.9l8 4.5a1 1 0 001 0l8-4.5a1 1 0 00.5-.9V8.2a1 1 0 00-.5-.9zM3.3 7.9l8.7 4.9 8.7-4.9M12 22v-9.2'],
            ['logistik',  'Logistik',  'M1 3h13v10H1zM14 8h4l3 3v2h-7zM5.5 18.5a1.5 1.5 0 11-3 0 1.5 1.5 0 013 0zM19.5 18.5a1.5 1.5 0 11-3 0 1.5 1.5 0 013 0z'],
          ].map(([id, label, d]) => {
            const on = area === id;
            return (
              <Pressable key={id} onClick={() => setArea(id)} scale={0.97}>
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 7, padding: '4px 2px 12px',
                  borderBottom: `2px solid ${on ? t.text : 'transparent'}`, marginBottom: -1,
                }}>
                  <span style={{ fontSize: 14.5, fontWeight: on ? 700 : 500, letterSpacing: -0.2, color: on ? t.text : t.textSec }}>{label}</span>
                </div>
              </Pressable>
            );
          })}
        </div>
      </div>

      {area === 'zubehoer' && (
        <ScreenZubehoer
          accessories={accessories} setAccessories={setAccessories}
          accCats={accCats} setAccCats={setAccCats}
          equipment={equipment} rentals={rentals} toast={toast} newNonce={zubNonce}
          view={(tabSettings.zubehoer || {}).view || 'card'} showIcons={(tabSettings.zubehoer || {}).showIcons !== false}
        />
      )}

      {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 */}
      <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>
        ))}
      </div>

      {/* List */}
      {(() => {
        const eqCfg = tabSettings.equipment || {};
        const eqView = eqCfg.view || 'card';
        const eqIcons = eqCfg.showIcons !== false;
        const setEqCfg = (patch) => setTabSettings && setTabSettings((prev) => ({ ...prev, equipment: { ...(prev.equipment || {}), ...patch } }));
        const VIEWS = [['card', 'Karten'], ['compact', 'Kompakt'], ['table', 'Tabelle']];
        return (
        <>
        <div style={{ padding: '12px 16px 0', display: 'flex', flexDirection: 'column', gap: eqView === 'card' ? 10 : 6 }}>
          {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>
          ) : filter === 'Alle' ? (
            (() => {
              const groups = {};
              for (const e of filtered) { const k = e.kind || 'Ohne Kategorie'; (groups[k] = groups[k] || []).push(e); }
              const groupOrder = (() => {
                const usedKinds = [...new Set(filtered.map(e => e.kind).filter(Boolean))];
                const ordered = [...categories.filter(c => groups[c]), ...usedKinds.filter(k => !categories.includes(k) && groups[k])];
                return [...ordered, ...(groups['Ohne Kategorie'] ? ['Ohne Kategorie'] : [])];
              })();
              return groupOrder.map(cat => (
                <div key={cat} style={{ marginBottom: 8 }}>
                  <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.6, marginBottom: 8, paddingLeft: 2 }}>{cat}</div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: eqView === 'card' ? 10 : 6 }}>
                    {groups[cat].map(e => (
                      <EqRow key={e.id} item={e} t={t} rentals={rentals} view={eqView} showIcons={eqIcons}
                        onOpen={() => openPreview(e)} onEdit={() => openEdit(e)} onDelete={() => setConfirmId(e.id)}/>
                    ))}
                  </div>
                </div>
              ));
            })()
          ) : (
            filtered.map(e => (
              <EqRow key={e.id} item={e} t={t} rentals={rentals} view={eqView} showIcons={eqIcons}
                onOpen={() => openPreview(e)} onEdit={() => openEdit(e)} onDelete={() => setConfirmId(e.id)}/>
            ))
          )}
        </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} setCategories={setCategories} 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 });
