// Desktop Mietvorgänge-Analyse — analytics modal opened from the rentals toolbar.
// Focus areas (per user): Auslastung & Zeiträume, Verwendungszweck, Logistik.

// ── Helpers ─────────────────────────────────────────────────────────────
const _raMonthsBack = (n) => {
  const today = new Date();
  const out = [];
  for (let i = n - 1; i >= 0; i--) {
    const d = new Date(today.getFullYear(), today.getMonth() - i, 1);
    out.push({
      key: `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`,
      label: DE_MONTHS_SHORT[d.getMonth()],
      year: d.getFullYear(),
      month: d.getMonth(),
      isCurrent: i === 0
    });
  }
  return out;
};

const _raYM = (iso) => iso ? iso.slice(0, 7) : '';

// Filter rentals by period.
function _raFilterByPeriod(rentals, period) {
  if (period === 'all') return rentals;
  const today = new Date();
  let cutoff;
  if (period === 'month') cutoff = new Date(today.getFullYear(), today.getMonth(), 1);else
  if (period === '3m') cutoff = new Date(today.getFullYear(), today.getMonth() - 2, 1);else
  if (period === '12m') cutoff = new Date(today.getFullYear(), today.getMonth() - 11, 1);else
  if (period === 'ytd') cutoff = new Date(today.getFullYear(), 0, 1);else
  return rentals;
  const cutoffISO = `${cutoff.getFullYear()}-${String(cutoff.getMonth() + 1).padStart(2, '0')}-01`;
  return rentals.filter((r) => (r.start || '') >= cutoffISO);
}

// Customer identity (name + phone normalized so same person counts once).
function _raCustKey(r) {
  const n = (r.tenantName || '').trim().toLowerCase().replace(/\s+/g, ' ');
  const p = (r.phone || '').replace(/[^\d+]/g, '');
  return p && p.length >= 4 ? p : n;
}

// ── Atoms (reuse pattern from equipment-analyse) ────────────────────────
function RaKpi({ label, value, sub, color, icon }) {
  const t = useTheme();
  return (
    <div style={{ background: t.cardAlt, borderRadius: 12, padding: '14px 16px', border: `0.5px solid ${t.sep}` }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
        {icon && <div style={{ width: 22, height: 22, borderRadius: 6, background: (color || t.accent) + '22', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon d={icon} color={color || t.accent} size={12} sw={2.2} />
        </div>}
        <div style={{ fontSize: 10.5, fontWeight: 700, color: t.textSec, textTransform: 'uppercase', letterSpacing: 0.5 }}>{label}</div>
      </div>
      <div style={{ fontSize: 22, fontWeight: 700, color: color || t.text, marginTop: 8, letterSpacing: -0.4, ...NUMS }}>{value}</div>
      {sub && <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 2, ...NUMS }}>{sub}</div>}
    </div>);

}

function RaSection({ title, sub, children, action }) {
  const t = useTheme();
  return (
    <div style={{ marginTop: 22 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
        <div>
          <div style={{ fontSize: 14, fontWeight: 700, color: t.text, letterSpacing: -0.2 }}>{title}</div>
          {sub && <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 1 }}>{sub}</div>}
        </div>
        {action}
      </div>
      {children}
    </div>);

}

// ── Main view ──────────────────────────────────────────────────────────
function RentalsAnalyseSheet({ open, onClose, rentals, equipment, go }) {
  const t = useTheme();
  const [tab, setTab] = useState('overview'); // overview | usage | purpose | logistics
  const [period, setPeriod] = useState('12m'); // month | 3m | 12m | ytd | all
  useEffect(() => {if (!open) {setTab('overview');setPeriod('12m');}}, [open]);
  if (!open) return null;

  const periodOpts = [['month', 'Monat'], ['3m', '3 M.'], ['12m', '12 M.'], ['ytd', 'YTD'], ['all', 'Gesamt']];
  const filtered = _raFilterByPeriod(rentals, period);

  // ── KPI aggregates ─────────────────────────────────────────────
  const totalRevenue = filtered.reduce((s, r) => s + (rentalTotal(r) || 0), 0);
  const totalCount = filtered.length;
  const avgValue = totalCount > 0 ? Math.round(totalRevenue / totalCount) : 0;
  const avgDuration = totalCount > 0 ? Math.round(filtered.reduce((s, r) => s + Math.max(1, daysBetween(r.start, r.end)), 0) / totalCount * 10) / 10 : 0;
  // Unique customers — count over THIS period
  const custCounts = {};
  filtered.forEach((r) => {const k = _raCustKey(r);if (k) custCounts[k] = (custCounts[k] || 0) + 1;});
  const uniqueCust = Object.keys(custCounts).length;
  const returningCust = Object.values(custCounts).filter((c) => c >= 2).length;
  const returnPct = uniqueCust > 0 ? Math.round(returningCust / uniqueCust * 100) : 0;
  // Live state (always now, not period-bound)
  const activeNow = rentals.filter((r) => r.status === 'aktiv').length;
  const reservedNow = rentals.filter((r) => r.status === 'reserviert').length;
  // Logistics share over period
  const deliveryCount = filtered.filter((r) => r.delivery && r.delivery.enabled).length;
  const deliveryPct = totalCount > 0 ? Math.round(deliveryCount / totalCount * 100) : 0;

  // ── Verwendungszweck-Ranking ──────────────────────────────────
  const byPurpose = {};
  filtered.forEach((r) => {
    const p = (r.purpose || 'Ohne Angabe').trim() || 'Ohne Angabe';
    if (!byPurpose[p]) byPurpose[p] = { purpose: p, count: 0, revenue: 0, days: 0 };
    byPurpose[p].count += 1;
    byPurpose[p].revenue += rentalTotal(r) || 0;
    byPurpose[p].days += Math.max(1, daysBetween(r.start, r.end));
  });
  const purposes = Object.values(byPurpose).sort((a, b) => b.count - a.count || b.revenue - a.revenue);

  // ── Wochentag-Heatmap (Abholtag) ──────────────────────────────
  // index 0=Mo … 6=So (German week)
  const weekdayCounts = [0, 0, 0, 0, 0, 0, 0];
  const weekdayRevenue = [0, 0, 0, 0, 0, 0, 0];
  filtered.forEach((r) => {
    if (!r.start) return;
    const jsDay = fromISO(r.start).getDay(); // 0=Sun … 6=Sat
    const idx = (jsDay + 6) % 7; // 0=Mo
    weekdayCounts[idx] += 1;
    weekdayRevenue[idx] += rentalTotal(r) || 0;
  });
  const weekdayMax = Math.max(1, ...weekdayCounts);
  const weekdayLabels = ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'];

  // ── Saisonalität: Vorgänge pro Monat im Jahresvergleich ───────
  const monthBuckets = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // Jan..Dez
  const monthRevenue = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  filtered.forEach((r) => {
    if (!r.start) return;
    const m = fromISO(r.start).getMonth();
    monthBuckets[m] += 1;
    monthRevenue[m] += rentalTotal(r) || 0;
  });
  const monthMax = Math.max(1, ...monthBuckets);

  // ── Umsatz-Verlauf (12-month rolling, bars) ───────────────────
  const months = _raMonthsBack(period === 'month' ? 6 : period === '3m' ? 6 : period === '12m' ? 12 : period === 'ytd' ? new Date().getMonth() + 1 : 24);
  const monthlyTotal = months.map((m) => ({ ...m, value: 0, count: 0 }));
  rentals.forEach((r) => {
    const k = _raYM(r.start);
    const i = months.findIndex((m) => m.key === k);
    if (i >= 0) {monthlyTotal[i].value += rentalTotal(r) || 0;monthlyTotal[i].count += 1;}
  });
  const maxMonthly = Math.max(1, ...monthlyTotal.map((m) => m.value));

  // ── Dauer-Verteilung ──────────────────────────────────────────
  const durationBuckets = [
  { label: '1 Tag', min: 1, max: 1, n: 0, rev: 0 },
  { label: '2–3 Tage', min: 2, max: 3, n: 0, rev: 0 },
  { label: '4–7 Tage', min: 4, max: 7, n: 0, rev: 0 },
  { label: '> 7 Tage', min: 8, max: Infinity, n: 0, rev: 0 }];

  filtered.forEach((r) => {
    const d = Math.max(1, daysBetween(r.start, r.end));
    const b = durationBuckets.find((x) => d >= x.min && d <= x.max);
    if (b) {b.n += 1;b.rev += rentalTotal(r) || 0;}
  });
  const durationMax = Math.max(1, ...durationBuckets.map((b) => b.n));

  // ── Logistik aggregates ───────────────────────────────────────
  const withDelivery = filtered.filter((r) => r.delivery && r.delivery.enabled);
  const selfPickup = filtered.filter((r) => !(r.delivery && r.delivery.enabled));
  const totalKm = withDelivery.reduce((s, r) => s + (Number(r.delivery.km) || 0) * (r.delivery.tripFactor || LOGISTIK_DEFAULTS.tripFactor), 0);
  const avgKm = withDelivery.length > 0 ? Math.round(totalKm / withDelivery.length * 10) / 10 : 0;
  const deliveryRevenue = withDelivery.reduce((s, r) => s + rentalDeliveryFee(r), 0);
  const tripFactorMix = { 1: 0, 2: 0, 4: 0 };
  withDelivery.forEach((r) => {
    const f = r.delivery.tripFactor || LOGISTIK_DEFAULTS.tripFactor;
    tripFactorMix[f] = (tripFactorMix[f] || 0) + 1;
  });
  const longestTrip = withDelivery.reduce((mx, r) => Math.max(mx, Number(r.delivery.km) || 0), 0);

  // City / address aggregation
  const cityCounts = {};
  withDelivery.forEach((r) => {
    const addr = (r.delivery.address || r.address || '').trim();
    // pull "PLZ Ort" or last line
    const lines = addr.split(/\n/).map((s) => s.trim()).filter(Boolean);
    const last = lines[lines.length - 1] || addr;
    const m = last.match(/\d{5}\s+(.+)/);
    const city = m ? m[1] : last || 'Unbekannt';
    if (!city) return;
    cityCounts[city] = (cityCounts[city] || 0) + 1;
  });
  const topCities = Object.entries(cityCounts).sort((a, b) => b[1] - a[1]).slice(0, 8);

  // ── Tabs definition ──────────────────────────────────────────
  const tabs = [
  ['overview', 'Übersicht', icons.bolt],
  ['usage', 'Zeiträume', icons.cal],
  ['purpose', 'Verwendung', icons.tag || icons.bell],
  ['logistics', 'Logistik', icons.truck]];


  const card = { background: t.card, borderRadius: 14, padding: 18, border: `0.5px solid ${t.sep}` };

  return (
    <div role="dialog" aria-modal="true"
    onClick={(e) => {if (e.target === e.currentTarget) onClose();}}
    style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.45)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100 }}>
      <div style={{ background: t.bg, borderRadius: 18, width: 'min(1180px, 96vw)', height: 'min(860px, 92vh)', display: 'flex', flexDirection: 'column', boxShadow: '0 24px 64px rgba(0,0,0,0.35)', overflow: 'hidden' }}>
        {/* Header */}
        <div style={{ padding: '18px 26px', borderBottom: `0.5px solid ${t.sep}`, display: 'flex', alignItems: 'center', gap: 14, background: t.card }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 22, fontWeight: 700, color: t.text, letterSpacing: -0.5 }}>Mietaufträge-Analyse</div>
            <div style={{ fontSize: 12.5, color: t.textSec, marginTop: 2 }}>{totalCount} Vorgänge im Zeitraum · {uniqueCust} Kunden · {Math.round(totalRevenue).toLocaleString('de-DE')} € Umsatz</div>
          </div>
          <Segmented size="sm" value={period} onChange={setPeriod} options={periodOpts} />
          <Pressable onClick={onClose} scale={0.94}>
            <div style={{ width: 32, height: 32, borderRadius: 16, background: t.chip, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon d="M6 6l12 12M18 6L6 18" color={t.text} size={13} sw={2.2} />
            </div>
          </Pressable>
        </div>

        {/* Tabs */}
        <div style={{ padding: '12px 26px 0', borderBottom: `0.5px solid ${t.sep}`, display: 'flex', gap: 4, background: t.card }}>
          {tabs.map(([k, label, ic]) => {
            const sel = tab === k;
            return (
              <Pressable key={k} onClick={() => setTab(k)} scale={0.97}>
                <div style={{ padding: '9px 14px 11px', display: 'flex', alignItems: 'center', gap: 6, borderBottom: sel ? `2px solid ${t.text}` : '2px solid transparent', color: sel ? t.text : t.textSec, fontWeight: 600, fontSize: 13 }}>
                  <Icon d={ic} color={sel ? t.text : t.textSec} size={13} sw={2.2} />
                  {label}
                </div>
              </Pressable>);

          })}
        </div>

        {/* Body */}
        <div className="rf-scroll" style={{ flex: 1, overflow: 'auto', padding: '20px 26px 30px' }}>

          {tab === 'overview' &&
          <>
              {/* KPIs */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
                <RaKpi label="Gesamtumsatz" value={`${Math.round(totalRevenue).toLocaleString('de-DE')} €`} sub={`Ø ${avgValue} € pro Vorgang`} icon={icons.euro} color={t.green} />
                <RaKpi label="Anzahl Kunden" value={`${uniqueCust}`} sub={`${totalCount} Vorgänge gesamt`} icon={icons.user} color={t.accent} />
                <RaKpi label="Wiederkehrend" value={`${returnPct}%`} sub={`${returningCust} von ${uniqueCust} kommen wieder`} icon={icons.bolt} color="#AF52DE" />
                <RaKpi label="Ø Mietdauer" value={`${avgDuration} ${avgDuration === 1 ? 'Tag' : 'Tage'}`} sub="Über alle Vorgänge" icon={icons.cal} />
                <RaKpi label="Aktiv jetzt" value={`${activeNow}`} sub="Laufende Vermietungen" icon={icons.truck} color={t.green} />
                <RaKpi label="Reserviert" value={`${reservedNow}`} sub="Geplant für später" icon={icons.clock || icons.cal} color={t.orange} />
                <RaKpi label="Lieferanteil" value={`${deliveryPct}%`} sub={`${deliveryCount} mit Lieferung`} icon={icons.truck} color={t.accent} />
                <RaKpi label="Selbstabholer" value={`${totalCount - deliveryCount}`} sub={`${100 - deliveryPct}% holen ab`} icon={icons.user} />
              </div>

              {/* Umsatz-Verlauf */}
              <RaSection title="Umsatz-Verlauf" sub={`Monatlicher Mietumsatz · ${months.length} Monate`}>
                <div style={{ ...card }}>
                  <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 200, paddingBottom: 28, borderBottom: `0.5px solid ${t.sep}`, position: 'relative' }}>
                    {monthlyTotal.map((m) => {
                    const h = m.value / maxMonthly * 170;
                    return (
                      <div key={m.key} title={`${m.label}: ${Math.round(m.value).toLocaleString('de-DE')} € · ${m.count} Vorgänge`} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                          <div style={{ fontSize: 10, color: t.text, fontWeight: 700, opacity: m.value > 0 ? 1 : 0.3, ...NUMS }}>{m.value > 0 ? Math.round(m.value) + '€' : ''}</div>
                          <div style={{ width: '72%', height: Math.max(2, h), borderRadius: 4, background: m.isCurrent ? t.accent : t.green }} />
                        </div>);

                  })}
                    <div style={{ position: 'absolute', bottom: 6, left: 0, right: 0, display: 'flex', gap: 6 }}>
                      {monthlyTotal.map((m) =>
                    <div key={m.key} style={{ flex: 1, textAlign: 'center', fontSize: 10.5, color: m.isCurrent ? t.text : t.textSec, fontWeight: m.isCurrent ? 700 : 500 }}>{m.label}</div>
                    )}
                    </div>
                  </div>
                </div>
              </RaSection>

              {/* Top Verwendungszwecke (kompakt auf Übersicht) */}
              {purposes.length > 0 &&
            <RaSection title="Häufigste Verwendungszwecke" sub="Wofür werden die Geräte vermietet?">
                  <div style={{ ...card }}>
                    {purposes.slice(0, 5).map((p, i, arr) => {
                  const maxC = Math.max(1, ...arr.map((x) => x.count));
                  const pct = p.count / maxC * 100;
                  return (
                    <div key={p.purpose} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 4px', borderBottom: i === arr.length - 1 ? 'none' : `0.5px solid ${t.sep}` }}>
                          <div style={{ width: 22, fontSize: 11, fontWeight: 700, color: t.textTer, textAlign: 'center', ...NUMS }}>{i + 1}</div>
                          <div style={{ flex: 1, fontSize: 13.5, fontWeight: 600, color: t.text }}>{p.purpose}</div>
                          <div style={{ width: 240, height: 8, borderRadius: 4, background: t.chipStrong, overflow: 'hidden' }}>
                            <div style={{ width: `${pct}%`, height: '100%', background: t.accent, borderRadius: 4 }} />
                          </div>
                          <div style={{ width: 60, textAlign: 'right', fontSize: 13, fontWeight: 700, color: t.text, ...NUMS }}>{p.count}×</div>
                          <div style={{ width: 90, textAlign: 'right', fontSize: 12.5, fontWeight: 700, color: t.green, ...NUMS }}>{Math.round(p.revenue).toLocaleString('de-DE')} €</div>
                        </div>);

                })}
                  </div>
                </RaSection>
            }
            </>
          }

          {tab === 'usage' &&
          <>
              {/* Wochentag-Heatmap */}
              <RaSection title="Abholungen nach Wochentag" sub="An welchen Tagen starten die meisten Mietvorgänge?">
                <div style={{ ...card }}>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 8 }}>
                    {weekdayLabels.map((lbl, i) => {
                    const intensity = weekdayCounts[i] / weekdayMax;
                    const isWeekend = i >= 5;
                    const cellColor = isWeekend ? t.accent : t.green;
                    return (
                      <div key={lbl} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                          <div style={{ fontSize: 11, fontWeight: 700, color: t.textSec, letterSpacing: 0.4 }}>{lbl}</div>
                          <div style={{
                          width: '100%', minHeight: 80, borderRadius: 10,
                          background: weekdayCounts[i] > 0 ?
                          `linear-gradient(180deg, ${cellColor + Math.round(Math.max(0.18, intensity) * 255).toString(16).padStart(2, '0').toUpperCase()} 0%, ${cellColor + Math.round(Math.max(0.32, intensity * 1.2) * 255).toString(16).padStart(2, '0').toUpperCase()} 100%)` :
                          t.cardAlt,
                          border: `0.5px solid ${t.sep}`,
                          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', padding: '8px 4px'
                        }}>
                            <div style={{ fontSize: 20, fontWeight: 700, color: weekdayCounts[i] > 0 ? '#fff' : t.textTer, ...NUMS, lineHeight: 1 }}>{weekdayCounts[i]}</div>
                            <div style={{ fontSize: 10, fontWeight: 600, color: weekdayCounts[i] > 0 ? '#ffffffc0' : t.textTer, marginTop: 4, ...NUMS }}>{Math.round(weekdayRevenue[i]).toLocaleString('de-DE')} €</div>
                          </div>
                        </div>);

                  })}
                  </div>
                  <div style={{ marginTop: 12, fontSize: 11.5, color: t.textSec, display: 'flex', gap: 14, justifyContent: 'center' }}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><span style={{ width: 8, height: 8, borderRadius: 2, background: t.green }} /> Werktag</span>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}><span style={{ width: 8, height: 8, borderRadius: 2, background: t.accent }} /> Wochenende</span>
                  </div>
                </div>
              </RaSection>

              {/* Saisonalität */}
              <RaSection title="Saisonalität" sub="Vorgänge pro Kalendermonat — wo liegen die Spitzen?">
                <div style={{ ...card }}>
                  <div style={{ display: 'flex', alignItems: 'flex-end', gap: 5, height: 150, paddingBottom: 22, borderBottom: `0.5px solid ${t.sep}`, position: 'relative' }}>
                    {monthBuckets.map((c, i) => {
                    const h = c / monthMax * 120;
                    return (
                      <div key={i} title={`${DE_MONTHS[i]}: ${c} Vorgänge · ${Math.round(monthRevenue[i]).toLocaleString('de-DE')} €`} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5 }}>
                          <div style={{ fontSize: 10, color: t.text, fontWeight: 700, opacity: c > 0 ? 1 : 0.3, ...NUMS }}>{c > 0 ? c : ''}</div>
                          <div style={{ width: '70%', height: Math.max(2, h), borderRadius: 4, background: c === monthMax && c > 0 ? t.accent : t.text + '88' }} />
                        </div>);

                  })}
                    <div style={{ position: 'absolute', bottom: 4, left: 0, right: 0, display: 'flex', gap: 5 }}>
                      {DE_MONTHS_SHORT.map((m, i) =>
                    <div key={i} style={{ flex: 1, textAlign: 'center', fontSize: 10, color: t.textSec, fontWeight: 500 }}>{m}</div>
                    )}
                    </div>
                  </div>
                  {(() => {
                  const peak = monthBuckets.indexOf(monthMax);
                  if (monthMax > 0) return (
                    <div style={{ marginTop: 12, fontSize: 12, color: t.textSec, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <span>Spitzenmonat: <b style={{ color: t.accent }}>{DE_MONTHS[peak]}</b> mit {monthMax} Vorgängen</span>
                        <span style={{ ...NUMS }}>{Math.round(monthRevenue[peak]).toLocaleString('de-DE')} €</span>
                      </div>);

                  return null;
                })()}
                </div>
              </RaSection>

              {/* Dauer-Verteilung */}
              <RaSection title="Mietdauer-Verteilung" sub={`Ø ${avgDuration} ${avgDuration === 1 ? 'Tag' : 'Tage'} pro Vorgang`}>
                <div style={{ ...card }}>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
                    {durationBuckets.map((b) => {
                    const pct = b.n / durationMax * 100;
                    const sharePct = totalCount > 0 ? Math.round(b.n / totalCount * 100) : 0;
                    return (
                      <div key={b.label} style={{ background: t.cardAlt, borderRadius: 10, padding: '12px 14px', border: `0.5px solid ${t.sep}` }}>
                          <div style={{ fontSize: 11, color: t.textSec, fontWeight: 700, textTransform: 'uppercase', letterSpacing: 0.5 }}>{b.label}</div>
                          <div style={{ fontSize: 22, fontWeight: 700, color: t.text, marginTop: 6, ...NUMS }}>{b.n}</div>
                          <div style={{ fontSize: 11, color: t.textSec, marginTop: 1, ...NUMS }}>{sharePct}% · {Math.round(b.rev).toLocaleString('de-DE')} €</div>
                          <div style={{ height: 5, borderRadius: 3, background: t.chipStrong, overflow: 'hidden', marginTop: 8 }}>
                            <div style={{ width: `${pct}%`, height: '100%', background: t.accent, borderRadius: 3 }} />
                          </div>
                        </div>);

                  })}
                  </div>
                </div>
              </RaSection>
            </>
          }

          {tab === 'purpose' &&
          <>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
                <RaKpi label="Verwendungszwecke" value={`${purposes.length}`} sub="Unterschiedliche Anlässe" icon={icons.bolt} color={t.accent} />
                <RaKpi label="Häufigster Zweck" value={purposes[0] ? purposes[0].purpose : '—'} sub={purposes[0] ? `${purposes[0].count} Vorgänge` : 'Keine Daten'} icon={icons.star} color="#AF52DE" />
                <RaKpi label="Umsatzstärkster Zweck" value={(() => {const top = [...purposes].sort((a, b) => b.revenue - a.revenue)[0];return top ? top.purpose : '—';})()} sub={(() => {const top = [...purposes].sort((a, b) => b.revenue - a.revenue)[0];return top ? `${Math.round(top.revenue).toLocaleString('de-DE')} €` : '';})()} icon={icons.euro} color={t.green} />
              </div>

              <RaSection title="Verwendungszwecke im Detail" sub="Anzahl, Umsatz und durchschnittliche Mietdauer pro Anlass">
                <div style={{ ...card, padding: 0 }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '36px 2fr 1fr 1fr 1fr 1fr', padding: '11px 16px', borderBottom: `0.5px solid ${t.sep}`, background: t.cardAlt, fontSize: 10.5, fontWeight: 700, color: t.textSec, textTransform: 'uppercase', letterSpacing: 0.5 }}>
                    <div>#</div>
                    <div>Zweck</div>
                    <div style={{ textAlign: 'right' }}>Anzahl</div>
                    <div style={{ textAlign: 'right' }}>Ø Dauer</div>
                    <div style={{ textAlign: 'right' }}>Umsatz</div>
                    <div style={{ textAlign: 'right' }}>Ø Vorgang</div>
                  </div>
                  {purposes.length === 0 ?
                <div style={{ padding: '32px 16px', textAlign: 'center', fontSize: 13, color: t.textSec }}>Keine Daten im Zeitraum.</div> :
                purposes.map((p, i) => {
                  const avg = p.count > 0 ? Math.round(p.days / p.count * 10) / 10 : 0;
                  const perVorgang = p.count > 0 ? Math.round(p.revenue / p.count) : 0;
                  return (
                    <div key={p.purpose} style={{ display: 'grid', gridTemplateColumns: '36px 2fr 1fr 1fr 1fr 1fr', padding: '12px 16px', borderBottom: i === purposes.length - 1 ? 'none' : `0.5px solid ${t.sep}`, alignItems: 'center' }}>
                        <div style={{ fontSize: 12, fontWeight: 700, color: t.textTer, ...NUMS }}>{i + 1}</div>
                        <div style={{ fontSize: 13, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{p.purpose}</div>
                        <div style={{ textAlign: 'right', fontSize: 13, fontWeight: 700, color: t.text, ...NUMS }}>{p.count}×</div>
                        <div style={{ textAlign: 'right', fontSize: 12.5, color: t.textSec, ...NUMS }}>{avg} {avg === 1 ? 'Tag' : 'Tage'}</div>
                        <div style={{ textAlign: 'right', fontSize: 13, fontWeight: 700, color: t.green, ...NUMS }}>{Math.round(p.revenue).toLocaleString('de-DE')} €</div>
                        <div style={{ textAlign: 'right', fontSize: 12.5, color: t.text, ...NUMS }}>{perVorgang} €</div>
                      </div>);

                })}
                </div>
              </RaSection>
            </>
          }

          {tab === 'logistics' &&
          <>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
                <RaKpi label="Lieferanteil" value={`${deliveryPct}%`} sub={`${deliveryCount} von ${totalCount} mit Lieferung`} icon={icons.truck} color={t.accent} />
                <RaKpi label="Selbstabholer" value={`${selfPickup.length}`} sub={`${100 - deliveryPct}% holen selbst ab`} icon={icons.user} />
                <RaKpi label="Gefahrene km" value={`${Math.round(totalKm).toLocaleString('de-DE')}`} sub={`Ø ${avgKm} km pro Lieferung`} icon={icons.truck} color={t.green} />
                <RaKpi label="Liefer-Umsatz" value={`${Math.round(deliveryRevenue).toLocaleString('de-DE')} €`} sub="Pauschalen + km-Sätze" icon={icons.euro} color={t.green} />
              </div>

              {/* Trip-factor mix */}
              <RaSection title="Liefer-Modus" sub="Wie häufig welcher Fahrt-Faktor (1× bis 4×)">
                <div style={{ ...card }}>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
                    {TRIP_OPTIONS.map((opt) => {
                    const n = tripFactorMix[opt.f] || 0;
                    const pct = withDelivery.length > 0 ? Math.round(n / withDelivery.length * 100) : 0;
                    return (
                      <div key={opt.f} style={{ background: t.cardAlt, borderRadius: 10, padding: '12px 14px', border: `0.5px solid ${t.sep}` }}>
                          <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
                            <div style={{ fontSize: 14, fontWeight: 700, color: t.text }}>{opt.label}</div>
                            <div style={{ fontSize: 10.5, color: t.textSec, fontWeight: 600 }}>{opt.sub}</div>
                          </div>
                          <div style={{ fontSize: 22, fontWeight: 700, color: t.text, marginTop: 6, ...NUMS }}>{n}</div>
                          <div style={{ fontSize: 11.5, color: t.textSec, marginTop: 1, ...NUMS }}>{pct}% der Lieferungen</div>
                          <div style={{ height: 5, borderRadius: 3, background: t.chipStrong, overflow: 'hidden', marginTop: 8 }}>
                            <div style={{ width: `${pct}%`, height: '100%', background: t.accent, borderRadius: 3 }} />
                          </div>
                        </div>);

                  })}
                  </div>
                </div>
              </RaSection>

              {/* Top-Lieferorte */}
              <RaSection title="Top-Lieferorte" sub="Wohin fahren wir am häufigsten?">
                <div style={{ ...card }}>
                  {topCities.length === 0 ?
                <div style={{ padding: '16px 4px', textAlign: 'center', fontSize: 13, color: t.textSec }}>Keine Lieferadressen im Zeitraum.</div> :
                topCities.map(([city, n], i) => {
                  const pct = n / topCities[0][1] * 100;
                  return (
                    <div key={city} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 4px', borderBottom: i === topCities.length - 1 ? 'none' : `0.5px solid ${t.sep}` }}>
                        <div style={{ width: 22, fontSize: 11, fontWeight: 700, color: t.textTer, textAlign: 'center', ...NUMS }}>{i + 1}</div>
                        <div style={{ flex: 1, fontSize: 13, fontWeight: 600, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{city}</div>
                        <div style={{ width: 260, height: 7, borderRadius: 4, background: t.chipStrong, overflow: 'hidden' }}>
                          <div style={{ width: `${pct}%`, height: '100%', background: t.accent, borderRadius: 4 }} />
                        </div>
                        <div style={{ width: 60, textAlign: 'right', fontSize: 13, fontWeight: 700, color: t.text, ...NUMS }}>{n}×</div>
                      </div>);

                })}
                </div>
              </RaSection>

              {/* Längste Touren */}
              <RaSection title="Längste Lieferungen" sub="Wo lohnt sich eine Kilometer-Pauschale am ehesten?">
                <div style={{ ...card, padding: 0 }}>
                  {[...withDelivery].sort((a, b) => (Number(b.delivery.km) || 0) - (Number(a.delivery.km) || 0)).slice(0, 6).map((r, i, arr) => {
                  const km = Number(r.delivery.km) || 0;
                  const fee = rentalDeliveryFee(r);
                  const factor = r.delivery.tripFactor || LOGISTIK_DEFAULTS.tripFactor;
                  return (
                    <Pressable key={r.id} onClick={() => {go && go('rentals', { rentalId: r.id });onClose();}} scale={0.998} hoverBg={t.cardAlt}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 14px', borderBottom: i === arr.length - 1 ? 'none' : `0.5px solid ${t.sep}` }}>
                          <Avatar name={r.tenantName} size={32} />
                          <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, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{r.purpose || '—'} · {fmtRange(r.start, r.end)}</div>
                          </div>
                          <div style={{ textAlign: 'right', flexShrink: 0 }}>
                            <div style={{ fontSize: 13, fontWeight: 700, color: t.text, ...NUMS }}>{km.toString().replace('.', ',')} km</div>
                            <div style={{ fontSize: 10.5, color: t.textSec, ...NUMS }}>×{factor} Fahrten</div>
                          </div>
                          <div style={{ width: 80, textAlign: 'right', flexShrink: 0 }}>
                            <div style={{ fontSize: 13, fontWeight: 700, color: t.green, ...NUMS }}>{fee.toFixed(2).replace('.', ',')} €</div>
                            <div style={{ fontSize: 10.5, color: t.textSec }}>Liefer-Fee</div>
                          </div>
                        </div>
                      </Pressable>);

                })}
                  {withDelivery.length === 0 &&
                <div style={{ padding: '32px 16px', textAlign: 'center', fontSize: 13, color: t.textSec }}>Keine Lieferungen im Zeitraum.</div>
                }
                </div>
              </RaSection>
            </>
          }

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

}

Object.assign(window, { RentalsAnalyseSheet });