// Desktop Equipment — grid of cards + detail pane + add/edit dialog.

const EQ_GLYPHS = ['speaker', 'mic', 'mixer', 'trailer', 'light', 'cable', 'case'];
const MAINT_TYPES = ['service', 'repair', 'defect', 'tuev'];
const maintMeta = (ty) => ({
  service: { icon: '🧰', label: 'Wartung', color: '#34C759' },
  repair: { icon: '🔧', label: 'Reparatur', color: '#FF9500' },
  defect: { icon: '⚠️', label: 'Defekt', color: '#FF3B30' },
  tuev: { icon: '📋', label: 'TÜV / HU', color: '#5856D6' }
})[ty] || { icon: '•', label: ty, color: '#8E8E93' };

// ── Add / Edit equipment ──
function EquipmentSheet({ open, onClose, initial, categories, rentals = [], onSave }) {
  const t = useTheme();
  const isEdit = !!(initial && initial.id);
  const blank = { id: '', name: '', cat: '', sub: '', kind: categories[0] || 'Tontechnik', repairQty: 0, price: 0, qty: 1, ic: 'speaker', emoji: '', photo: '', accessories: [], maint: [] };
  const [form, setForm] = useState(blank);
  const [accInput, setAccInput] = useState('');
  const fileRef = useRef(null);
  useEffect(() => {if (open) {setForm(initial ? { ...blank, ...initial } : blank);setAccInput('');}}, [open, initial]);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const valid = form.name.trim() && form.cat.trim();
  const addAcc = () => {const v = accInput.trim();if (!v) return;set('accessories', [...(form.accessories || []), v]);setAccInput('');};
  const onPickPhoto = (ev) => {
    const file = ev.target.files && ev.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => setForm((f) => ({ ...f, photo: reader.result }));
    reader.readAsDataURL(file);
    ev.target.value = '';
  };
  // Live availability tiles (uses current form qty + repairQty + live rentals for active count)
  const liveTotal = Math.max(1, Number(form.qty) || 1);
  const liveRepair = Math.max(0, Math.min(liveTotal, Number(form.repairQty) || 0));
  const liveActive = isEdit ? rentals.filter((r) => r && r.status === 'aktiv' && (r.equipmentId === form.id || (Array.isArray(r.items) && r.items.some((it) => it && it.equipmentId === form.id)))).reduce((s, r) => s + (Number(r.quantity) || 1), 0) : 0;
  const liveAvail = Math.max(0, liveTotal - liveActive - liveRepair);
  const save = () => {if (!valid) return;onSave({ ...form, id: form.id || 'eq-' + Date.now(), price: Number(form.price) || 0, qty: liveTotal, repairQty: liveRepair });onClose();};

  return (
    <Sheet open={open} onClose={onClose} width={600}>
      <div style={{ padding: '4px 28px 26px' }}>
        <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: 3 }}>{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>

        <div style={{ display: 'flex', gap: 16, marginTop: 18, alignItems: 'flex-start' }}>
          <div style={{ flexShrink: 0, textAlign: 'center' }}>
            <EqAvatar item={form} size={84} radius={18} />
          </div>
          <div style={{ flex: 1 }}>
            <Field label="Bezeichnung" required style={{ marginTop: 0 }}><TextInput value={form.name} onChange={(e) => set('name', e.target.value)} placeholder="z.B. JBL PRX-815" /></Field>
            <Field label="Kategorie / Bauart" required><TextInput value={form.cat} onChange={(e) => set('cat', e.target.value)} placeholder="z.B. Aktivlautsprecher" /></Field>
          </div>
        </div>

        <Field label="Spezifikation"><TextInput value={form.sub} onChange={(e) => set('sub', e.target.value)} placeholder="z.B. 1.300 W · 12″ · Bluetooth" /></Field>
        <Field 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></Field>

        {/* ── Bild / Symbol ── */}
        <Field label="Bild / Symbol">
          <div style={{ display: 'flex', gap: 12, alignItems: 'stretch' }}>
            <div style={{ width: 70, height: 70, borderRadius: 14, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, overflow: 'hidden' }}>
              <EqAvatar item={form} size={70} radius={14} />
            </div>
            <Pressable onClick={() => fileRef.current && fileRef.current.click()} scale={0.98} style={{ flex: 1 }}>
              <div style={{ height: '100%', minHeight: 70, borderRadius: 14, background: t.accentSoft, color: t.accent, fontSize: 14, fontWeight: 600, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
                <Icon d="M3 7h3l2-3h8l2 3h3v13H3V7zM12 11a4 4 0 100 8 4 4 0 000-8z" color={t.accent} size={17} sw={1.8} />
                {form.photo ? 'Foto ersetzen' : 'Eigenes Foto hochladen'}
              </div>
            </Pressable>
            {form.photo && <Pressable onClick={() => set('photo', '')} scale={0.94}>
              <div title="Foto entfernen" style={{ width: 36, height: 70, borderRadius: 12, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon d="M6 6l12 12M18 6L6 18" color={t.textSec} size={14} sw={2.2} />
              </div>
            </Pressable>}
            <input ref={fileRef} type="file" accept="image/*" onChange={onPickPhoto} style={{ display: 'none' }} />
          </div>
          <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 7 }}>Eigenes Bild hochladen — oder unten ein Symbol/Emoji wählen.</div>
        </Field>

        <Field label="Symbole"><div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {EQ_GLYPHS.map((g) => {const sel = !form.photo && !form.emoji && form.ic === g;return (
                <Pressable key={g} onClick={() => set('ic', g)} scale={0.9}><div style={{ width: 44, height: 44, borderRadius: 11, 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={22} color={sel ? t.accent : t.dark ? 'rgba(235,235,245,0.85)' : '#1c1c1e'} /></div></Pressable>);
            })}
        </div></Field>

        <Field label="Eigenes Emoji">
          <div style={{ display: 'flex', gap: 10, alignItems: 'center' }}>
            <div style={{ width: 44, height: 44, borderRadius: 11, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, fontSize: 22 }}>{form.emoji || <span style={{ color: t.textTer, fontSize: 18, fontWeight: 600 }}>?</span>}</div>
            <TextInput value={form.emoji} onChange={(e) => set('emoji', e.target.value.slice(0, 4))} placeholder="Emoji eingeben …" />
          </div>
        </Field>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Field label="Tagespreis €"><TextInput type="number" value={form.price} onChange={(e) => set('price', e.target.value)} /></Field>
          <Field label="Anzahl"><TextInput type="number" value={form.qty} onChange={(e) => set('qty', e.target.value)} /></Field>
        </div>

        {/* ── Verfügbarkeit (live) ── */}
        <Field label="Verfügbarkeit">
          <div style={{ background: t.cardAlt, borderRadius: 14, padding: '14px 6px', display: 'grid', gridTemplateColumns: 'repeat(3,1fr)' }}>
            {[['Verfügbar', liveAvail, liveAvail > 0 ? t.green : t.textTer], ['Vermietet', liveActive, liveActive > 0 ? t.accent : t.textTer], ['In Reparatur', liveRepair, liveRepair > 0 ? t.orange : t.textTer]].map(([l, v, c]) =>
              <div key={l} style={{ textAlign: 'center', padding: '2px 4px' }}>
                <div style={{ fontSize: 26, fontWeight: 700, color: c, letterSpacing: -0.5, ...NUMS }}>{v}</div>
                <div style={{ fontSize: 11.5, color: t.textSec, fontWeight: 500, marginTop: 2 }}>{l}</div>
              </div>
            )}
          </div>
        </Field>

        {/* ── Repair stepper ── */}
        <div style={{ marginTop: 16, display: 'flex', alignItems: 'center', gap: 14, background: t.cardAlt, borderRadius: 14, padding: '12px 16px' }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>Für Reparatur / Wartung rausnehmen</div>
            <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 2 }}>Reduziert automatisch die verfügbare Menge.</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <Pressable onClick={() => set('repairQty', Math.max(0, liveRepair - 1))} scale={0.9}>
              <div style={{ width: 32, height: 32, borderRadius: 10, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: liveRepair === 0 ? 0.4 : 1 }}>
                <Icon d="M5 12h14" color={t.text} size={15} sw={2.4} />
              </div>
            </Pressable>
            <div style={{ minWidth: 28, textAlign: 'center', fontSize: 18, fontWeight: 700, color: t.text, ...NUMS }}>{liveRepair}</div>
            <Pressable onClick={() => set('repairQty', Math.min(liveTotal, liveRepair + 1))} scale={0.9}>
              <div style={{ width: 32, height: 32, borderRadius: 10, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: liveRepair >= liveTotal ? 0.4 : 1 }}>
                <Icon d="M12 5v14M5 12h14" color={t.text} size={15} sw={2.4} />
              </div>
            </Pressable>
          </div>
        </div>

        <Field label="Zubehör">
          <div style={{ display: 'flex', gap: 8 }}>
            <TextInput value={accInput} onChange={(e) => setAccInput(e.target.value)} onKeyDown={(e) => {if (e.key === 'Enter') {e.preventDefault();addAcc();}}} placeholder="z.B. Stromkabel 5m" />
            <Button variant="soft" onClick={addAcc}>Hinzufügen</Button>
          </div>
          {form.accessories && form.accessories.length > 0 &&
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 10 }}>
              {form.accessories.map((a, i) =>
            <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 600, color: t.text, padding: '5px 8px 5px 11px', borderRadius: 8, background: t.chip }}>{a}
                  <Pressable onClick={() => set('accessories', form.accessories.filter((_, j) => j !== i))} scale={0.8}><Icon d="M6 6l12 12M18 6L6 18" color={t.textSec} size={12} sw={2.2} /></Pressable>
                </span>
            )}
            </div>
          }
        </Field>

        <Pressable onClick={save} scale={0.98} style={{ marginTop: 20 }}>
          <div style={{ padding: '14px 0', textAlign: 'center', borderRadius: 12, background: valid ? t.solidBg : t.chip, color: valid ? t.solidFg : t.textTer, fontSize: 15, fontWeight: 700, boxShadow: valid ? '0 6px 16px rgba(0,0,0,0.22)' : 'none' }}>{isEdit ? 'Speichern' : 'Equipment anlegen'}</div>
        </Pressable>
      </div>
    </Sheet>);

}

// ── Detail pane ──
function EquipmentDetail({ item, rentals, equipment, categories, onEdit, onDelete, onAddMaint, onToggleMaint, onRemoveMaint, onUpdateRepair, go }) {
  const t = useTheme();
  const toast = useToast();
  const e = item;

  const util = eqUtil(e, rentals, equipment);
  const related = rentals.filter((r) => r.equipmentId === e.id || (Array.isArray(r.items) && r.items.some((it) => it && it.equipmentId === e.id))).sort((a, b) => b.start.localeCompare(a.start));
  const uses = related.length;
  const earned = related.filter((r) => r.paymentStatus === 'bezahlt').reduce((s, r) => s + rentalTotal(r), 0);

  const total = Math.max(1, Number(e.qty) || 1);
  const repairQty = Math.max(0, Math.min(total, Number(e.repairQty) || 0));
  const activeQty = rentals.filter((r) => r && r.status === 'aktiv' && (r.equipmentId === e.id || (Array.isArray(r.items) && r.items.some((it) => it && it.equipmentId === e.id)))).reduce((s, r) => s + (Number(r.quantity) || 1), 0);
  const availQty = Math.max(0, total - activeQty - repairQty);

  const [maintOpen, setMaintOpen] = useState(false);
  const [draft, setDraft] = useState({ type: 'service', title: '', date: todayISO(), note: '' });

  // ── small atoms ──
  const Section = ({ label, action, children, top = 22 }) => (
    <div style={{ marginTop: top }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 8 }}>
        <div style={{ fontSize: 11, fontWeight: 700, color: t.textSec, textTransform: 'uppercase', letterSpacing: 0.5 }}>{label}</div>
        {action}
      </div>
      {children}
    </div>
  );

  // KPI tile (compact)
  const KPI = ({ label, value, color, sub }) => (
    <div style={{ flex: 1, padding: '11px 14px' }}>
      <div style={{ fontSize: 10.5, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.4 }}>{label}</div>
      <div style={{ fontSize: 22, fontWeight: 700, color: color || t.text, marginTop: 4, letterSpacing: -0.4, ...NUMS }}>{value}</div>
      {sub && <div style={{ fontSize: 10.5, color: t.textSec, marginTop: 2 }}>{sub}</div>}
    </div>
  );

  // Info row with icon chip (matches rentals detail pattern)
  const InfoRow = ({ icon, label, value, isLast }) => (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 0', borderBottom: isLast ? 'none' : `0.5px solid ${t.sep}` }}>
      <div style={{ width: 22, height: 22, borderRadius: 6, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
        <Icon d={icon} color={t.textSec} size={12} sw={1.8}/>
      </div>
      <div style={{ fontSize: 12, color: t.textSec, fontWeight: 500, width: 110, flexShrink: 0 }}>{label}</div>
      <div style={{ flex: 1, minWidth: 0, fontSize: 13.5, color: t.text, fontWeight: 600, textAlign: 'right' }}>{value || <span style={{ color: t.textTer, fontWeight: 500 }}>–</span>}</div>
    </div>
  );

  return (
    <Scroll padding={0}>
      <div style={{ padding: '24px 28px 32px' }}>
        {/* ── Header ── */}
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
          <EqAvatar item={e} size={60} radius={15} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 22, fontWeight: 700, color: t.text, letterSpacing: -0.5 }}>{e.name}</div>
            <div style={{ fontSize: 13, color: t.textSec, marginTop: 3 }}>{e.cat}{e.sub ? ' · ' + e.sub : ''}</div>
            <div style={{ display: 'flex', gap: 6, marginTop: 9 }}>
              <Tag color={t.text} soft>{e.kind}</Tag>
              <Tag color={t.text} soft>{e.price} €/Tag</Tag>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
            <Button variant="soft" size="sm" icon={icons.edit} onClick={onEdit}>Bearbeiten</Button>
            <IconBtn icon={icons.trash} color={t.red} onClick={onDelete} title="Löschen" />
          </div>
        </div>

        {/* ── KPI strip — 4 compact tiles incl. embedded Buchungsanteil ── */}
        <div style={{ marginTop: 18, display: 'flex', background: t.cardAlt, borderRadius: 12, border: `0.5px solid ${t.sep}`, overflow: 'hidden' }}>
          <KPI label="Verfügbar"  value={availQty}  color={availQty > 0 ? t.green : t.textTer} sub={`von ${total}`}/>
          <div style={{ width: 0.5, background: t.sep }}/>
          <KPI label="Vermietet"  value={activeQty} color={activeQty > 0 ? t.accent : t.textTer} sub="aktiv"/>
          <div style={{ width: 0.5, background: t.sep }}/>
          <KPI label="Reparatur"  value={repairQty} color={repairQty > 0 ? t.orange : t.textTer} sub="rausgenommen"/>
          <div style={{ width: 0.5, background: t.sep }}/>
          <div style={{ flex: 1, padding: '11px 14px' }}>
            <div style={{ fontSize: 10.5, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.4 }}>Auslastung</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginTop: 4 }}>
              <div style={{ fontSize: 22, fontWeight: 700, color: t.text, letterSpacing: -0.4, ...NUMS }}>{util}</div>
              <div style={{ fontSize: 13, fontWeight: 600, color: t.textSec, ...NUMS }}>%</div>
            </div>
            <div style={{ height: 3, borderRadius: 2, background: t.chipStrong, overflow: 'hidden', marginTop: 5 }}>
              <div style={{ width: `${util}%`, height: '100%', background: t.accent }} />
            </div>
          </div>
        </div>

        {/* ── Details card ── */}
        <Section label="Details">
          <div style={{ background: t.card, borderRadius: 12, border: `0.5px solid ${t.sep}`, padding: '0 16px' }}>
            <InfoRow icon={icons.bolt}  label="Spezifikation" value={e.sub}/>
            <InfoRow icon={icons.truck} label="Typ"           value={e.kind}/>
            <InfoRow icon={icons.euro}  label="Tagespreis"    value={`${e.price} €`}/>
            <InfoRow icon={icons.doc}   label="Anzahl"        value={total}/>
            <InfoRow icon={icons.refresh} label="Einsätze"    value={e.uses == null ? uses : e.uses} isLast/>
          </div>
        </Section>

        {/* ── Reparatur Stepper (compact inline) ── */}
        <Section label="Reparatur / Wartung" top={18}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, background: t.cardAlt, borderRadius: 12, padding: '10px 14px', border: `0.5px solid ${t.sep}` }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: t.text }}>Für Reparatur rausnehmen</div>
              <div style={{ fontSize: 11, color: t.textSec, marginTop: 2 }}>Reduziert die verfügbare Menge automatisch.</div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <Pressable onClick={() => onUpdateRepair(Math.max(0, repairQty - 1))} scale={0.9}>
                <div style={{ width: 28, height: 28, borderRadius: 9, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: repairQty === 0 ? 0.4 : 1 }}>
                  <Icon d="M5 12h14" color={t.text} size={13} sw={2.4}/>
                </div>
              </Pressable>
              <div style={{ minWidth: 22, textAlign: 'center', fontSize: 16, fontWeight: 700, color: t.text, ...NUMS }}>{repairQty}</div>
              <Pressable onClick={() => onUpdateRepair(Math.min(total, repairQty + 1))} scale={0.9}>
                <div style={{ width: 28, height: 28, borderRadius: 9, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: repairQty >= total ? 0.4 : 1 }}>
                  <Icon d="M12 5v14M5 12h14" color={t.text} size={13} sw={2.4}/>
                </div>
              </Pressable>
            </div>
          </div>
        </Section>

        {/* ── Wartung · TÜV · Defekte ── */}
        <Section label="Wartung · TÜV · Defekte" action={<Button variant="soft" size="sm" icon={icons.plus} onClick={() => setMaintOpen((v) => !v)}>Eintrag</Button>}>
          {maintOpen &&
            <div style={{ background: t.cardAlt, borderRadius: 12, padding: 12, marginBottom: 8, border: `0.5px solid ${t.sep}` }}>
              <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: '5px 10px', borderRadius: 8, fontSize: 11.5, fontWeight: 600, background: sel ? mm.color : t.chip, color: sel ? '#fff' : t.text }}>{mm.icon} {mm.label}</div></Pressable>);
                })}
              </div>
              <TextInput value={draft.title} onChange={(ev) => setDraft((d) => ({ ...d, title: ev.target.value }))} placeholder="z.B. Nächster TÜV / HU" />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, marginTop: 8 }}>
                <TextInput type="date" value={draft.date} onChange={(ev) => setDraft((d) => ({ ...d, date: ev.target.value }))} />
                <TextInput value={draft.note} onChange={(ev) => setDraft((d) => ({ ...d, note: ev.target.value }))} placeholder="Notiz" />
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
                <Button variant="primary" onClick={() => { if (!draft.title.trim()) return; onAddMaint({ id: 'm-' + Date.now(), done: false, ...draft }); setDraft({ type: 'service', title: '', date: todayISO(), note: '' }); setMaintOpen(false); toast('Eintrag hinzugefügt'); }} style={{ flex: 1, justifyContent: 'center' }}>Hinzufügen</Button>
              </div>
            </div>
          }
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {(!e.maint || e.maint.length === 0) && !maintOpen && <div style={{ fontSize: 12, color: t.textSec, padding: '4px 0' }}>Keine Einträge.</div>}
            {(e.maint || []).map((m) => { const mm = maintMeta(m.type); return (
              <div key={m.id} style={{ background: t.cardAlt, borderRadius: 10, padding: '9px 11px', display: 'flex', alignItems: 'center', gap: 10, border: `0.5px solid ${t.sep}` }}>
                <Pressable onClick={() => onToggleMaint(m.id)} scale={0.85}><div style={{ width: 20, height: 20, borderRadius: 10, 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="11" height="11" 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 }}><div style={{ fontSize: 12.5, fontWeight: 600, color: m.done ? t.textTer : t.text, textDecoration: m.done ? 'line-through' : 'none' }}>{mm.icon} {m.title}</div><div style={{ fontSize: 10.5, color: t.textSec, marginTop: 1 }}>{mm.label} · {fmtDateDE(m.date)}{m.note ? ' · ' + m.note : ''}</div></div>
                <Pressable onClick={() => onRemoveMaint(m.id)} scale={0.8}><div style={{ width: 22, height: 22, borderRadius: 11, background: t.redSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon d="M6 6l12 12M18 6L6 18" color={t.red} size={11} sw={2.2} /></div></Pressable>
              </div>);
            })}
          </div>
        </Section>

        {/* ── Zubehör ── */}
        {e.accessories && e.accessories.length > 0 &&
          <Section label="Zubehör">
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {e.accessories.map((a, i) =>
                <span key={i} style={{ fontSize: 12, fontWeight: 600, color: t.text, padding: '6px 11px', borderRadius: 8, background: t.chip }}>{a}</span>
              )}
            </div>
          </Section>
        }

        {/* ── Mietverlauf ── */}
        {related.length > 0 &&
          <Section label="Mietverlauf">
            <div style={{ background: t.card, borderRadius: 12, border: `0.5px solid ${t.sep}`, overflow: 'hidden' }}>
              {related.map((r, i) =>
                <Pressable key={r.id} onClick={() => go('rentals', { rentalId: r.id })} scale={0.998} hoverBg={t.cardAlt}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '9px 12px', borderTop: i === 0 ? 'none' : `0.5px solid ${t.sep}` }}>
                    <Avatar name={r.tenantName} size={28}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 13, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.tenantName}</div>
                      <div style={{ fontSize: 11, color: t.textSec, marginTop: 1 }}>{fmtRange(r.start, r.end)}</div>
                    </div>
                    <StatusPill status={r.status}/>
                    <div style={{ fontSize: 12.5, fontWeight: 700, color: t.text, width: 56, textAlign: 'right', ...NUMS }}>{rentalTotal(r)} €</div>
                  </div>
                </Pressable>
              )}
            </div>
          </Section>
        }
      </div>
    </Scroll>);
}

// ── Editable kind chip ──
function EditableKindChip({ name, onRename, onDelete }) {
  const t = useTheme();
  const [val, setVal] = useState(name);
  const [focus, setFocus] = useState(false);
  useEffect(() => {setVal(name);}, [name]);
  const inputRef = useRef(null);
  const commit = () => {if (val.trim() && val !== name) onRename(val.trim());else setVal(name);};
  return (
    <div style={{ display: 'inline-flex', alignItems: 'center', gap: 2, background: t.chip, borderRadius: 100, padding: '2px 2px 2px 10px', border: focus ? `1px solid ${t.accent}` : '1px solid transparent', whiteSpace: 'nowrap' }}>
      <input ref={inputRef} value={val} onChange={(e) => setVal(e.target.value)}
        onFocus={() => setFocus(true)}
        onBlur={() => {setFocus(false);commit();}}
        onKeyDown={(e) => {if (e.key === 'Enter') {commit();inputRef.current && inputRef.current.blur();}if (e.key === 'Escape') {setVal(name);inputRef.current && inputRef.current.blur();}}}
        style={{ background: 'transparent', border: 'none', outline: 'none', fontSize: 12.5, fontWeight: 600, color: t.text, width: Math.max(40, val.length * 7.5 + 6), padding: '4px 0' }} />
      <Pressable onClick={onDelete} scale={0.85}>
        <div title="Typ entfernen" style={{ width: 20, height: 20, borderRadius: 10, background: 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon d="M6 6l12 12M18 6L6 18" color={t.textSec} size={10} sw={2.2} />
        </div>
      </Pressable>
    </div>);
}

// ── Screen ──
function ScreenEquipment({ go, nav, equipment, setEquipment, categories, setCategories, rentals }) {
  const t = useTheme();
  const toast = useToast();
  const [query, setQuery] = useState('');
  const [kind, setKind] = useState('alle');
  const [selId, setSelId] = useState(equipment[0] ? equipment[0].id : null);
  const [sheet, setSheet] = useState(null);
  const [confirmDel, setConfirmDel] = useState(null);
  const [editKinds, setEditKinds] = useState(false);
  const [addingKind, setAddingKind] = useState(false);
  const [newKindName, setNewKindName] = useState('');
  const [analyseOpen, setAnalyseOpen] = useState(false);

  const renameCategory = (oldName, newName) => {
    const v = (newName || '').trim();
    if (!v || v === oldName) return;
    if (categories.includes(v)) {toast('Typ existiert bereits');return;}
    setCategories((prev) => prev.map((c) => c === oldName ? v : c));
    setEquipment((prev) => prev.map((e) => e.kind === oldName ? { ...e, kind: v } : e));
    if (kind === oldName) setKind(v);
    toast('Umbenannt');
  };
  const deleteCategory = (name) => {
    const inUse = equipment.filter((e) => e.kind === name).length;
    if (inUse > 0) {toast(`„${name}" wird von ${inUse} Objekt(en) genutzt`);return;}
    setCategories((prev) => prev.filter((c) => c !== name));
    if (kind === name) setKind('alle');
    toast('Typ entfernt');
  };
  const addCategory = () => {
    const v = newKindName.trim();
    if (!v) {setAddingKind(false);return;}
    if (categories.includes(v)) {toast('Typ existiert bereits');return;}
    setCategories((prev) => [...prev, v]);
    setNewKindName('');
    setAddingKind(false);
    toast('Typ hinzugefügt');
  };

  useEffect(() => {if (nav && nav.equipmentId) setSelId(nav.equipmentId);if (nav && nav.newEquipment) setSheet({});}, [nav]);

  const filtered = equipment.
  filter((e) => kind === 'alle' || e.kind === kind).
  filter((e) => !query || (e.name + ' ' + e.cat + ' ' + e.sub).toLowerCase().includes(query.toLowerCase()));
  const selected = equipment.find((e) => e.id === selId);

  const saveEq = (e) => {setEquipment((prev) => {const ex = prev.find((x) => x.id === e.id);return ex ? prev.map((x) => x.id === e.id ? e : x) : [...prev, e];});setSelId(e.id);toast(equipment.find((x) => x.id === e.id) ? 'Gespeichert' : 'Equipment angelegt');};
  const del = (e) => {setEquipment((prev) => prev.filter((x) => x.id !== e.id));if (selId === e.id) setSelId(null);toast('Gelöscht');};
  const patchMaint = (fn) => setEquipment((prev) => prev.map((x) => x.id === selId ? { ...x, maint: fn(x.maint || []) } : x));

  return (
    <>
      <Toolbar title="Equipment" subtitle={`${equipment.length} Mietobjekte`}>
        <SearchField value={query} onChange={setQuery} placeholder="Equipment…" />
        <Button variant="soft" size="sm" icon={icons.chart || icons.bolt} onClick={() => setAnalyseOpen(true)}>Analyse</Button>
        <Button variant="primary" icon={icons.plus} onClick={() => setSheet({})}>Neu</Button>
      </Toolbar>
      <div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
        {/* grid */}
        <div style={{ width: 380, flexShrink: 0, borderRight: `0.5px solid ${t.sep}`, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div style={{ padding: '12px 12px 12px 16px', borderBottom: `0.5px solid ${t.sep}`, display: 'flex', gap: 8, alignItems: 'center' }}>
            <div className="rf-scroll-x" style={{ flex: 1, minWidth: 0, display: 'flex', gap: 6, overflowX: 'auto', alignItems: 'center', paddingRight: 4 }}>
              <Pressable onClick={() => setKind('alle')} scale={0.95}><div style={{ padding: '6px 13px', borderRadius: 100, fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap', background: kind === 'alle' ? t.solidBg : t.chip, color: kind === 'alle' ? t.solidFg : t.text }}>Alle</div></Pressable>
              {categories.map((k) => editKinds ?
                <EditableKindChip key={k} name={k} onRename={(v) => renameCategory(k, v)} onDelete={() => deleteCategory(k)} /> :
                <Pressable key={k} onClick={() => setKind(k)} scale={0.95}><div style={{ padding: '6px 13px', borderRadius: 100, fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap', background: kind === k ? t.solidBg : t.chip, color: kind === k ? t.solidFg : t.text }}>{k}</div></Pressable>
              )}
              {editKinds && (addingKind ?
                <div style={{ display: 'flex', alignItems: 'center', gap: 4, background: t.chip, borderRadius: 100, padding: '2px 4px 2px 10px', border: `1px solid ${t.accent}`, flexShrink: 0 }}>
                  <input autoFocus value={newKindName} onChange={(e) => setNewKindName(e.target.value)}
                    onKeyDown={(e) => {if (e.key === 'Enter') addCategory();if (e.key === 'Escape') {setAddingKind(false);setNewKindName('');}}}
                    onBlur={addCategory} placeholder="Neuer Typ"
                    style={{ background: 'transparent', border: 'none', outline: 'none', fontSize: 12.5, fontWeight: 600, color: t.text, width: 90, padding: '4px 0' }} />
                </div> :
                <Pressable onClick={() => setAddingKind(true)} scale={0.94}><div style={{ padding: '6px 11px', borderRadius: 100, fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap', background: t.chip, color: t.textSec, display: 'inline-flex', alignItems: 'center', gap: 4, flexShrink: 0 }}><Icon d={icons.plus} color={t.textSec} size={11} sw={2.4} />Typ</div></Pressable>
              )}
            </div>
            <Pressable onClick={() => {setEditKinds((v) => !v);setAddingKind(false);setNewKindName('');}} scale={0.94}>
              <div title={editKinds ? 'Fertig' : 'Typen bearbeiten'} style={{ width: 28, height: 28, borderRadius: 14, background: editKinds ? t.accent : t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <Icon d={editKinds ? icons.check : icons.edit} color={editKinds ? '#fff' : t.textSec} size={13} sw={2.2} />
              </div>
            </Pressable>
          </div>
          <div className="rf-scroll" style={{ flex: 1, overflow: 'auto', padding: 12 }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
              {filtered.map((e) => {
                const st = eqStock(e, rentals);
                const sel = e.id === selId;
                return (
                  <Pressable key={e.id} onClick={() => setSelId(e.id)} scale={0.997}>
                    <div className={sel ? '' : 'rf-card-hover'} style={{ background: sel ? t.chip : 'transparent', borderRadius: 11, padding: '10px 12px', border: sel ? `1px solid ${t.sep}` : '1px solid transparent', display: 'flex', alignItems: 'center', gap: 12, transition: 'all 0.12s' }}>
                      <EqAvatar item={e} size={42} radius={10} />
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                          <span style={{ fontSize: 14, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.name}</span>
                        </div>
                        <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{e.cat}</div>
                      </div>
                      <div style={{ textAlign: 'right', flexShrink: 0 }}>
                        <div style={{ fontSize: 13, fontWeight: 700, color: t.text, ...NUMS }}>{e.price} €<span style={{ fontSize: 10, color: t.textSec, fontWeight: 500 }}>/Tag</span></div>
                        <div style={{ fontSize: 11, fontWeight: 600, color: t.textSec, marginTop: 1 }}><span style={{ color: t.text }}>{st.verfuegbar}</span>/{st.total} verfügbar</div>
                      </div>
                    </div>
                  </Pressable>);

              })}
            </div>
            {filtered.length === 0 && <div style={{ padding: '40px 20px', textAlign: 'center', color: t.textSec, fontSize: 13 }}>Keine Treffer.</div>}
          </div>
        </div>
        {/* detail */}
        <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column' }}>
          {selected ?
          <EquipmentDetail item={selected} rentals={rentals} equipment={equipment} categories={categories} go={go}
          onEdit={() => setSheet(selected)} onDelete={() => setConfirmDel(selected)}
          onUpdateRepair={(n) => setEquipment((prev) => prev.map((x) => x.id === selected.id ? { ...x, repairQty: n } : x))}
          onAddMaint={(m) => patchMaint((list) => [m, ...list])}
          onToggleMaint={(id) => patchMaint((list) => list.map((m) => m.id === id ? { ...m, done: !m.done } : m))}
          onRemoveMaint={(id) => patchMaint((list) => list.filter((m) => m.id !== id))} /> :

          <Empty icon={icons.truck} title="Kein Equipment gewählt" sub="Wähle links ein Objekt oder lege neues Equipment an." action="Neues Equipment" onAction={() => setSheet({})} />
          }
        </div>
      </div>

      <EquipmentSheet open={sheet !== null} initial={sheet && sheet.id ? sheet : null} categories={categories} rentals={rentals} onClose={() => setSheet(null)} onSave={saveEq} />
      <EquipmentAnalyseSheet open={analyseOpen} onClose={() => setAnalyseOpen(false)} equipment={equipment} rentals={rentals} go={go} />
      <Confirm open={!!confirmDel} title="Equipment löschen?" message={confirmDel ? `„${confirmDel.name}" wird entfernt.` : ''} onConfirm={() => del(confirmDel)} onClose={() => setConfirmDel(null)} />
    </>);

}

Object.assign(window, { ScreenEquipment, EquipmentSheet, EquipmentDetail, EditableKindChip, EQ_GLYPHS, MAINT_TYPES, maintMeta });