// Logistik — delivery price calculator + per-rental delivery + address book
const { useState, useEffect } = React;

// Package icon — isometric box, used for Logistik tab + headers
const ICON_TRUCK = 'M12 4l8 4v8l-8 4-8-4V8l8-4z M4 8l8 4 8-4 M12 12v8';
const ICON_PIN = 'M12 22s-7-7.6-7-13a7 7 0 0114 0c0 5.4-7 13-7 13zM12 11a2 2 0 100-4 2 2 0 000 4z';

const DEFAULT_LOGISTIK = {
  kmRate: 0.70,
  pauschale: 10,
  tripFactor: 4,   // 1 = nur Hinfahrt, 2 = hin & zurück, 4 = bringen + abholen (jeweils hin & zurück)
  lagerAddress: 'Bahnhofstr. 18, 82110 Germering',
  addressBook: [
    { id: 'ab1', label: 'München · Zentrum', km: 18 },
    { id: 'ab2', label: 'Germering · Ort',   km: 4 },
    { id: 'ab3', label: 'Planegg',           km: 9 },
    { id: 'ab4', label: 'Fürstenfeldbruck',  km: 14 },
  ],
};

// Trip factor helper — supports legacy `returnTrip` boolean from older saved data
const readTripFactor = (obj, fallback = 4) => {
  if (!obj) return fallback;
  if (typeof obj.tripFactor === 'number') return obj.tripFactor;
  if (typeof obj.returnTrip === 'boolean') return obj.returnTrip ? 2 : 1;
  return fallback;
};
const TRIP_OPTIONS = [
  { f: 1, label: 'Nur Hin',          sub: '×1'                },
  { f: 2, label: 'Hin & zurück',     sub: '×2'                },
  { f: 4, label: 'Bringen + Abholen', sub: '×4 · incl. Abbau'   },
];
const tripMeta = (f) => TRIP_OPTIONS.find(o => o.f === f) || TRIP_OPTIONS[2];

// Pure: returns the delivery price breakdown. Accepts "12,5" or "12.5" for km.
function calcDelivery(km, tripFactor, rate, pauschale) {
  const k = Math.max(0, Number(String(km).replace(',', '.')) || 0);
  const f = Number(tripFactor) || 1;
  if (k === 0) return { tripKm: 0, totalKm: 0, kmCost: 0, pauschale: 0, total: 0, factor: f };
  const totalKm = k * f;
  const kmCost  = totalKm * rate;
  return { tripKm: k, totalKm, kmCost, pauschale, total: kmCost + pauschale, factor: f };
}

// ─ Geocode + route helpers (OpenStreetMap public APIs, CORS-enabled) ─
async function geocodeAddress(query) {
  const url = `https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(query)}&format=json&limit=1&addressdetails=0`;
  const res = await fetch(url, { headers: { 'Accept': 'application/json' } });
  if (!res.ok) throw new Error('Adress-Suche nicht erreichbar');
  const j = await res.json();
  if (!j || !j.length) throw new Error('„' + query + '“ nicht gefunden');
  return { lat: parseFloat(j[0].lat), lon: parseFloat(j[0].lon), label: j[0].display_name };
}
async function routeDistanceKm(from, to) {
  const url = `https://router.project-osrm.org/route/v1/driving/${from.lon},${from.lat};${to.lon},${to.lat}?overview=false`;
  const res = await fetch(url);
  if (!res.ok) throw new Error('Routing-Service nicht erreichbar');
  const j = await res.json();
  if (j.code !== 'Ok' || !j.routes || !j.routes.length) throw new Error('Keine Route gefunden');
  return j.routes[0].distance / 1000;
}

const eu = (n) => n.toLocaleString('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' €';

// Tiny CSS spinner for the address lookup button
function Spinner({ color = '#fff', size = 12 }) {
  return (
    <span style={{
      display: 'inline-block', width: size, height: size,
      border: `2px solid ${color}`, borderTopColor: 'transparent',
      borderRadius: '50%', animation: 'rfSpin 0.7s linear infinite',
      verticalAlign: '-2px',
    }}>
      <style>{`@keyframes rfSpin { to { transform: rotate(360deg); } }`}</style>
    </span>
  );
}

// ─────────────────────────────────────────────────────────────
// Inline rate row — tap to edit a number with a unit suffix
// ─────────────────────────────────────────────────────────────
function RateRow({ label, value, suffix, step = 0.05, onChange }) {
  const t = useTheme();
  const [editing, setEditing] = useState(false);
  const [tmp, setTmp] = useState(String(value).replace('.', ','));
  useEffect(() => { setTmp(String(value).replace('.', ',')); }, [value]);
  const save = () => {
    setEditing(false);
    const n = Number(tmp.replace(',', '.'));
    if (!isNaN(n) && n >= 0) onChange(n);
  };
  return (
    <div style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <div style={{ fontSize: 13, color: t.textSec, fontWeight: 500 }}>{label}</div>
      {editing ? (
        <input autoFocus value={tmp} onChange={e => setTmp(e.target.value)}
          onBlur={save}
          onKeyDown={e => { if (e.key === 'Enter') save(); if (e.key === 'Escape') { setTmp(String(value).replace('.', ',')); setEditing(false); } }}
          inputMode="decimal"
          style={{ width: 100, padding: '6px 10px', borderRadius: 8, border: `1px solid ${t.accent}`, background: t.inputBg, fontSize: 14, color: t.text, outline: 'none', textAlign: 'right', fontFamily: 'inherit' }}/>
      ) : (
        <Pressable onClick={() => setEditing(true)} scale={0.97}>
          <div style={{ fontSize: 15, fontWeight: 700, color: t.text }}>
            {String(value).replace('.', ',')} <span style={{ color: t.textSec, fontWeight: 500, fontSize: 13 }}>{suffix}</span>
            <span style={{ color: t.textTer, fontSize: 10, marginLeft: 6 }}>✎</span>
          </div>
        </Pressable>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Address book sheet
// ─────────────────────────────────────────────────────────────
function AddressBookSheet({ open, onClose, logistik, setLogistik, toast }) {
  const t = useTheme();
  const [label, setLabel] = useState('');
  const [km, setKm] = useState('');

  const add = () => {
    const l = label.trim();
    const k = Number(km);
    if (!l || isNaN(k) || k <= 0) return;
    setLogistik(prev => ({ ...prev, addressBook: [...(prev.addressBook || []), { id: 'ab-' + Date.now(), label: l, km: k }] }));
    setLabel(''); setKm('');
    toast('Adresse hinzugefügt');
  };
  const remove = (id) => setLogistik(prev => ({ ...prev, addressBook: prev.addressBook.filter(a => a.id !== id) }));

  const inp = {
    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',
  };

  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 }}>Adressbuch</div>
            <div style={{ fontSize: 13, color: t.textSec, marginTop: 4 }}>Häufige Lieferorte mit Entfernung speichern.</div>
          </div>
          <Pressable onClick={onClose}>
            <div style={{ fontSize: 14, color: t.accent, fontWeight: 600 }}>Fertig</div>
          </Pressable>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 90px', gap: 8, marginTop: 18 }}>
          <input value={label} onChange={e => setLabel(e.target.value)} placeholder="Ort / Stichwort" style={inp}/>
          <input value={km} onChange={e => setKm(e.target.value)} placeholder="km" inputMode="decimal" style={{ ...inp, textAlign: 'center' }}/>
        </div>
        <Pressable onClick={add} scale={0.97} style={{ marginTop: 10 }}>
          <div style={{ padding: '12px 0', textAlign: 'center', borderRadius: 12, background: t.solidBg, color: t.solidFg, fontSize: 14, fontWeight: 600 }}>+ Adresse speichern</div>
        </Pressable>

        <div style={{ marginTop: 18, background: t.card, borderRadius: 14, overflow: 'hidden' }}>
          {(logistik.addressBook || []).map((a, i, arr) => (
            <div key={a.id} style={{
              display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px',
              borderBottom: i < arr.length - 1 ? `0.5px solid ${t.sep}` : 'none',
            }}>
              <div style={{ width: 30, height: 30, borderRadius: 15, background: t.accentSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon d={ICON_PIN} color={t.accent} size={15} sw={2}/>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{a.label}</div>
                <div style={{ fontSize: 11, color: t.textSec, marginTop: 1 }}>{String(a.km).replace('.', ',')} km · einfache Strecke</div>
              </div>
              <Pressable onClick={() => remove(a.id)} scale={0.85}>
                <div style={{ width: 28, height: 28, borderRadius: 14, 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>
          ))}
          {(logistik.addressBook || []).length === 0 && (
            <div style={{ padding: '24px 0', textAlign: 'center', color: t.textSec, fontSize: 13 }}>Noch keine Adressen.</div>
          )}
        </div>
      </div>
    </Sheet>
  );
}

// ─────────────────────────────────────────────────────────────
// Settings sheet (km rate, Pauschale, Lagerstandort)
// ─────────────────────────────────────────────────────────────
function SettingsSheet({ open, onClose, logistik, setLogistik, toast }) {
  const t = useTheme();
  const inp = {
    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',
  };
  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 }}>Tarife & Standort</div>
            <div style={{ fontSize: 13, color: t.textSec, marginTop: 4 }}>Werden bei jeder Berechnung verwendet.</div>
          </div>
          <Pressable onClick={onClose}>
            <div style={{ fontSize: 14, color: t.accent, fontWeight: 600 }}>Fertig</div>
          </Pressable>
        </div>

        <div style={{ marginTop: 18, background: t.card, borderRadius: 14, overflow: 'hidden' }}>
          <RateRow label="Preis pro km" value={logistik.kmRate} suffix="€/km" onChange={v => setLogistik(p => ({ ...p, kmRate: v }))}/>
          <div style={{ height: 0.5, background: t.sep, marginLeft: 14 }}/>
          <RateRow label="Pauschale" value={logistik.pauschale} suffix="€" onChange={v => setLogistik(p => ({ ...p, pauschale: v }))}/>
        </div>

        <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6, marginTop: 18 }}>Standard-Fahrten</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          {TRIP_OPTIONS.map(opt => {
            const sel = readTripFactor(logistik) === opt.f;
            return (
              <Pressable key={opt.f} onClick={() => setLogistik(p => ({ ...p, tripFactor: opt.f, returnTrip: opt.f !== 1 }))} scale={0.98}>
                <div style={{
                  padding: '12px 14px', borderRadius: 12,
                  background: sel ? t.solidBg : t.card,
                  border: sel ? 'none' : `0.5px solid ${t.sep}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                }}>
                  <div>
                    <div style={{ fontSize: 14, fontWeight: 700, color: sel ? t.solidFg : t.text }}>{opt.label}</div>
                    <div style={{ fontSize: 11, color: sel ? 'rgba(255,255,255,0.7)' : t.textSec, marginTop: 1 }}>{opt.sub}</div>
                  </div>
                  <div style={{ fontSize: 18, fontWeight: 700, color: sel ? t.solidFg : t.textTer }}>✕{opt.f}</div>
                </div>
              </Pressable>
            );
          })}
        </div>

        <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6, marginTop: 18 }}>Lager / Startadresse</div>
        <input value={logistik.lagerAddress || ''} onChange={e => setLogistik(p => ({ ...p, lagerAddress: e.target.value }))}
          placeholder="Bahnhofstr. 18, 82110 Germering" style={inp}/>
        <div style={{ fontSize: 11, color: t.textSec, marginTop: 6, lineHeight: 1.4 }}>
          Von hier aus werden Entfernungen gemessen.
        </div>

        <div style={{ marginTop: 22, padding: '14px 16px', background: t.accentSoft, borderRadius: 14, display: 'flex', gap: 12 }}>
          <div style={{ fontSize: 20, lineHeight: 1 }}>💡</div>
          <div style={{ flex: 1, fontSize: 12, color: t.text, lineHeight: 1.5 }}>
            <strong>Faustregel:</strong> Aktuell <b>{String(logistik.kmRate).replace('.', ',')} €/km</b> × <b>{readTripFactor(logistik)}</b> Fahrten + <b>{logistik.pauschale} € Pauschale</b>.<br/>
            <span style={{ color: t.textSec }}>Beispiel 10 km: {eu(calcDelivery(10, readTripFactor(logistik), logistik.kmRate, logistik.pauschale).total)}</span>
          </div>
        </div>
      </div>
    </Sheet>
  );
}

// ─────────────────────────────────────────────────────────────
// Per-rental delivery sheet
// ─────────────────────────────────────────────────────────────
function RentalDeliverySheet({ open, onClose, rental, rentals, setRentals, logistik, toast }) {
  const t = useTheme();
  const r = rentals.find(x => x.id === (rental && rental.id));
  const defaultFactor = readTripFactor(logistik);
  const dRaw = (r && r.delivery) || { enabled: false, address: '', km: 0 };
  const d = { ...dRaw, tripFactor: readTripFactor(dRaw, defaultFactor) };

  const set = (patch) => {
    setRentals(prev => prev.map(x => x.id === r.id ? {
      ...x,
      delivery: {
        ...(x.delivery || { enabled: false, address: '', km: 0, tripFactor: defaultFactor }),
        ...patch,
      },
    } : x));
  };

  const calc = calcDelivery(d.km, d.tripFactor, logistik.kmRate, logistik.pauschale);
  const inp = {
    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',
  };

  if (!r) return null;

  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 }}>Lieferung</div>
            <div style={{ fontSize: 13, color: t.textSec, marginTop: 4 }}>{r.tenantName} · {r.equipmentName}</div>
          </div>
          <Pressable onClick={onClose}>
            <div style={{ fontSize: 14, color: t.accent, fontWeight: 600 }}>Fertig</div>
          </Pressable>
        </div>

        {/* Enabled toggle */}
        <div style={{ marginTop: 18, background: t.card, borderRadius: 14, padding: '14px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>Anlieferung & Abholung</div>
            <div style={{ fontSize: 11, color: t.textSec, marginTop: 1 }}>{d.enabled ? 'Wir liefern' : 'Selbstabholung'}</div>
          </div>
          <Pressable onClick={() => set({ enabled: !d.enabled })} scale={0.94}>
            <div style={{
              width: 44, height: 26, borderRadius: 13, padding: 2,
              background: d.enabled ? t.green : t.chipStrong,
              transition: 'background 0.2s',
              display: 'flex', justifyContent: d.enabled ? 'flex-end' : 'flex-start', alignItems: 'center',
            }}>
              <div style={{ width: 22, height: 22, borderRadius: 11, background: '#fff', boxShadow: '0 1px 3px rgba(0,0,0,0.25)' }}/>
            </div>
          </Pressable>
        </div>

        {d.enabled && (
          <>
            <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginTop: 18, marginBottom: 6 }}>Lieferadresse</div>
            <input value={d.address || r.address.split('\n')[0] || ''} onChange={e => set({ address: e.target.value })}
              placeholder="Straße, PLZ Ort" style={inp}/>

            {(logistik.addressBook || []).length > 0 && (
              <div style={{ display: 'flex', gap: 6, overflowX: 'auto', marginTop: 8, paddingBottom: 4 }}>
                {logistik.addressBook.map(a => (
                  <Pressable key={a.id} onClick={() => set({ address: a.label, km: a.km })} scale={0.95}>
                    <div style={{
                      padding: '6px 10px', borderRadius: 9, fontSize: 11, fontWeight: 600,
                      background: t.chip, color: t.text, whiteSpace: 'nowrap',
                    }}>
                      <Icon d={ICON_PIN} color={t.accent} size={10} sw={2.2}/> {a.label} · {String(a.km).replace('.', ',')} km
                    </div>
                  </Pressable>
                ))}
              </div>
            )}

            <div style={{ marginTop: 14, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              <div>
                <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>Entfernung</div>
                <input value={d.km || ''} onChange={e => set({ km: Number(e.target.value) || 0 })}
                  placeholder="km" inputMode="decimal" style={inp}/>
              </div>
              <div>
                <div style={{ fontSize: 11, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 6 }}>Fahrten</div>
                <div style={{ display: 'flex', gap: 4 }}>
                  {TRIP_OPTIONS.map(opt => {
                    const sel = d.tripFactor === opt.f;
                    return (
                      <Pressable key={opt.f} onClick={() => set({ tripFactor: opt.f })} scale={0.95} style={{ flex: 1 }}>
                        <div style={{ padding: '12px 0', textAlign: 'center', borderRadius: 12, background: sel ? t.solidBg : t.chip, color: sel ? t.solidFg : t.text, fontSize: 14, fontWeight: 700 }}>
                          ×{opt.f}
                        </div>
                      </Pressable>
                    );
                  })}
                </div>
              </div>
            </div>
            <div style={{ fontSize: 11, color: t.textSec, marginTop: 6 }}>{tripMeta(d.tripFactor).label} · {tripMeta(d.tripFactor).sub}</div>

            {/* Breakdown */}
            <div style={{ marginTop: 18, background: t.card, borderRadius: 14, overflow: 'hidden' }}>
              <BreakdownRow label="Gefahrene km" value={`${String(calc.totalKm).replace('.', ',')} km`} sub={d.tripFactor > 1 ? `${String(calc.tripKm).replace('.', ',')} km × ${d.tripFactor}` : 'einfache Strecke'}/>
              <BreakdownRow label={`${String(logistik.kmRate).replace('.', ',')} € × ${String(calc.totalKm).replace('.', ',')} km`} value={eu(calc.kmCost)}/>
              <BreakdownRow label="Pauschale" value={eu(calc.pauschale)}/>
              <div style={{ padding: '14px 14px', background: t.accentSoft, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>Lieferpreis gesamt</div>
                <div style={{ fontSize: 22, fontWeight: 700, color: t.accent, letterSpacing: -0.5 }}>{eu(calc.total)}</div>
              </div>
            </div>

            {/* Copy line for sharing */}
            <Pressable onClick={() => { toast('„Lieferung: ' + eu(calc.total) + '" kopiert'); }} scale={0.97} style={{ marginTop: 12 }}>
              <div style={{ padding: '12px 0', textAlign: 'center', borderRadius: 12, background: t.chip, color: t.text, fontSize: 13, fontWeight: 600 }}>
                Text für Kunde kopieren
              </div>
            </Pressable>
          </>
        )}
      </div>
    </Sheet>
  );
}

function BreakdownRow({ label, value, sub }) {
  const t = useTheme();
  return (
    <div style={{ padding: '12px 14px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: `0.5px solid ${t.sep}` }}>
      <div>
        <div style={{ fontSize: 13, color: t.text, fontWeight: 500 }}>{label}</div>
        {sub && <div style={{ fontSize: 10, color: t.textSec, marginTop: 1 }}>{sub}</div>}
      </div>
      <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{value}</div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Main Logistik screen
// ─────────────────────────────────────────────────────────────
function ScreenLogistik({ rentals, setRentals, logistik, setLogistik, equipment, toast, go, embedded = false, settingsOpen: externalSettingsOpen, onSettingsClose }) {
  const t = useTheme();
  const [km, setKm] = useState('');
  const [tripFactor, setTripFactor] = useState(readTripFactor(logistik));
  const [addrOpen, setAddrOpen] = useState(false);
  const [internalSettingsOpen, setInternalSettingsOpen] = useState(false);
  const settingsOpen = embedded ? !!externalSettingsOpen : internalSettingsOpen;
  const setSettingsOpen = embedded ? (v) => { if (!v && onSettingsClose) onSettingsClose(); } : setInternalSettingsOpen;
  const [rentalSheet, setRentalSheet] = useState(null); // rental id

  // Address → km lookup state
  const [address, setAddress] = useState('');
  const [looking, setLooking] = useState(false);
  const [lookErr, setLookErr] = useState('');
  const [resolvedLabel, setResolvedLabel] = useState('');

  useEffect(() => { setTripFactor(readTripFactor(logistik)); }, [logistik.tripFactor, logistik.returnTrip]);

  const lookup = async () => {
    const q = address.trim();
    if (!q) return;
    if (!logistik.lagerAddress) {
      setLookErr('Bitte zuerst Lager-Adresse in den Einstellungen eintragen.');
      setSettingsOpen(true);
      return;
    }
    setLooking(true); setLookErr(''); setResolvedLabel('');
    try {
      const from = await geocodeAddress(logistik.lagerAddress);
      const to   = await geocodeAddress(q);
      const d    = await routeDistanceKm(from, to);
      const rounded = Math.round(d * 10) / 10;
      setKm(String(rounded).replace('.', ','));
      setResolvedLabel((to.label || '').split(',').slice(0, 3).join(',').trim());
      toast(`${String(rounded).replace('.', ',')} km berechnet`);
    } catch (e) {
      setLookErr(e.message || 'Adresse konnte nicht berechnet werden');
    } finally {
      setLooking(false);
    }
  };

  const calc = calcDelivery(km, tripFactor, logistik.kmRate, logistik.pauschale);
  const liveRentals = rentals.filter(r => r.status !== 'abgeschlossen')
    .sort((a, b) => a.start.localeCompare(b.start));

  // KPI: delivery revenue from rentals
  const deliveryRevenue = rentals
    .filter(r => r.delivery && r.delivery.enabled)
    .reduce((s, r) => s + calcDelivery(r.delivery.km, readTripFactor(r.delivery, readTripFactor(logistik)), logistik.kmRate, logistik.pauschale).total, 0);
  const deliveryCount = rentals.filter(r => r.delivery && r.delivery.enabled).length;

  return (
    <div style={embedded ? { paddingBottom: 16 } : { paddingBottom: 100 }}>
      {/* Header — skipped in embedded mode */}
      {!embedded && (
      <div style={{ padding: '8px 20px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end' }}>
        <div>
          <div style={{ fontSize: 13, color: t.textSec, fontWeight: 500 }}>Lieferpreis · Routen</div>
          <div style={{ fontSize: 32, fontWeight: 700, color: t.text, letterSpacing: -0.8, marginTop: 2 }}>Logistik</div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <Pressable onClick={() => setSettingsOpen(true)} scale={0.88}>
            <div style={{ width: 38, height: 38, borderRadius: 19, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon d="M12 15a3 3 0 100-6 3 3 0 000 6zM19.4 15a1.7 1.7 0 00.3 1.8l.1.1a2 2 0 11-2.8 2.8l-.1-.1a1.7 1.7 0 00-1.8-.3 1.7 1.7 0 00-1 1.5V21a2 2 0 11-4 0v-.1a1.7 1.7 0 00-1-1.5 1.7 1.7 0 00-1.8.3l-.1.1a2 2 0 11-2.8-2.8l.1-.1a1.7 1.7 0 00.3-1.8 1.7 1.7 0 00-1.5-1H3a2 2 0 110-4h.1a1.7 1.7 0 001.5-1 1.7 1.7 0 00-.3-1.8l-.1-.1a2 2 0 112.8-2.8l.1.1a1.7 1.7 0 001.8.3h0a1.7 1.7 0 001-1.5V3a2 2 0 114 0v.1a1.7 1.7 0 001 1.5 1.7 1.7 0 001.8-.3l.1-.1a2 2 0 112.8 2.8l-.1.1a1.7 1.7 0 00-.3 1.8v0a1.7 1.7 0 001.5 1H21a2 2 0 110 4h-.1a1.7 1.7 0 00-1.5 1z" color={t.text} size={18} sw={1.6}/>
            </div>
          </Pressable>
          <CompanyGear size={38} />
        </div>
      </div>
      )}

      {/* Calculator card */}
      <div style={{ padding: '16px 16px 0' }}>
        <div style={{ background: t.card, borderRadius: 22, padding: '18px 18px', boxShadow: t.shadowCard }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <div style={{ width: 32, height: 32, borderRadius: 16, background: t.accentSoft, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <ImgIcon light={IMG_ICONS.truck.light} dark={IMG_ICONS.truck.dark} size={18}/>
            </div>
            <div style={{ fontSize: 13, color: t.textSec, fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.6 }}>Lieferpreis-Rechner</div>
          </div>

          {/* Address → km lookup */}
          <div style={{ marginTop: 14, display: 'flex', gap: 6 }}>
            <div style={{ flex: 1, minWidth: 0, position: 'relative' }}>
              <input value={address}
                onChange={e => { setAddress(e.target.value); setLookErr(''); }}
                onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); lookup(); } }}
                placeholder="Adresse · Straße, PLZ Ort"
                style={{
                  width: '100%', padding: '11px 12px 11px 34px', borderRadius: 12,
                  border: `0.5px solid ${t.inputBorder}`, background: t.inputBg,
                  fontSize: 14, color: t.text, outline: 'none', fontFamily: 'inherit', boxSizing: 'border-box',
                }}/>
              <div style={{ position: 'absolute', left: 11, top: '50%', transform: 'translateY(-50%)', pointerEvents: 'none' }}>
                <Icon d={ICON_PIN} color={t.textSec} size={14} sw={2}/>
              </div>
              {address && !looking && (
                <Pressable onClick={() => { setAddress(''); setResolvedLabel(''); setLookErr(''); }} scale={0.85}
                  style={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)' }}>
                  <div style={{ width: 20, height: 20, borderRadius: 10, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    <svg width="8" height="8" viewBox="0 0 12 12" fill="none" stroke={t.textSec} strokeWidth="2.4" strokeLinecap="round"><path d="M3 3l6 6M9 3l-6 6"/></svg>
                  </div>
                </Pressable>
              )}
            </div>
            <Pressable onClick={lookup} scale={0.94} disabled={!address.trim() || looking}>
              <div style={{
                padding: '11px 14px', borderRadius: 12,
                background: address.trim() && !looking ? t.solidBg : t.chip,
                color: address.trim() && !looking ? t.solidFg : t.textSec,
                fontSize: 13, fontWeight: 700, whiteSpace: 'nowrap',
                display: 'flex', alignItems: 'center', gap: 6,
              }}>
                {looking
                  ? (<><Spinner color={t.solidFg}/> berechne…</>)
                  : '→ km'}
              </div>
            </Pressable>
          </div>
          {lookErr && (
            <div style={{ marginTop: 6, fontSize: 11, color: t.red, fontWeight: 600, lineHeight: 1.4 }}>{lookErr}</div>
          )}
          {resolvedLabel && !lookErr && (
            <div style={{ marginTop: 6, fontSize: 11, color: t.textSec, fontWeight: 500, lineHeight: 1.4 }}>
              ✓ {resolvedLabel}
            </div>
          )}

          {/* km input */}
          <div style={{ marginTop: 14, display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <input value={km} onChange={e => setKm(e.target.value)}
              placeholder="0" inputMode="decimal" autoFocus
              style={{
                flex: 1, minWidth: 0, width: 0, padding: '4px 0',
                fontSize: 52, fontWeight: 700, letterSpacing: -1.6,
                border: 'none', outline: 'none', background: 'transparent', color: t.text,
                fontFamily: 'inherit', textAlign: 'right',
              }}/>
            <div style={{ fontSize: 24, fontWeight: 600, color: t.textSec, paddingRight: 4 }}>km</div>
          </div>
          <div style={{ height: 1, background: t.sep, marginTop: 4 }}/>

          {/* Trip mode — 3 options */}
          <div style={{ marginTop: 12, display: 'flex', gap: 6 }}>
            {TRIP_OPTIONS.map(opt => {
              const sel = tripFactor === opt.f;
              return (
                <Pressable key={opt.f} onClick={() => setTripFactor(opt.f)} scale={0.96} style={{ flex: 1, minWidth: 0 }}>
                  <div style={{
                    padding: '10px 4px', textAlign: 'center', borderRadius: 12,
                    background: sel ? t.solidBg : t.chip, color: sel ? t.solidFg : t.text,
                  }}>
                    <div style={{ fontSize: 12, fontWeight: 700, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{opt.label}</div>
                    <div style={{ fontSize: 9.5, fontWeight: 600, marginTop: 2, opacity: sel ? 0.75 : 0.65 }}>{opt.sub}</div>
                  </div>
                </Pressable>
              );
            })}
          </div>

          {/* Quick chips from address book */}
          {(logistik.addressBook || []).length > 0 && (
            <div style={{ display: 'flex', gap: 6, overflowX: 'auto', marginTop: 12, paddingBottom: 4 }}>
              {logistik.addressBook.map(a => (
                <Pressable key={a.id} onClick={() => setKm(String(a.km).replace('.', ','))} scale={0.95}>
                  <div style={{
                    padding: '6px 10px', borderRadius: 9, fontSize: 11, fontWeight: 600,
                    background: t.chip, color: t.text, whiteSpace: 'nowrap',
                    display: 'flex', alignItems: 'center', gap: 4,
                  }}>
                    <Icon d={ICON_PIN} color={t.accent} size={10} sw={2.2}/>{a.label} · {String(a.km).replace('.', ',')} km
                  </div>
                </Pressable>
              ))}
              <Pressable onClick={() => setAddrOpen(true)} scale={0.95}>
                <div style={{
                  padding: '6px 10px', borderRadius: 9, fontSize: 11, fontWeight: 600,
                  background: t.accentSoft, color: t.accent, whiteSpace: 'nowrap',
                }}>
                  + Adresse
                </div>
              </Pressable>
            </div>
          )}

          {/* Breakdown */}
          <div style={{ marginTop: 16, padding: '14px 0 0', borderTop: `0.5px solid ${t.sep}` }}>
            <BreakLine label={`Gefahrene km`} value={`${String(calc.totalKm).replace('.', ',')} km`} sub={tripFactor > 1 && calc.tripKm > 0 ? `${String(calc.tripKm).replace('.', ',')} km × ${tripFactor} Fahrten` : null}/>
            <BreakLine label={`${String(logistik.kmRate).replace('.', ',')} €/km`} value={eu(calc.kmCost)}/>
            <BreakLine label={`Pauschale`} value={eu(calc.pauschale)}/>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 10, paddingTop: 12, borderTop: `0.5px solid ${t.sep}` }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>Lieferpreis</div>
              <div style={{ fontSize: 28, fontWeight: 700, color: t.accent, letterSpacing: -0.8 }}>{eu(calc.total)}</div>
            </div>
            {calc.total > 0 && (
              <div style={{ fontSize: 11, color: t.textSec, marginTop: 6, textAlign: 'right' }}>
                „Lieferung {eu(calc.total)} — {String(calc.totalKm).replace('.', ',')} km ({tripMeta(tripFactor).label.toLowerCase()}) bei {String(logistik.kmRate).replace('.', ',')} €/km + {logistik.pauschale} € Pauschale.“
              </div>
            )}
          </div>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{ padding: '10px 16px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        <Pressable onClick={() => setAddrOpen(true)} scale={0.97}>
          <div style={{ background: t.card, borderRadius: 16, padding: '12px 12px', boxShadow: t.shadowCard }}>
            <div style={{ fontSize: 11, color: t.textSec, fontWeight: 500 }}>Adressbuch</div>
            <div style={{ fontSize: 24, fontWeight: 700, color: t.text, letterSpacing: -0.4, marginTop: 4 }}>{(logistik.addressBook || []).length}</div>
            <div style={{ fontSize: 11, color: t.accent, marginTop: 2, fontWeight: 600 }}>Verwalten ›</div>
          </div>
        </Pressable>
        <div style={{ background: t.card, borderRadius: 16, padding: '12px 12px', boxShadow: t.shadowCard }}>
          <div style={{ fontSize: 11, color: t.textSec, fontWeight: 500 }}>Lieferungen aktiv</div>
          <div style={{ fontSize: 24, fontWeight: 700, color: t.green, letterSpacing: -0.4, marginTop: 4 }}>{deliveryCount}</div>
          <div style={{ fontSize: 11, color: t.textSec, marginTop: 2, fontWeight: 500 }}>{eu(deliveryRevenue)} Umsatz</div>
        </div>
      </div>

      {/* Per-rental delivery list */}
      <div style={{ padding: '24px 20px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <div style={{ fontSize: 18, fontWeight: 600, color: t.text, letterSpacing: -0.3 }}>Anstehende Lieferungen</div>
      </div>
      <div style={{ padding: '0 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {liveRentals.length === 0 && (
          <div style={{ textAlign: 'center', padding: '30px 20px', color: t.textSec, fontSize: 13, background: t.card, borderRadius: 16, border: '1px dashed ' + t.sep }}>
            Keine laufenden Mieten.
          </div>
        )}
        {liveRentals.map(r => {
          const eq = equipment.find(e => e.id === r.equipmentId);
          const d = r.delivery;
          const enabled = d && d.enabled;
          const rCalc = enabled ? calcDelivery(d.km, readTripFactor(d, readTripFactor(logistik)), logistik.kmRate, logistik.pauschale) : null;
          const m = statusMeta(r.status);
          return (
            <Pressable key={r.id} onClick={() => setRentalSheet(r.id)} scale={0.98}>
              <div style={{ background: t.card, borderRadius: 16, padding: 12, display: 'flex', gap: 12, alignItems: 'center', boxShadow: t.shadowCard }}>
                <EqAvatar item={eq || {}} size={42} radius={10}/>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.tenantName}</div>
                  <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                    {fmtDateDE(r.start).slice(0, 6)} · {eq ? eq.name : r.equipmentName}
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 5 }}>
                    {enabled ? (
                      <>
                        <div style={{ fontSize: 10, fontWeight: 700, color: t.green, background: t.greenSoft, padding: '2px 7px', borderRadius: 100 }}>
                          🚚 {String(d.km).replace('.', ',')} km
                        </div>
                        <div style={{ fontSize: 10, fontWeight: 700, color: t.text }}>{eu(rCalc.total)}</div>
                      </>
                    ) : (
                      <div style={{ fontSize: 10, fontWeight: 600, color: t.textSec, background: t.chip, padding: '2px 7px', borderRadius: 100 }}>Selbstabholung</div>
                    )}
                  </div>
                </div>
                <Icon d={icons.chev} color={t.textTer} size={14} sw={2}/>
              </div>
            </Pressable>
          );
        })}
      </div>

      <RentalDeliverySheet
        open={!!rentalSheet}
        rental={rentals.find(r => r.id === rentalSheet)}
        rentals={rentals} setRentals={setRentals}
        logistik={logistik}
        onClose={() => setRentalSheet(null)} toast={toast}/>

      <AddressBookSheet open={addrOpen} onClose={() => setAddrOpen(false)} logistik={logistik} setLogistik={setLogistik} toast={toast}/>
      <SettingsSheet open={settingsOpen} onClose={() => setSettingsOpen(false)} logistik={logistik} setLogistik={setLogistik} toast={toast}/>
    </div>
  );
}

function BreakLine({ label, value, sub }) {
  const t = useTheme();
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '6px 0' }}>
      <div>
        <div style={{ fontSize: 13, color: t.textSec, fontWeight: 500 }}>{label}</div>
        {sub && <div style={{ fontSize: 10, color: t.textTer, marginTop: 1 }}>{sub}</div>}
      </div>
      <div style={{ fontSize: 14, fontWeight: 600, color: t.text }}>{value}</div>
    </div>
  );
}

Object.assign(window, { ScreenLogistik, DEFAULT_LOGISTIK, calcDelivery, ICON_TRUCK });
