// MissionChef — Vollständige Mitarbeiterverwaltung
// Tabs: Übersicht · Onboarding · Offboarding · Personalakte · Stunden · Export

function fmtDate(iso) {
  if (!iso) return '—';
  return new Date(iso).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit', year: 'numeric' });
}
function fmtDateShort(iso) {
  if (!iso) return '—';
  return new Date(iso).toLocaleDateString('de-DE', { day: '2-digit', month: '2-digit' });
}
function fmtTime(iso) {
  if (!iso) return '—';
  return new Date(iso).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
}
function daysSince(iso) {
  return Math.floor((Date.now() - new Date(iso).getTime()) / (1000 * 60 * 60 * 24));
}

// ─── Avatar helper ─────────────────────────────────────────────────────────────
function Avatar({ u, size = 40 }) {
  return (
    <div style={{
      width: size, height: size, background: u.color || '#8A8178', color: '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontSize: size * 0.38, fontWeight: 600, flexShrink: 0,
      fontFamily: "'Space Grotesk', sans-serif",
    }}>
      {u.name.split(' ').map(n => n[0]).join('').slice(0,2)}
    </div>
  );
}

function StatusPill({ status }) {
  const map = {
    active: { tone: 'leaf', label: 'Aktiv' },
    onboarding: { tone: 'info', label: 'Onboarding' },
    offboarding: { tone: 'ember', label: 'Offboarding' },
    offboarded: { tone: 'default', label: 'Ausgeschieden' },
  };
  const m = map[status] || map.active;
  return <Pill tone={m.tone}>{m.label}</Pill>;
}

// ─── Main Screen ───────────────────────────────────────────────────────────────
function StaffScreen({ Topbar }) {
  const store = useStore();
  const [tab, setTab] = React.useState('overview');
  const [selectedId, setSelectedId] = React.useState(null);
  const [showHire, setShowHire] = React.useState(false);

  const selected = store.staff.find(s => s.id === selectedId);

  const tabs = [
    { id: 'overview', label: 'Team-Übersicht', icon: 'team' },
    { id: 'onboarding', label: 'Onboarding', icon: 'plus' },
    { id: 'offboarding', label: 'Offboarding', icon: 'arrow' },
    { id: 'hours', label: 'Stunden-Dashboard', icon: 'clock' },
    { id: 'export', label: 'Export & Lohn', icon: 'chart' },
  ];

  return (
    <>
      <Topbar
        title="Mitarbeiter"
        subtitle={`${store.staff.filter(s => s.status !== 'offboarded').length} Team · ${store.staff.filter(s => s.status === 'onboarding').length} im Onboarding · ${store.staff.filter(s => s.status === 'offboarding').length} im Austritt`}
        actions={<button className="mc-btn leaf sm" onClick={() => setShowHire(true)}><McIcon2 name="plus" size={14} />Einstellen</button>}
      />

      {/* Tabs */}
      <div style={{ borderBottom: '1px solid var(--mc-rule)', background: 'var(--mc-surface)', padding: '0 28px', display: 'flex', gap: 0, flexShrink: 0 }}>
        {tabs.map(t => (
          <button key={t.id} onClick={() => { setTab(t.id); setSelectedId(null); }} style={{
            padding: '14px 16px', background: 'transparent', border: 'none',
            borderBottom: tab === t.id ? '2px solid var(--mc-leaf)' : '2px solid transparent',
            color: tab === t.id ? 'var(--mc-ink)' : 'var(--mc-ink-muted)',
            fontSize: 13, fontWeight: tab === t.id ? 500 : 400, cursor: 'pointer',
            fontFamily: "'Space Grotesk', sans-serif",
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <McIcon2 name={t.icon} size={14} />{t.label}
          </button>
        ))}
      </div>

      <div className="mc-scroll" style={{ flex: 1, overflow: 'auto', background: 'var(--mc-bg)' }}>
        {tab === 'overview' && <StaffOverview staff={store.staff} onSelect={setSelectedId} />}
        {tab === 'onboarding' && <OnboardingBoard staff={store.staff.filter(s => s.onboarding && s.onboarding.status !== 'complete')} onSelect={setSelectedId} />}
        {tab === 'offboarding' && <OffboardingBoard staff={store.staff.filter(s => s.offboarding && s.offboarding.status !== 'complete')} onSelect={setSelectedId} />}
        {tab === 'hours' && <HoursDashboard staff={store.staff} entries={store.timeEntries} />}
        {tab === 'export' && <ExportCenter config={store.exportConfig} entries={store.timeEntries} staff={store.staff} />}
      </div>

      {/* Personnel file drawer */}
      {selected && <PersonnelDrawer user={selected} onClose={() => setSelectedId(null)} />}
      {showHire && <HireModal onClose={() => setShowHire(false)} />}
    </>
  );
}

// ─── Overview ──────────────────────────────────────────────────────────────────
function StaffOverview({ staff, onSelect }) {
  const [area, setArea] = React.useState('Alle');
  const [status, setStatus] = React.useState('Alle');
  const AREAS = ['Alle', 'Küche', 'Service', 'Management'];
  const STATUSES = ['Alle', 'active', 'onboarding', 'offboarding'];
  const STATUS_LABEL = { 'Alle': 'Alle Status', active: 'Aktiv', onboarding: 'Onboarding', offboarding: 'Offboarding' };
  const filtered = staff.filter(s => (area === 'Alle' || s.area === area) && (status === 'Alle' || s.status === status));

  // quick stats
  const active = staff.filter(s => s.status === 'active' || s.status === 'onboarding').length;
  const totalHours = staff.reduce((s, u) => s + (u.contractHours || 0), 0);
  const avgTenure = Math.round(staff.filter(s=>s.hiredAt).reduce((sum, u) => sum + daysSince(u.hiredAt), 0) / staff.length / 30);
  const expiringCerts = staff.reduce((n, u) => n + u.certifications.filter(c => c.status === 'expiring' || c.status === 'expired').length, 0);

  return (
    <div style={{ padding: 28 }}>
      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 24 }}>
        <Kpi label="Aktive Mitarbeiter" value={active} sub={`von ${staff.length} gesamt`} />
        <Kpi label="Ø Betriebszugehörigkeit" value={avgTenure + ' Mon.'} />
        <Kpi label="Vertragsstunden/Woche" value={totalHours + 'h'} />
        <Kpi label="Ablaufende Zertifikate" value={expiringCerts} tone={expiringCerts > 0 ? 'ember' : 'leaf'} />
      </div>

      {/* Filters */}
      <div style={{ display: 'flex', gap: 10, marginBottom: 16, alignItems: 'center', flexWrap: 'wrap' }}>
        <span className="mc-eyebrow" style={{ marginRight: 4 }}>Bereich</span>
        {AREAS.map(a => (
          <button key={a} onClick={() => setArea(a)} className={area === a ? 'mc-btn sm' : 'mc-btn ghost sm'}>{a}</button>
        ))}
        <span className="mc-eyebrow" style={{ marginLeft: 16, marginRight: 4 }}>Status</span>
        {STATUSES.map(s => (
          <button key={s} onClick={() => setStatus(s)} className={status === s ? 'mc-btn sm' : 'mc-btn ghost sm'}>{STATUS_LABEL[s]}</button>
        ))}
      </div>

      {/* Employee cards */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
        {filtered.map(u => {
          const tenure = daysSince(u.hiredAt);
          const tenureLabel = tenure < 30 ? `${tenure}T` : tenure < 365 ? `${Math.floor(tenure/30)}M` : `${(tenure/365).toFixed(1)}J`;
          const hasExpiring = u.certifications.some(c => c.status === 'expiring' || c.status === 'expired');
          return (
            <div key={u.id} className="mc-card" style={{ padding: 20, cursor: 'pointer' }} onClick={() => onSelect(u.id)}>
              <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start' }}>
                <Avatar u={u} size={48} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
                    <div style={{ fontSize: 15, fontWeight: 500 }}>{u.name}</div>
                    <StatusPill status={u.status} />
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--mc-ink-dim)', marginTop: 2 }}>{u.role}</div>
                </div>
              </div>

              <div style={{ display: 'flex', gap: 6, marginTop: 12, flexWrap: 'wrap' }}>
                <Pill>{u.area}</Pill>
                <Pill>{u.employmentType}</Pill>
                {hasExpiring && <Pill tone="ember">Zert. prüfen</Pill>}
              </div>

              <div style={{ marginTop: 14, paddingTop: 14, borderTop: '1px solid var(--mc-rule)', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
                <div>
                  <div className="mc-eyebrow">Dabei seit</div>
                  <div className="mc-num" style={{ marginTop: 3, fontSize: 13, fontWeight: 500 }}>{tenureLabel}</div>
                </div>
                <div>
                  <div className="mc-eyebrow">Std./W</div>
                  <div className="mc-num" style={{ marginTop: 3, fontSize: 13, fontWeight: 500 }}>{u.contractHours}h</div>
                </div>
                <div>
                  <div className="mc-eyebrow">Urlaub</div>
                  <div className="mc-num" style={{ marginTop: 3, fontSize: 13, fontWeight: 500 }}>{u.vacation.entitled - u.vacation.taken - u.vacation.pending}T</div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── Onboarding Board ──────────────────────────────────────────────────────────
function OnboardingBoard({ staff, onSelect }) {
  return (
    <div style={{ padding: 28 }}>
      <div className="mc-card" style={{ padding: 22, marginBottom: 20, background: 'var(--mc-leaf-50, #F4F7E7)', borderColor: 'var(--mc-leaf)' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
          <div style={{ width: 40, height: 40, background: 'var(--mc-leaf)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <McIcon2 name="plus" size={20} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 500 }}>Onboarding-Pipeline</div>
            <div style={{ fontSize: 12, color: 'var(--mc-ink-dim)' }}>{staff.length} Mitarbeiter gerade im Einarbeitungsprozess. 10 Schritte gemäß Standard-Checkliste.</div>
          </div>
        </div>
      </div>

      {staff.length === 0 && (
        <div className="mc-card" style={{ padding: 40, textAlign: 'center' }}>
          <div style={{ fontSize: 14, color: 'var(--mc-ink-dim)' }}>Aktuell niemand im Onboarding.</div>
        </div>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {staff.map(u => {
          const done = u.onboarding.steps.filter(s => s.done).length;
          const total = u.onboarding.steps.length;
          const pct = Math.round((done / total) * 100);
          const daysInProcess = daysSince(u.onboarding.startedAt);
          return (
            <div key={u.id} className="mc-card" style={{ padding: 22 }}>
              <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
                <Avatar u={u} size={48} />
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 4 }}>
                    <div>
                      <div style={{ fontSize: 17, fontWeight: 500 }}>{u.name}</div>
                      <div style={{ fontSize: 12, color: 'var(--mc-ink-dim)' }}>{u.role} · {u.area} · seit {fmtDateShort(u.hiredAt)} · Tag {daysInProcess + 1}</div>
                    </div>
                    <button className="mc-btn ghost sm" onClick={() => onSelect(u.id)}>Akte öffnen →</button>
                  </div>

                  {/* Progress */}
                  <div style={{ marginTop: 14, marginBottom: 14 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 12 }}>
                      <span className="mc-eyebrow">Fortschritt</span>
                      <span className="mc-num" style={{ fontWeight: 500 }}>{done}/{total} · {pct}%</span>
                    </div>
                    <div style={{ height: 8, background: 'var(--mc-rule)', position: 'relative' }}>
                      <div style={{ height: '100%', width: pct + '%', background: 'var(--mc-leaf)', transition: 'width .3s' }} />
                    </div>
                  </div>

                  {/* Checklist grid */}
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
                    {u.onboarding.steps.map(step => (
                      <label key={step.id} style={{
                        display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px',
                        border: '1px solid var(--mc-rule)', cursor: 'pointer',
                        background: step.done ? 'var(--mc-surface-2)' : 'transparent',
                      }}>
                        <input
                          type="checkbox" checked={step.done}
                          onChange={(e) => mcApi.patch(`/staff/${u.id}/onboarding/${step.id}`, { done: e.target.checked })}
                          style={{ accentColor: 'var(--mc-leaf-700)' }}
                        />
                        <span style={{ fontSize: 12, flex: 1, textDecoration: step.done ? 'line-through' : 'none', color: step.done ? 'var(--mc-ink-dim)' : 'var(--mc-ink)' }}>
                          {step.label}
                        </span>
                        {step.doneAt && <span className="mc-mono" style={{ fontSize: 10, color: 'var(--mc-ink-dim)' }}>{fmtDateShort(step.doneAt)}</span>}
                      </label>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── Offboarding Board ─────────────────────────────────────────────────────────
function OffboardingBoard({ staff, onSelect }) {
  return (
    <div style={{ padding: 28 }}>
      <div className="mc-card" style={{ padding: 22, marginBottom: 20, background: 'var(--mc-ember-50, #FDECE0)', borderColor: 'var(--mc-ember)' }}>
        <div style={{ display: 'flex', gap: 14, alignItems: 'center' }}>
          <div style={{ width: 40, height: 40, background: 'var(--mc-ember)', color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <McIcon2 name="arrow" size={20} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 16, fontWeight: 500 }}>Offboarding-Pipeline</div>
            <div style={{ fontSize: 12, color: 'var(--mc-ink-dim)' }}>{staff.length} Austritt(e) in Bearbeitung. 8 Schritte — Schlüssel, Zugänge, Endabrechnung, Zeugnis.</div>
          </div>
        </div>
      </div>

      {staff.length === 0 && (
        <div className="mc-card" style={{ padding: 40, textAlign: 'center' }}>
          <div style={{ fontSize: 14, color: 'var(--mc-ink-dim)' }}>Kein Austritt in Bearbeitung.</div>
        </div>
      )}

      <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        {staff.map(u => {
          const done = u.offboarding.steps.filter(s => s.done).length;
          const total = u.offboarding.steps.length;
          const pct = Math.round((done / total) * 100);
          const daysLeft = u.offboarding.lastDay ? Math.ceil((new Date(u.offboarding.lastDay) - new Date()) / (1000 * 60 * 60 * 24)) : null;
          return (
            <div key={u.id} className="mc-card" style={{ padding: 22 }}>
              <div style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
                <Avatar u={u} size={48} />
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 4 }}>
                    <div>
                      <div style={{ fontSize: 17, fontWeight: 500 }}>{u.name}</div>
                      <div style={{ fontSize: 12, color: 'var(--mc-ink-dim)' }}>{u.role} · Letzter Tag: {fmtDate(u.offboarding.lastDay)} {daysLeft !== null && <span style={{ color: daysLeft < 7 ? 'var(--mc-ember-700)' : 'var(--mc-ink-dim)' }}>· noch {daysLeft}T</span>}</div>
                      {u.offboarding.reason && <div style={{ fontSize: 12, fontStyle: 'italic', marginTop: 2, color: 'var(--mc-ink-dim)' }}>Grund: {u.offboarding.reason}</div>}
                    </div>
                    <button className="mc-btn ghost sm" onClick={() => onSelect(u.id)}>Akte öffnen →</button>
                  </div>

                  <div style={{ marginTop: 14, marginBottom: 14 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6, fontSize: 12 }}>
                      <span className="mc-eyebrow">Fortschritt</span>
                      <span className="mc-num" style={{ fontWeight: 500 }}>{done}/{total} · {pct}%</span>
                    </div>
                    <div style={{ height: 8, background: 'var(--mc-rule)' }}>
                      <div style={{ height: '100%', width: pct + '%', background: 'var(--mc-ember)', transition: 'width .3s' }} />
                    </div>
                  </div>

                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
                    {u.offboarding.steps.map(step => (
                      <label key={step.id} style={{
                        display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px',
                        border: '1px solid var(--mc-rule)', cursor: 'pointer',
                        background: step.done ? 'var(--mc-surface-2)' : 'transparent',
                      }}>
                        <input
                          type="checkbox" checked={step.done}
                          onChange={(e) => mcApi.patch(`/staff/${u.id}/offboarding/${step.id}`, { done: e.target.checked })}
                          style={{ accentColor: 'var(--mc-ember-700)' }}
                        />
                        <span style={{ fontSize: 12, flex: 1, textDecoration: step.done ? 'line-through' : 'none', color: step.done ? 'var(--mc-ink-dim)' : 'var(--mc-ink)' }}>
                          {step.label}
                        </span>
                        {step.doneAt && <span className="mc-mono" style={{ fontSize: 10, color: 'var(--mc-ink-dim)' }}>{fmtDateShort(step.doneAt)}</span>}
                      </label>
                    ))}
                  </div>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── Hours Dashboard ───────────────────────────────────────────────────────────
function HoursDashboard({ staff, entries }) {
  const today = new Date(); today.setHours(0,0,0,0);
  const [month, setMonth] = React.useState(today.toISOString().slice(0,7));
  const [selectedUid, setSelectedUid] = React.useState(staff[0]?.id);

  const monthEntries = entries.filter(e => e.date.startsWith(month));

  // Aggregate per user
  const perUser = staff.map(u => {
    const ue = monthEntries.filter(e => e.uid === u.id);
    const hours = ue.reduce((s, e) => s + e.hoursWorked, 0);
    const overtime = ue.reduce((s, e) => s + e.overtime, 0);
    const night = ue.reduce((s, e) => s + e.nightHours, 0);
    const days = ue.length;
    const contractMonthly = u.contractHours * 4.33;
    return { u, hours: Math.round(hours*10)/10, overtime: Math.round(overtime*10)/10, night: Math.round(night*10)/10, days, contractMonthly, delta: Math.round((hours - contractMonthly)*10)/10 };
  }).sort((a,b) => b.hours - a.hours);

  const totalHours = perUser.reduce((s,p) => s + p.hours, 0);
  const totalOvertime = perUser.reduce((s,p) => s + p.overtime, 0);
  const totalLabor = perUser.reduce((s,p) => s + p.hours * p.u.wage, 0);

  const selected = perUser.find(p => p.u.id === selectedUid);

  // Month options (last 6 months)
  const monthOpts = [];
  for (let i = 0; i < 6; i++) {
    const d = new Date(today); d.setMonth(d.getMonth() - i); d.setDate(1);
    monthOpts.push(d.toISOString().slice(0,7));
  }

  return (
    <div style={{ padding: 28 }}>
      {/* Month selector + KPIs */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <span className="mc-eyebrow">Abrechnungsmonat</span>
          <select value={month} onChange={e => setMonth(e.target.value)} style={{
            padding: '8px 12px', border: '1px solid var(--mc-rule)', background: 'var(--mc-surface)',
            color: 'var(--mc-ink)', fontFamily: "'Space Grotesk', sans-serif", fontSize: 13,
          }}>
            {monthOpts.map(m => <option key={m} value={m}>{new Date(m + '-01').toLocaleDateString('de-DE', { month: 'long', year: 'numeric' })}</option>)}
          </select>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button className="mc-btn ghost sm"><McIcon2 name="arrow" size={14} />CSV</button>
          <button className="mc-btn sm"><McIcon2 name="arrow" size={14} />PDF-Monatsbericht</button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 24 }}>
        <Kpi label="Stunden gesamt" value={totalHours.toFixed(1) + 'h'} sub={`${perUser.filter(p=>p.hours>0).length} Mitarbeiter`} />
        <Kpi label="Überstunden" value={totalOvertime.toFixed(1) + 'h'} tone={totalOvertime > 40 ? 'ember' : 'default'} />
        <Kpi label="Lohnsumme (Brutto)" value={fmtEUR(totalLabor)} />
        <Kpi label="Ø Tage/MA" value={(monthEntries.length / Math.max(1, perUser.filter(p=>p.hours>0).length)).toFixed(1)} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.3fr', gap: 20 }}>
        {/* Per-user list */}
        <div className="mc-card">
          <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--mc-rule)', background: 'var(--mc-surface-2)' }}>
            <div className="mc-eyebrow">Mitarbeiter · {new Date(month + '-01').toLocaleDateString('de-DE', { month: 'long', year: 'numeric' })}</div>
          </div>
          {perUser.map(p => {
            const isSel = selectedUid === p.u.id;
            const fulfillment = p.contractMonthly > 0 ? Math.round((p.hours / p.contractMonthly) * 100) : 0;
            return (
              <button key={p.u.id} onClick={() => setSelectedUid(p.u.id)} style={{
                width: '100%', display: 'grid', gridTemplateColumns: '32px 1fr auto auto', gap: 12, alignItems: 'center',
                padding: '12px 18px', border: 'none', borderBottom: '1px solid var(--mc-rule)',
                background: isSel ? 'var(--mc-surface-2)' : 'transparent',
                borderLeft: isSel ? '3px solid var(--mc-leaf)' : '3px solid transparent',
                cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', color: 'var(--mc-ink)',
              }}>
                <Avatar u={p.u} size={32} />
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{p.u.name}</div>
                  <div style={{ fontSize: 11, color: 'var(--mc-ink-dim)' }}>{p.u.role} · {p.days} Tage</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div className="mc-num" style={{ fontSize: 14, fontWeight: 500 }}>{p.hours.toFixed(1)}h</div>
                  <div className="mc-num" style={{ fontSize: 10, color: p.delta > 0 ? 'var(--mc-ember-700)' : 'var(--mc-ink-dim)' }}>
                    {p.delta > 0 ? '+' : ''}{p.delta}h · {fulfillment}%
                  </div>
                </div>
                <div style={{ width: 60, textAlign: 'right' }}>
                  <div className="mc-num" style={{ fontSize: 12, fontWeight: 500 }}>{fmtEUR(p.hours * p.u.wage)}</div>
                </div>
              </button>
            );
          })}
        </div>

        {/* Selected user detail */}
        {selected && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            <div className="mc-card" style={{ padding: 22 }}>
              <div style={{ display: 'flex', gap: 14, alignItems: 'center', marginBottom: 16 }}>
                <Avatar u={selected.u} size={48} />
                <div>
                  <div style={{ fontSize: 17, fontWeight: 500 }}>{selected.u.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--mc-ink-dim)' }}>{selected.u.role} · {selected.u.employmentType} · {selected.u.contractHours}h/Woche</div>
                </div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
                <DetailStat label="Ist-Stunden" value={selected.hours.toFixed(1) + 'h'} />
                <DetailStat label="Soll (Vertrag)" value={selected.contractMonthly.toFixed(1) + 'h'} />
                <DetailStat label="Überstd." value={selected.overtime.toFixed(1) + 'h'} tone={selected.overtime > 10 ? 'ember' : undefined} />
                <DetailStat label="Nachtstd." value={selected.night.toFixed(1) + 'h'} />
                <DetailStat label="Arbeitstage" value={selected.days + 'T'} />
                <DetailStat label="Stundensatz" value={fmtEUR(selected.u.wage)} />
                <DetailStat label="Brutto-Monat" value={fmtEUR(selected.hours * selected.u.wage)} />
                <DetailStat label="Urlaub offen" value={(selected.u.vacation.entitled - selected.u.vacation.taken - selected.u.vacation.pending) + 'T'} />
              </div>
            </div>

            {/* Entry list */}
            <div className="mc-card">
              <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--mc-rule)', display: 'flex', justifyContent: 'space-between' }}>
                <div className="mc-eyebrow">Zeiteinträge (neueste zuerst)</div>
                <div className="mc-eyebrow">{monthEntries.filter(e => e.uid === selected.u.id).length} Tage</div>
              </div>
              <div style={{ maxHeight: 340, overflow: 'auto' }}>
                <div style={{ display: 'grid', gridTemplateColumns: '90px 70px 70px 50px 60px 50px 60px', padding: '10px 18px', borderBottom: '1px solid var(--mc-rule)', background: 'var(--mc-surface-2)', fontSize: 10 }}>
                  <div className="mc-eyebrow">Datum</div>
                  <div className="mc-eyebrow">Start</div>
                  <div className="mc-eyebrow">Ende</div>
                  <div className="mc-eyebrow">Pause</div>
                  <div className="mc-eyebrow" style={{ textAlign: 'right' }}>Std.</div>
                  <div className="mc-eyebrow" style={{ textAlign: 'right' }}>ÜS</div>
                  <div className="mc-eyebrow" style={{ textAlign: 'right' }}>OK</div>
                </div>
                {monthEntries.filter(e => e.uid === selected.u.id).sort((a,b) => b.date.localeCompare(a.date)).map(e => (
                  <div key={e.id} style={{ display: 'grid', gridTemplateColumns: '90px 70px 70px 50px 60px 50px 60px', padding: '10px 18px', borderBottom: '1px solid var(--mc-rule)', fontSize: 12, alignItems: 'center' }}>
                    <div className="mc-num">{fmtDateShort(e.date)}</div>
                    <div className="mc-num">{fmtTime(e.clockIn)}</div>
                    <div className="mc-num">{fmtTime(e.clockOut)}</div>
                    <div className="mc-num" style={{ color: 'var(--mc-ink-dim)' }}>{e.breakMin}'</div>
                    <div className="mc-num" style={{ textAlign: 'right', fontWeight: 500 }}>{e.hoursWorked.toFixed(1)}</div>
                    <div className="mc-num" style={{ textAlign: 'right', color: e.overtime > 0 ? 'var(--mc-ember-700)' : 'var(--mc-ink-dim)' }}>{e.overtime > 0 ? e.overtime.toFixed(1) : '—'}</div>
                    <div style={{ textAlign: 'right' }}>
                      {e.approved
                        ? <span style={{ color: 'var(--mc-leaf-700)', fontSize: 14 }}>✓</span>
                        : <button onClick={() => mcApi.patch('/time-entries/' + e.id, { approved: true })} className="mc-btn ghost sm" style={{ padding: '2px 8px', fontSize: 10 }}>OK?</button>
                      }
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// ─── Export Center ─────────────────────────────────────────────────────────────
function ExportCenter({ config, entries, staff }) {
  const [cfg, setCfg] = React.useState(config);
  React.useEffect(() => setCfg(config), [config]);

  const patch = (body) => {
    setCfg(prev => ({ ...prev, ...body }));
    mcApi.patch('/export-config', body);
  };

  const today = new Date();
  const currentMonth = today.toISOString().slice(0,7);
  const currentEntries = entries.filter(e => e.date.startsWith(currentMonth));
  const currentHours = currentEntries.reduce((s,e) => s + e.hoursWorked, 0);

  const runExport = () => {
    mcApi.post('/exports/run', {
      period: currentMonth, hours: Math.round(currentHours*10)/10, format: cfg.format,
    }).then(() => {
      // simulate file download
      const blob = new Blob([buildCsv(entries, staff, currentMonth)], { type: 'text/csv' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a'); a.href = url; a.download = `stunden_${currentMonth}.csv`; a.click();
      URL.revokeObjectURL(url);
    });
  };

  return (
    <div style={{ padding: 28, display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: 20 }}>
      {/* Left: Config */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div className="mc-card" style={{ padding: 26 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18 }}>
            <div>
              <div className="mc-eyebrow">Automatischer Export</div>
              <div style={{ fontSize: 18, fontWeight: 500, marginTop: 6 }}>Lohnabrechnung · Stunden-Export</div>
              <div style={{ fontSize: 12, color: 'var(--mc-ink-dim)', marginTop: 4 }}>Läuft automatisch nach Konfiguration. Manueller Lauf jederzeit möglich.</div>
            </div>
            <button onClick={() => patch({ autoEnabled: !cfg.autoEnabled })} style={{
              width: 52, height: 28, borderRadius: 14, border: 'none', cursor: 'pointer',
              background: cfg.autoEnabled ? 'var(--mc-leaf)' : 'var(--mc-rule)',
              position: 'relative', transition: 'background .2s',
            }}>
              <div style={{
                position: 'absolute', top: 2, left: cfg.autoEnabled ? 26 : 2, width: 24, height: 24,
                borderRadius: '50%', background: '#fff', transition: 'left .2s',
                boxShadow: '0 2px 4px rgba(0,0,0,.2)',
              }} />
            </button>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
            <ConfigField label="Intervall">
              <select value={cfg.schedule} onChange={e => patch({ schedule: e.target.value })} disabled={!cfg.autoEnabled} style={cfgSelect}>
                <option value="monthly">Monatlich</option>
                <option value="biweekly">Zweiwöchentlich</option>
                <option value="weekly">Wöchentlich</option>
              </select>
            </ConfigField>
            <ConfigField label="Tag">
              <select value={cfg.dayOfMonth} onChange={e => patch({ dayOfMonth: parseInt(e.target.value) })} disabled={!cfg.autoEnabled} style={cfgSelect}>
                {[1,5,10,15,20,25].map(d => <option key={d} value={d}>{d}. des Monats</option>)}
              </select>
            </ConfigField>
            <ConfigField label="Uhrzeit">
              <input type="time" value={cfg.time} onChange={e => patch({ time: e.target.value })} disabled={!cfg.autoEnabled} style={cfgSelect} />
            </ConfigField>
            <ConfigField label="Format">
              <select value={cfg.format} onChange={e => patch({ format: e.target.value })} style={cfgSelect}>
                <option value="csv">CSV (universal)</option>
                <option value="xlsx">Excel (XLSX)</option>
                <option value="datev">DATEV Lohn und Gehalt</option>
                <option value="pdf">PDF-Bericht</option>
              </select>
            </ConfigField>
            <ConfigField label="Zustellung">
              <select value={cfg.deliver} onChange={e => patch({ deliver: e.target.value })} style={cfgSelect}>
                <option value="email">E-Mail</option>
                <option value="datev">DATEV Unternehmen online</option>
                <option value="download">Nur Download</option>
              </select>
            </ConfigField>
            <ConfigField label="Empfänger-E-Mail">
              <input type="email" value={cfg.email} onChange={e => patch({ email: e.target.value })} style={cfgSelect} />
            </ConfigField>
          </div>

          <div style={{ marginTop: 16, padding: 14, border: '1px solid var(--mc-rule)', display: 'flex', flexDirection: 'column', gap: 8 }}>
            <label style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, cursor: 'pointer' }}>
              <input type="checkbox" checked={cfg.includeOvertime} onChange={e => patch({ includeOvertime: e.target.checked })} style={{ accentColor: 'var(--mc-leaf-700)' }} />
              Überstunden getrennt ausweisen
            </label>
            <label style={{ display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, cursor: 'pointer' }}>
              <input type="checkbox" checked={cfg.includeSickDays} onChange={e => patch({ includeSickDays: e.target.checked })} style={{ accentColor: 'var(--mc-leaf-700)' }} />
              Krankheitstage mitexportieren
            </label>
          </div>

          <div style={{ marginTop: 20, padding: 16, background: 'var(--mc-surface-2)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <div className="mc-eyebrow">Nächster Lauf</div>
              <div style={{ fontSize: 15, fontWeight: 500, marginTop: 3 }}>{cfg.autoEnabled ? fmtDate(cfg.nextRun) + ' · ' + cfg.time : 'Deaktiviert'}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div className="mc-eyebrow">Letzter Lauf</div>
              <div style={{ fontSize: 13, marginTop: 3 }}>{fmtDate(cfg.lastRun)}</div>
            </div>
          </div>
        </div>

        {/* Manual run */}
        <div className="mc-card" style={{ padding: 22 }}>
          <div className="mc-eyebrow">Jetzt exportieren</div>
          <div style={{ fontSize: 16, fontWeight: 500, marginTop: 6, marginBottom: 4 }}>Alle Mitarbeiter · {new Date(currentMonth + '-01').toLocaleDateString('de-DE', { month: 'long', year: 'numeric' })}</div>
          <div style={{ fontSize: 12, color: 'var(--mc-ink-dim)', marginBottom: 14 }}>
            {currentEntries.length} Einträge · {currentHours.toFixed(1)}h Gesamtstunden · {staff.filter(s=>s.status!=='offboarded').length} Mitarbeiter
          </div>
          <div style={{ display: 'flex', gap: 10 }}>
            <button className="mc-btn leaf" onClick={runExport}><McIcon2 name="arrow" size={14} />CSV herunterladen</button>
            <button className="mc-btn ghost" onClick={runExport}>Per E-Mail senden</button>
          </div>
        </div>
      </div>

      {/* Right: History */}
      <div className="mc-card">
        <div style={{ padding: '16px 20px', borderBottom: '1px solid var(--mc-rule)' }}>
          <div className="mc-eyebrow">Export-Historie</div>
          <div style={{ fontSize: 14, fontWeight: 500, marginTop: 4 }}>Vergangene Läufe</div>
        </div>
        {cfg.history.map(h => (
          <div key={h.id} style={{ padding: '14px 20px', borderBottom: '1px solid var(--mc-rule)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div>
              <div style={{ fontSize: 13, fontWeight: 500 }}>{new Date(h.period + '-01').toLocaleDateString('de-DE', { month: 'long', year: 'numeric' })}</div>
              <div style={{ fontSize: 11, color: 'var(--mc-ink-dim)', marginTop: 2 }}>
                {h.employees} MA · {h.hours.toFixed(1)}h · {h.format} · {fmtDate(h.runAt)}
              </div>
            </div>
            <div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
              <Pill tone="leaf">Erfolgreich</Pill>
              <button className="mc-btn ghost sm" style={{ padding: '4px 10px', fontSize: 11 }}>↓</button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

const cfgSelect = {
  width: '100%', padding: '8px 10px', border: '1px solid var(--mc-rule)',
  background: 'var(--mc-surface)', color: 'var(--mc-ink)',
  fontFamily: "'Space Grotesk', sans-serif", fontSize: 13,
};

function ConfigField({ label, children }) {
  return (
    <div>
      <div className="mc-eyebrow" style={{ marginBottom: 6 }}>{label}</div>
      {children}
    </div>
  );
}

function DetailStat({ label, value, tone }) {
  return (
    <div>
      <div className="mc-eyebrow">{label}</div>
      <div className="mc-num" style={{ fontSize: 18, fontWeight: 500, marginTop: 4, color: tone === 'ember' ? 'var(--mc-ember-700)' : 'var(--mc-ink)' }}>{value}</div>
    </div>
  );
}

function Kpi({ label, value, sub, tone }) {
  return (
    <div className="mc-card" style={{ padding: 20 }}>
      <div className="mc-eyebrow">{label}</div>
      <div className="mc-num" style={{ fontSize: 28, fontWeight: 500, marginTop: 6, color: tone === 'ember' ? 'var(--mc-ember-700)' : tone === 'leaf' ? 'var(--mc-leaf-700)' : 'var(--mc-ink)' }}>{value}</div>
      {sub && <div style={{ fontSize: 11, color: 'var(--mc-ink-dim)', marginTop: 4 }}>{sub}</div>}
    </div>
  );
}

// Build CSV content
function buildCsv(entries, staff, month) {
  const header = 'Personalnr;Name;Rolle;Datum;Start;Ende;Pause(Min);Stunden;Überstunden;Nachtstunden;Stundensatz;Brutto\n';
  const rows = entries.filter(e => e.date.startsWith(month)).map(e => {
    const u = staff.find(s => s.id === e.uid);
    if (!u) return '';
    const brutto = (e.hoursWorked * u.wage).toFixed(2).replace('.', ',');
    return [
      u.id, u.name, u.role, e.date,
      new Date(e.clockIn).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }),
      new Date(e.clockOut).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' }),
      e.breakMin, e.hoursWorked.toFixed(2).replace('.', ','),
      e.overtime.toFixed(2).replace('.', ','), e.nightHours.toFixed(2).replace('.', ','),
      u.wage.toFixed(2).replace('.', ','), brutto,
    ].join(';');
  }).filter(Boolean).join('\n');
  return header + rows;
}

Object.assign(window, { StaffScreen, PersonnelDrawer: null, HireModal: null });
