// Sidebar + secondary views (Customers, Services, Statistics)

const Sidebar = ({ active, onChange, unreadCount, onBell, onSettings }) => {
  const items = [
    { id: 'calendar',    icon: IconCalendar,  label: 'Kalender' },
    { id: 'customers',   icon: IconUsers,     label: 'Kunder' },
    { id: 'staff',       icon: IconUser,      label: 'Medarbejdere' },
    { id: 'departments', icon: IconBuilding,  label: 'Afdelinger' },
    { id: 'services',    icon: IconScissors,  label: 'Ydelser' },
    { id: 'products',    icon: IconBox,       label: 'Produkter' },
    { id: 'register',    icon: IconGrid,      label: 'Kasse' },
    { id: 'stats',       icon: IconChart,     label: 'Statistik' },
  ];
  return (
    <div style={{
      width: 64, background: 'linear-gradient(180deg, #1F2A2E 0%, #14191C 100%)',
      display: 'flex', flexDirection: 'column', alignItems: 'center',
      padding: '16px 0', flexShrink: 0,
      borderRight: '1px solid #0A0E10',
    }}>
      <div title={window.__SALONIQ_SALON__?.name || 'Saloniq'} style={{
        width: 36, height: 36, borderRadius: 10,
        background: window.__SALONIQ_SALON__?.color || '#7B8A6B',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        color: '#fff', fontSize: 18, fontWeight: 700,
        marginBottom: 24, fontFamily: 'Fraunces, serif',
      }}>{(window.__SALONIQ_SALON__?.name || 'Saloniq')[0].toUpperCase()}</div>

      {items.map(it => {
        const Ic = it.icon;
        const isActive = active === it.id;
        return (
          <button key={it.id} onClick={() => onChange(it.id)} title={it.label} style={{
            width: 44, height: 44, borderRadius: 10,
            background: isActive ? 'rgba(255,255,255,0.1)' : 'transparent',
            border: 'none', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: isActive ? '#fff' : 'rgba(255,255,255,0.55)',
            marginBottom: 6, transition: 'all 120ms',
            position: 'relative',
          }} onMouseEnter={e => { if (!isActive) e.currentTarget.style.color = '#fff'; }}
             onMouseLeave={e => { if (!isActive) e.currentTarget.style.color = 'rgba(255,255,255,0.55)'; }}>
            <Ic size={20} />
            {isActive && <div style={{ position: 'absolute', left: -8, top: 10, bottom: 10, width: 3, borderRadius: 3, background: '#C9D8B5' }} />}
          </button>
        );
      })}

      <div style={{ flex: 1 }} />

      <button onClick={onBell} title="Notifikationer" style={{
        width: 44, height: 44, borderRadius: 10, background: 'transparent',
        border: 'none', cursor: 'pointer', position: 'relative',
        color: 'rgba(255,255,255,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 6,
      }} onMouseEnter={e => e.currentTarget.style.color = '#fff'}
         onMouseLeave={e => e.currentTarget.style.color = 'rgba(255,255,255,0.55)'}>
        <IconBell size={20} />
        {unreadCount > 0 && (
          <div style={{ position: 'absolute', top: 6, right: 6, background: '#D4654E', color: '#fff', fontSize: 9, fontWeight: 700, borderRadius: 8, padding: '1px 5px', minWidth: 16, textAlign: 'center' }}>{unreadCount}</div>
        )}
      </button>
      <button onClick={onSettings} title="Indstillinger" style={{
        width: 44, height: 44, borderRadius: 10, background: 'transparent',
        border: 'none', cursor: 'pointer',
        color: 'rgba(255,255,255,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center',
        marginBottom: 6,
      }} onMouseEnter={e => e.currentTarget.style.color = '#fff'}
         onMouseLeave={e => e.currentTarget.style.color = 'rgba(255,255,255,0.55)'}>
        <IconSettings size={20} />
      </button>
      <button onClick={() => {
        if (confirm('Log ud af ' + (window.__SALONIQ_SALON__?.name || 'salonen') + '?')) {
          window.dispatchEvent(new Event('saloniq-logout'));
        }
      }} title="Log ud" style={{
        width: 44, height: 44, borderRadius: 10, background: 'transparent',
        border: 'none', cursor: 'pointer',
        color: 'rgba(255,255,255,0.55)', display: 'flex', alignItems: 'center', justifyContent: 'center',
      }} onMouseEnter={e => e.currentTarget.style.color = '#F87171'}
         onMouseLeave={e => e.currentTarget.style.color = 'rgba(255,255,255,0.55)'}>
        <IconLogOut size={20} />
      </button>
    </div>
  );
};

// ---------- Customers list with detail panel ----------
const CustomersView = ({ customers, onUpdateCustomer }) => {
  const [search, setSearch] = React.useState('');
  const [selectedId, setSelectedId] = React.useState(customers[0]?.id);
  const filtered = customers.filter(c =>
    c.name.toLowerCase().includes(search.toLowerCase()) ||
    c.phone.includes(search) ||
    c.email.toLowerCase().includes(search.toLowerCase())
  );
  const selected = customers.find(c => c.id === selectedId);

  return (
    <div style={{ display: 'flex', height: '100%', background: '#FBFAF6', overflow: 'hidden' }}>
      {/* List */}
      <div style={{ width: 420, flexShrink: 0, borderRight: '1px solid #EFEDE5', display: 'flex', flexDirection: 'column', background: '#fff' }}>
        <div style={{ padding: '20px 24px 16px', borderBottom: '1px solid #EFEDE5' }}>
          <h1 style={{ fontFamily: 'Fraunces, serif', fontSize: 22, fontWeight: 500, margin: '0 0 12px 0', color: '#1a1a1a' }}>Kunder</h1>
          <div style={{ position: 'relative' }}>
            <div style={{ position: 'absolute', left: 12, top: 11, color: '#999' }}><IconSearch size={16} /></div>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Søg navn, telefon, email…"
              style={{ ...inputStyle, paddingLeft: 36, width: '100%' }} />
          </div>
        </div>
        <div style={{ flex: 1, overflow: 'auto' }}>
          {filtered.map(c => {
            const fav = STAFF.find(s => s.id === c.favoriteStaffId);
            const isActive = c.id === selectedId;
            return (
              <button key={c.id} onClick={() => setSelectedId(c.id)} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                width: '100%', textAlign: 'left',
                padding: '12px 24px', borderBottom: '1px solid #F4F2EA',
                background: isActive ? '#F4F2EA' : 'transparent',
                border: 'none', cursor: 'pointer', fontFamily: 'inherit',
                borderLeft: isActive ? '3px solid #7B8A6B' : '3px solid transparent',
                paddingLeft: isActive ? 21 : 24,
              }} onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = '#FBFAF6'; }}
                 onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}>
                <Avatar name={c.name} tone="#E8DBC8" size={36} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: '#1a1a1a', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</div>
                  <div style={{ fontSize: 12, color: '#888', marginTop: 2 }}>{c.phone}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 11, color: '#888' }}>{c.visits} besøg</div>
                  {fav && <div style={{ fontSize: 11, color: '#7B8A6B', fontWeight: 500, marginTop: 2 }}>♥ {fav.name.split(' ')[0]}</div>}
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* Detail panel */}
      {selected ? (
        <CustomerDetail
          customer={selected}
          onUpdate={(patch) => onUpdateCustomer(selected.id, patch)}
        />
      ) : (
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#888' }}>
          Vælg en kunde
        </div>
      )}
    </div>
  );
};

const CustomerDetail = ({ customer, onUpdate }) => {
  const [notes, setNotes] = React.useState(customer.notes || '');
  const [favStaff, setFavStaff] = React.useState(customer.favoriteStaffId || '');
  const [savedFlash, setSavedFlash] = React.useState(false);
  const dirtyRef = React.useRef(false);

  // When switching customer, reload local state
  React.useEffect(() => {
    setNotes(customer.notes || '');
    setFavStaff(customer.favoriteStaffId || '');
    dirtyRef.current = false;
  }, [customer.id]);

  // Auto-save notes after debounce
  React.useEffect(() => {
    if (!dirtyRef.current) return;
    const t = setTimeout(() => {
      onUpdate({ notes, favoriteStaffId: favStaff || null });
      setSavedFlash(true);
      setTimeout(() => setSavedFlash(false), 1600);
      dirtyRef.current = false;
    }, 500);
    return () => clearTimeout(t);
  }, [notes, favStaff]);

  const fav = STAFF.find(s => s.id === favStaff);

  return (
    <div style={{ flex: 1, overflow: 'auto', padding: '32px 40px', maxWidth: 720 }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 18, marginBottom: 28 }}>
        <Avatar name={customer.name} tone="#E8DBC8" size={64} />
        <div style={{ flex: 1 }}>
          <h2 style={{ fontFamily: 'Fraunces, serif', fontSize: 28, fontWeight: 500, margin: 0, color: '#1a1a1a' }}>{customer.name}</h2>
          <div style={{ display: 'flex', gap: 16, marginTop: 6, fontSize: 13, color: '#666' }}>
            <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><IconPhone size={13} /> {customer.phone}</span>
            <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><IconMail size={13} /> {customer.email}</span>
          </div>
        </div>
        {savedFlash && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: '#3F5A30', background: '#F4F7F0', padding: '6px 12px', borderRadius: 16, border: '1px solid #DCE6CC' }}>
            <IconCheck size={12} stroke="#3F5A30" /> Gemt
          </div>
        )}
      </div>

      {/* Stats strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 28 }}>
        <MiniStat label="Besøg i alt" value={customer.visits} />
        <MiniStat label="Sidste service" value={SERVICE_BY_ID[customer.lastService]?.name || '—'} />
        <MiniStat label="Foretrukken frisør" value={fav ? fav.name.split(' ')[0] : '—'} />
      </div>

      {/* Favorite stylist */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: '#1a1a1a', marginBottom: 4 }}>Foretrukken frisør</div>
        <div style={{ fontSize: 12, color: '#888', marginBottom: 12 }}>
          Vælges automatisk når kunden bookes ind.
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
          <FavChip
            active={!favStaff}
            onClick={() => { setFavStaff(''); dirtyRef.current = true; }}
            label="Ingen præference"
          />
          {STAFF.map(s => (
            <FavChip
              key={s.id}
              active={favStaff === s.id}
              onClick={() => { setFavStaff(s.id); dirtyRef.current = true; }}
              tone={s.tone}
              label={s.name}
            />
          ))}
        </div>
      </div>

      {/* Notes */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ fontSize: 13, fontWeight: 600, color: '#1a1a1a', marginBottom: 4 }}>Noter</div>
        <div style={{ fontSize: 12, color: '#888', marginBottom: 10 }}>
          Synlig for alle medarbejdere. Brug fx til allergi, foretrukne produkter, særlige ønsker.
        </div>
        <textarea
          value={notes}
          onChange={e => { setNotes(e.target.value); dirtyRef.current = true; }}
          placeholder="Skriv noter om kunden…"
          rows={6}
          style={{
            ...inputStyle,
            width: '100%', resize: 'vertical', lineHeight: 1.5,
            fontSize: 14, background: '#fff',
            minHeight: 120,
          }}
        />
        <div style={{ fontSize: 11, color: '#999', marginTop: 6, fontStyle: 'italic' }}>
          Gemmes automatisk
        </div>
      </div>

      {/* History placeholder */}
      <div>
        <div style={{ fontSize: 13, fontWeight: 600, color: '#1a1a1a', marginBottom: 12 }}>Seneste besøg</div>
        <div style={{ background: '#fff', border: '1px solid #EFEDE5', borderRadius: 10, padding: 16, fontSize: 13, color: '#666' }}>
          {SERVICE_BY_ID[customer.lastService]?.name} hos {fav ? fav.name : 'salonen'} — for 4 uger siden
        </div>
      </div>
    </div>
  );
};

const FavChip = ({ active, onClick, tone, label }) => (
  <button onClick={onClick} style={{
    display: 'flex', alignItems: 'center', gap: 8,
    padding: '8px 12px 8px 8px',
    background: active ? '#3F4A3A' : '#fff',
    color: active ? '#fff' : '#1a1a1a',
    border: `1px solid ${active ? '#3F4A3A' : '#DDD9CE'}`,
    borderRadius: 22, cursor: 'pointer',
    fontSize: 13, fontWeight: 500, fontFamily: 'inherit',
    transition: 'all 120ms',
  }}>
    {tone && (
      <span style={{
        width: 22, height: 22, borderRadius: '50%',
        background: tone, fontSize: 10, fontWeight: 700,
        color: '#3a2e22',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>{label.split(' ').map(w => w[0]).slice(0,2).join('')}</span>
    )}
    {!tone && (
      <span style={{ width: 22, height: 22, borderRadius: '50%', background: active ? 'rgba(255,255,255,0.2)' : '#F4F2EA', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11 }}>—</span>
    )}
    <span style={{ paddingRight: 4 }}>{label}</span>
  </button>
);

const MiniStat = ({ label, value }) => (
  <div style={{ background: '#fff', border: '1px solid #EFEDE5', borderRadius: 10, padding: '14px 16px' }}>
    <div style={{ fontSize: 11, color: '#888', textTransform: 'uppercase', letterSpacing: '0.05em', fontWeight: 600 }}>{label}</div>
    <div style={{ fontSize: 18, fontWeight: 600, color: '#1a1a1a', marginTop: 4, fontFamily: 'Fraunces, serif' }}>{value}</div>
  </div>
);

// ---------- Services ----------
const ServicesView = ({ services, onEdit, onAdd }) => (
  <div style={{ padding: '24px 32px', height: '100%', overflow: 'auto', background: '#FBFAF6' }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
      <div>
        <h1 style={{ fontFamily: 'Fraunces, serif', fontSize: 28, fontWeight: 500, margin: 0 }}>Ydelser</h1>
        <div style={{ fontSize: 13, color: '#888', marginTop: 4 }}>Behandlinger I tilbyder · varighed, pris, mellemrum efter</div>
      </div>
      <button onClick={onAdd} style={{
        background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 8,
        padding: '10px 18px', fontSize: 14, fontWeight: 600, cursor: 'pointer',
        fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <span style={{ fontSize: 18, lineHeight: 1 }}>+</span> Ny ydelse
      </button>
    </div>

    {services.length === 0 ? (
      <div style={{
        background: '#fff', border: '1px dashed #DDD9CE', borderRadius: 14,
        padding: '60px 32px', textAlign: 'center', maxWidth: 520, margin: '40px auto',
      }}>
        <div style={{
          width: 56, height: 56, margin: '0 auto 16px',
          background: '#F4F2EA', borderRadius: 14,
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#7B8A6B',
        }}>
          <IconScissors size={26} strokeWidth={1.6} />
        </div>
        <h2 style={{ fontFamily: 'Fraunces, serif', fontSize: 20, fontWeight: 500, margin: '0 0 8px' }}>
          Ingen ydelser endnu
        </h2>
        <p style={{ fontSize: 14, color: '#666', margin: '0 0 20px', lineHeight: 1.55 }}>
          Tilføj de behandlinger I tilbyder — fx herreklip, dameklip, helfarve eller manicure.
          Hver ydelse har sin egen varighed, pris og mellemrum til pause/farveventning.
        </p>
        <button onClick={onAdd} style={{
          background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 8,
          padding: '10px 22px', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
        }}>+ Tilføj første ydelse</button>
      </div>
    ) : (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 16 }}>
      {services.map(s => {
        const c = getServicePalette(s.color);
        return (
          <div key={s.id} onClick={() => onEdit(s)} style={{
            background: '#fff', borderRadius: 12, border: '1px solid #EFEDE5',
            overflow: 'hidden', cursor: 'pointer', transition: 'transform 120ms, box-shadow 120ms',
          }}
          onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 6px 16px rgba(0,0,0,0.08)'; }}
          onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'none'; }}
          >
            <div style={{ background: c.bg, padding: 16, borderBottom: `3px solid ${c.border}` }}>
              <div style={{ fontSize: 11, color: c.text, opacity: 0.7, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase' }}>Service</div>
              <div style={{ fontSize: 20, fontWeight: 600, color: c.text, marginTop: 4 }}>{s.name}</div>
            </div>
            <div style={{ padding: 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: s.pauseAfter ? 10 : 0 }}>
                <div>
                  <div style={{ fontSize: 12, color: '#888' }}>Varighed</div>
                  <div style={{ fontSize: 16, fontWeight: 500 }}>{s.duration} min</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 12, color: '#888' }}>Pris</div>
                  <div style={{ fontSize: 16, fontWeight: 500 }}>{s.price} kr</div>
                </div>
              </div>
              {s.pauseAfter > 0 && (
                <div style={{ marginTop: 10, padding: '8px 10px', background: '#FBFAF6', border: '1px dashed #DDD9CE', borderRadius: 6, fontSize: 12, color: '#666' }}>
                  + <strong>{s.pauseAfter} min mellemrum</strong> efter
                </div>
              )}
            </div>
          </div>
        );
      })}
    </div>
    )}
  </div>
);

// ---------- Products (physical items sold over the counter) ----------
const ProductsView = ({ products, onEdit, onAdd }) => (
  <div style={{ padding: '24px 32px', height: '100%', overflow: 'auto', background: '#FBFAF6' }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
      <div>
        <h1 style={{ fontFamily: 'Fraunces, serif', fontSize: 28, fontWeight: 500, margin: 0 }}>Produkter</h1>
        <div style={{ fontSize: 13, color: '#888', marginTop: 4 }}>
          Shampoo, balsam, stylingprodukter — alt I sælger over disken
        </div>
      </div>
      <button onClick={onAdd} style={{
        background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 8,
        padding: '10px 18px', fontSize: 14, fontWeight: 600, cursor: 'pointer',
        fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <span style={{ fontSize: 18, lineHeight: 1 }}>+</span> Nyt produkt
      </button>
    </div>

    {products.length === 0 ? (
      <div style={{
        background: '#fff', border: '1px dashed #DDD9CE', borderRadius: 14,
        padding: '60px 32px', textAlign: 'center', maxWidth: 520, margin: '40px auto',
      }}>
        <div style={{
          width: 56, height: 56, margin: '0 auto 16px',
          background: '#F4F2EA', borderRadius: 14,
          display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#7B8A6B',
        }}>
          <IconBox size={26} strokeWidth={1.6} />
        </div>
        <h2 style={{ fontFamily: 'Fraunces, serif', fontSize: 20, fontWeight: 500, margin: '0 0 8px' }}>
          Ingen produkter endnu
        </h2>
        <p style={{ fontSize: 14, color: '#666', margin: '0 0 20px', lineHeight: 1.55 }}>
          Tilføj de produkter I sælger til kunderne — fx shampoo, balsam, hårvoks osv.
          Hver vare har sin egen lagerbeholdning så I kan se hvornår der skal genbestilles.
        </p>
        <button onClick={onAdd} style={{
          background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 8,
          padding: '10px 22px', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
        }}>+ Tilføj første produkt</button>
      </div>
    ) : (
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 16 }}>
        {products.map(p => {
          const lowStock = typeof p.stock === 'number' && p.stock <= 3;
          const outOfStock = typeof p.stock === 'number' && p.stock <= 0;
          return (
            <div key={p.id} onClick={() => onEdit(p)} style={{
              background: '#fff', borderRadius: 12, border: '1px solid #EFEDE5',
              overflow: 'hidden', cursor: 'pointer', transition: 'transform 120ms, box-shadow 120ms',
            }}
            onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 6px 16px rgba(0,0,0,0.08)'; }}
            onMouseLeave={e => { e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'none'; }}>
              <div style={{ background: '#F4F2EA', padding: 16, borderBottom: '3px solid #DDD9CE' }}>
                <div style={{ fontSize: 11, color: '#888', fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                  {p.brand || 'Produkt'}
                </div>
                <div style={{ fontSize: 18, fontWeight: 600, color: '#1a1a1a', marginTop: 4 }}>{p.name}</div>
              </div>
              <div style={{ padding: 16 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <div>
                    <div style={{ fontSize: 12, color: '#888' }}>Pris</div>
                    <div style={{ fontSize: 16, fontWeight: 500 }}>{p.price} kr</div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontSize: 12, color: '#888' }}>På lager</div>
                    <div style={{
                      fontSize: 16, fontWeight: 500,
                      color: outOfStock ? '#A03838' : (lowStock ? '#B45309' : '#1a1a1a'),
                    }}>
                      {typeof p.stock === 'number' ? p.stock + ' stk' : '—'}
                    </div>
                  </div>
                </div>
                {outOfStock && (
                  <div style={{ marginTop: 10, padding: '6px 10px', background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 6, fontSize: 11, color: '#A03838' }}>
                    Udsolgt — bestil hjem
                  </div>
                )}
                {lowStock && !outOfStock && (
                  <div style={{ marginTop: 10, padding: '6px 10px', background: '#FEF6DC', border: '1px solid #F0DC9C', borderRadius: 6, fontSize: 11, color: '#8A6B1F' }}>
                    Lavt lager
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    )}
  </div>
);

// ---------- Stats ----------
const StatsView = ({ bookings, customers }) => {
  const totalRevenue = bookings.reduce((sum, b) => sum + getBookingPrice(b), 0);
  const byService = SERVICES.map(s => ({
    ...s,
    count: bookings.filter(b => (b.serviceIds || [b.serviceId]).includes(s.id)).length,
  }));
  const maxCount = Math.max(1, ...byService.map(b => b.count));

  return (
    <div style={{ padding: '24px 32px', height: '100%', overflow: 'auto', background: '#FBFAF6' }}>
      <h1 style={{ fontFamily: 'Fraunces, serif', fontSize: 28, fontWeight: 500, margin: '0 0 20px 0' }}>Statistik · denne uge</h1>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        <StatCard label="Bookinger" value={bookings.length} />
        <StatCard label="Omsætning" value={`${totalRevenue.toLocaleString('da-DK')} kr`} />
        <StatCard label="Aktive kunder" value={customers.length} />
        <StatCard label="Fyldningsgrad" value="78%" />
      </div>

      <div style={{ background: '#fff', borderRadius: 12, border: '1px solid #EFEDE5', padding: 24 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 18 }}>Ydelser fordelt</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {byService.map(s => {
            const c = getServicePalette(s.color);
            return (
              <div key={s.id} style={{ display: 'grid', gridTemplateColumns: '160px 1fr 60px', gap: 12, alignItems: 'center' }}>
                <div style={{ fontSize: 13, fontWeight: 500 }}>{s.name}</div>
                <div style={{ background: '#F4F2EA', borderRadius: 4, height: 20, position: 'relative', overflow: 'hidden' }}>
                  <div style={{ background: c.border, height: '100%', width: `${(s.count / maxCount) * 100}%`, transition: 'width 400ms' }} />
                </div>
                <div style={{ fontSize: 13, fontWeight: 600, textAlign: 'right' }}>{s.count}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

const StatCard = ({ label, value }) => (
  <div style={{ background: '#fff', borderRadius: 12, border: '1px solid #EFEDE5', padding: 20 }}>
    <div style={{ fontSize: 12, color: '#888', fontWeight: 500, marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.04em' }}>{label}</div>
    <div style={{ fontSize: 26, fontWeight: 600, color: '#1a1a1a', fontFamily: 'Fraunces, serif' }}>{value}</div>
  </div>
);

const PlaceholderView = ({ title }) => (
  <div style={{ padding: 32, height: '100%', background: '#FBFAF6', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
    <div style={{ textAlign: 'center', color: '#888' }}>
      <div style={{ fontFamily: 'Fraunces, serif', fontSize: 28, color: '#1a1a1a', marginBottom: 8 }}>{title}</div>
      <div>Denne sektion er ikke en del af denne prototype.</div>
    </div>
  </div>
);

// ---------- Staff ----------
const StaffAvatar = ({ s, size }) => {
  if (s.photo) {
    return (
      <div style={{
        width: size, height: size, borderRadius: '50%',
        background: `url(${s.photo}) center/cover`, border: '1px solid #E5E2D5',
        flexShrink: 0,
      }} />
    );
  }
  return <Avatar name={s.name} tone={s.tone} size={size} />;
};

const StaffView = ({ bookings, customers, staff, onSelectStaff, onEditStaff, onAddStaff }) => {
  const list = staff || STAFF;
  const [selectedId, setSelectedId] = React.useState(list[0]?.id);
  const selected = list.find(s => s.id === selectedId) || list[0];

  // Hooks must be called unconditionally on every render — keep this useEffect
  // ABOVE any early returns. (Was below the empty-state return → caused
  // 'Rendered more hooks than during the previous render' when the list
  // transitioned from empty to non-empty after creating the first staff.)
  React.useEffect(() => {
    if (list.length && !list.find(s => s.id === selectedId)) {
      setSelectedId(list[0]?.id);
    }
  }, [list, selectedId]);

  // Empty-state: when no staff exist yet, show a guide card with the action.
  if (!selected) {
    return (
      <div style={{ padding: '24px 32px', height: '100%', overflow: 'auto', background: '#FBFAF6' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
          <div>
            <h1 style={{ fontFamily: 'Fraunces, serif', fontSize: 28, fontWeight: 500, margin: 0 }}>Medarbejdere</h1>
            <div style={{ fontSize: 13, color: '#888', marginTop: 4 }}>
              {window.__SALONIQ_SALON__?.name || 'Salon'}
            </div>
          </div>
          <button onClick={onAddStaff} style={{
            background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 8,
            padding: '10px 18px', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <span style={{ fontSize: 18, lineHeight: 1 }}>+</span> Ny medarbejder
          </button>
        </div>

        <div style={{
          background: '#fff', border: '1px dashed #DDD9CE', borderRadius: 14,
          padding: '60px 32px', textAlign: 'center', maxWidth: 520, margin: '40px auto',
        }}>
          <div style={{
            width: 56, height: 56, margin: '0 auto 16px',
            background: '#F4F2EA', borderRadius: 14,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#7B8A6B',
          }}>
            <IconUser size={26} strokeWidth={1.6} />
          </div>
          <h2 style={{ fontFamily: 'Fraunces, serif', fontSize: 20, fontWeight: 500, margin: '0 0 8px' }}>
            Ingen medarbejdere endnu
          </h2>
          <p style={{ fontSize: 14, color: '#666', margin: '0 0 20px', lineHeight: 1.55 }}>
            Tilføj jeres frisører, neglepiger eller andre medarbejdere. Hver medarbejder har sin egen
            kalender, vagtplan, specialer og kan tildeles til en afdeling.
          </p>
          <button onClick={onAddStaff} style={{
            background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 8,
            padding: '10px 22px', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
          }}>+ Tilføj første medarbejder</button>
        </div>
      </div>
    );
  }

  const staffStats = (id) => {
    const sb = bookings.filter(b => b.staffId === id);
    const revenue = sb.reduce((sum, b) => sum + getBookingPrice(b), 0);
    const minutes = sb.reduce((sum, b) => sum + getBookingDuration(b), 0);
    const fans = customers.filter(c => c.favoriteStaffId === id).length;
    return { count: sb.length, revenue, minutes, fans };
  };

  const sStats = staffStats(selected.id);
  const todayBookings = bookings.filter(b => b.staffId === selected.id).sort((a,b) => a.start - b.start);
  const fans = customers.filter(c => c.favoriteStaffId === selected.id);
  const utilization = Math.min(100, Math.round((sStats.minutes / (8*60)) * 100));

  return (
    <div style={{ display: 'flex', height: '100%', background: '#FBFAF6', overflow: 'hidden' }}>
      <div style={{ width: 320, flexShrink: 0, borderRight: '1px solid #EFEDE5', display: 'flex', flexDirection: 'column', background: '#fff' }}>
        <div style={{ padding: '20px 24px 16px', borderBottom: '1px solid #EFEDE5', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <h1 style={{ fontFamily: 'Fraunces, serif', fontSize: 22, fontWeight: 500, margin: 0, color: '#1a1a1a' }}>Medarbejdere</h1>
            <div style={{ fontSize: 12, color: '#888', marginTop: 4 }}>
              {list.length} aktive · {window.__SALONIQ_SALON__?.name || 'Salon'}
            </div>
          </div>
          <button onClick={onAddStaff} title="Ny medarbejder" style={{
            background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 8,
            padding: '8px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <IconPlus size={12} /> Ny
          </button>
        </div>
        <div style={{ flex: 1, overflow: 'auto' }}>
          {list.map(s => {
            const st = staffStats(s.id);
            const isActive = s.id === selectedId;
            return (
              <button key={s.id} onClick={() => setSelectedId(s.id)} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                width: '100%', textAlign: 'left',
                padding: '14px 24px', borderBottom: '1px solid #F4F2EA',
                background: isActive ? '#F4F2EA' : 'transparent',
                border: 'none', cursor: 'pointer', fontFamily: 'inherit',
                borderLeft: isActive ? '3px solid #7B8A6B' : '3px solid transparent',
                paddingLeft: isActive ? 21 : 24,
              }} onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = '#FBFAF6'; }}
                 onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}>
                <StaffAvatar s={s} size={40} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: '#1a1a1a' }}>{s.name}</div>
                  <div style={{ fontSize: 12, color: '#888', marginTop: 2 }}>{s.role}</div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#1a1a1a' }}>{st.count}</div>
                  <div style={{ fontSize: 11, color: '#888' }}>i dag</div>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '32px 40px', maxWidth: 880 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 20, marginBottom: 28 }}>
          <StaffAvatar s={selected} size={72} />
          <div style={{ flex: 1 }}>
            <h2 style={{ fontFamily: 'Fraunces, serif', fontSize: 30, fontWeight: 500, margin: 0, color: '#1a1a1a' }}>{selected.name}</h2>
            <div style={{ display: 'flex', gap: 16, marginTop: 6, fontSize: 13, color: '#666', flexWrap: 'wrap' }}>
              <span>{selected.role}</span>
              {selected.phone && <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><IconPhone size={13} /> {selected.phone}</span>}
              {selected.email && <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}><IconMail size={13} /> {selected.email}</span>}
            </div>
          </div>
          <button onClick={() => onEditStaff(selected)} style={{
            background: '#fff', color: '#3F4A3A', border: '1.5px solid #DDD9CE', borderRadius: 8,
            padding: '10px 14px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <IconEdit size={14} /> Rediger
          </button>
          <button onClick={() => onSelectStaff(selected.id)} style={{
            background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 8,
            padding: '10px 16px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <IconCalendar size={14} /> Vis kalender
          </button>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginBottom: 28 }}>
          <MiniStat label="Bookinger i dag" value={sStats.count} />
          <MiniStat label="Omsætning i dag" value={`${sStats.revenue.toLocaleString('da-DK')} kr`} />
          <MiniStat label="Belastning" value={`${utilization}%`} />
          <MiniStat label="Stamkunder" value={sStats.fans} />
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20, marginBottom: 24 }}>
          <div style={{ background: '#fff', border: '1px solid #EFEDE5', borderRadius: 12, padding: 20 }}>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>Specialer</div>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {selected.specialties.map(sp => (
                <span key={sp} style={{ background: '#F4F2EA', borderRadius: 14, padding: '5px 12px', fontSize: 12, color: '#3F4A3A', fontWeight: 500 }}>{sp}</span>
              ))}
            </div>
          </div>
          <div style={{ background: '#fff', border: '1px solid #EFEDE5', borderRadius: 12, padding: 20 }}>
            <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>Ugentlig vagtplan</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 6 }}>
              {[['man','Man'],['tir','Tir'],['ons','Ons'],['tor','Tor'],['fre','Fre'],['lor','Lør']].map(([k,l]) => {
                const v = selected.schedule[k];
                const off = v === 'Fri';
                return (
                  <div key={k} style={{ background: off ? '#F4F2EA' : '#F4F7F0', border: `1px solid ${off ? '#E5E2D5' : '#DCE6CC'}`, borderRadius: 8, padding: '8px 6px', textAlign: 'center' }}>
                    <div style={{ fontSize: 10, color: '#888', fontWeight: 600, textTransform: 'uppercase' }}>{l}</div>
                    <div style={{ fontSize: 12, fontWeight: 600, color: off ? '#999' : '#3F5A30', marginTop: 3 }}>{v}</div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <div style={{ background: '#fff', border: '1px solid #EFEDE5', borderRadius: 12, padding: 20, marginBottom: 24 }}>
          <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>Aftaler i dag</div>
          {todayBookings.length === 0 ? (
            <div style={{ fontSize: 13, color: '#888', padding: '12px 0' }}>Ingen aftaler i dag.</div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {todayBookings.map(b => {
                const primary = getBookingPrimary(b);
                const dur = getBookingDuration(b);
                const c = getServicePalette(primary?.color);
                const cust = customers.find(x => x.id === b.customerId);
                return (
                  <div key={b.id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '10px 0', borderBottom: '1px solid #F4F2EA' }}>
                    <div style={{ width: 90, fontSize: 12, color: '#666', fontWeight: 500 }}>
                      {fmtTime(b.start)}–{fmtTime(b.start + dur)}
                    </div>
                    <div style={{ width: 8, height: 32, borderRadius: 4, background: c.border }} />
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 500 }}>{cust?.name || 'Ukendt'}</div>
                      <div style={{ fontSize: 12, color: '#888' }}>{getBookingTitle(b)} · {dur} min</div>
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: '#1a1a1a' }}>{getBookingPrice(b)} kr</div>
                  </div>
                );
              })}
            </div>
          )}
        </div>

        <div style={{ background: '#fff', border: '1px solid #EFEDE5', borderRadius: 12, padding: 20 }}>
          <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 12 }}>Stamkunder ({fans.length})</div>
          {fans.length === 0 ? (
            <div style={{ fontSize: 13, color: '#888' }}>Ingen kunder har valgt {selected.name.split(' ')[0]} som foretrukken frisør endnu.</div>
          ) : (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
              {fans.map(c => (
                <div key={c.id} style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#F4F2EA', borderRadius: 18, padding: '6px 12px 6px 6px' }}>
                  <Avatar name={c.name} tone="#E8DBC8" size={24} />
                  <span style={{ fontSize: 12, fontWeight: 500 }}>{c.name}</span>
                  <span style={{ fontSize: 11, color: '#888' }}>· {c.visits} besøg</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// ─── Departments View ─────────────────────────────────────────────────────────
const DepartmentsView = ({ departments, staff, onUpdateDepartments, onUpdateStaffDept }) => {
  const [selectedId, setSelectedId] = React.useState(departments[0]?.id || null);
  const [editingId, setEditingId] = React.useState(null);
  const [editingName, setEditingName] = React.useState('');
  const [creating, setCreating] = React.useState(false);
  const [newName, setNewName] = React.useState('');

  const selected = departments.find(d => d.id === selectedId);
  const countInDept = id => staff.filter(s => s.departmentId === id).length;

  const handleCreate = () => {
    if (!newName.trim()) return;
    const id = 'dept_' + Date.now();
    onUpdateDepartments([...departments, { id, name: newName.trim() }]);
    setNewName(''); setCreating(false); setSelectedId(id);
  };

  const handleDelete = deptId => {
    const updated = departments.filter(d => d.id !== deptId);
    onUpdateDepartments(updated);
    staff.filter(s => s.departmentId === deptId).forEach(s => onUpdateStaffDept(s.id, null));
    setSelectedId(updated[0]?.id || null);
  };

  const handleRename = deptId => {
    if (!editingName.trim()) return;
    onUpdateDepartments(departments.map(d => d.id === deptId ? { ...d, name: editingName.trim() } : d));
    setEditingId(null);
  };

  const handleToggleStaff = staffId => {
    const s = staff.find(x => x.id === staffId);
    onUpdateStaffDept(staffId, s.departmentId === selectedId ? null : selectedId);
  };

  return (
    <div style={{ display: 'flex', height: '100%', background: '#FBFAF6', overflow: 'hidden' }}>
      {/* Left: department list */}
      <div style={{ width: 300, flexShrink: 0, borderRight: '1px solid #EFEDE5', display: 'flex', flexDirection: 'column', background: '#fff' }}>
        <div style={{ padding: '20px 20px 14px', borderBottom: '1px solid #EFEDE5', display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
          <div>
            <h1 style={{ fontFamily: 'Fraunces, serif', fontSize: 22, fontWeight: 500, margin: 0 }}>Afdelinger</h1>
            <div style={{ fontSize: 12, color: '#888', marginTop: 4 }}>{departments.length} afdeling(er)</div>
          </div>
          <button onClick={() => { setCreating(true); setSelectedId(null); }} title="Ny afdeling" style={{
            background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 8,
            padding: '8px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <IconPlus size={12} /> Ny
          </button>
        </div>

        {creating && (
          <div style={{ padding: '12px 16px', borderBottom: '1px solid #EFEDE5', background: '#F4F7F0' }}>
            <input
              autoFocus
              value={newName}
              onChange={e => setNewName(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter') handleCreate(); if (e.key === 'Escape') { setCreating(false); setNewName(''); } }}
              placeholder="Navn på afdeling…"
              style={{ ...inputStyle, width: '100%', marginBottom: 8, boxSizing: 'border-box' }}
            />
            <div style={{ display: 'flex', gap: 6 }}>
              <button onClick={() => { setCreating(false); setNewName(''); }} style={{
                flex: 1, padding: '7px', background: '#fff', border: '1px solid #DDD9CE',
                borderRadius: 7, cursor: 'pointer', fontSize: 12, fontFamily: 'inherit',
              }}>Annuller</button>
              <button onClick={handleCreate} style={{
                flex: 1, padding: '7px', background: '#3F4A3A', color: '#fff', border: 'none',
                borderRadius: 7, cursor: 'pointer', fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
              }}>Opret</button>
            </div>
          </div>
        )}

        <div style={{ flex: 1, overflow: 'auto' }}>
          {departments.length === 0 && !creating && (
            <div style={{ padding: '40px 20px', textAlign: 'center', color: '#aaa', fontSize: 13 }}>
              Ingen afdelinger endnu.<br/>Opret din første afdeling.
            </div>
          )}
          {departments.map(d => {
            const count = countInDept(d.id);
            const isActive = d.id === selectedId;
            return (
              <button key={d.id} onClick={() => setSelectedId(d.id)} style={{
                display: 'flex', alignItems: 'center', width: '100%', textAlign: 'left',
                padding: '14px 20px', borderBottom: '1px solid #F4F2EA',
                background: isActive ? '#F4F2EA' : 'transparent',
                border: 'none', cursor: 'pointer', fontFamily: 'inherit',
                borderLeft: isActive ? '3px solid #7B8A6B' : '3px solid transparent',
                paddingLeft: isActive ? 17 : 20,
              }}
              onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = '#FBFAF6'; }}
              onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = 'transparent'; }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 14, fontWeight: 500, color: '#1a1a1a' }}>{d.name}</div>
                  <div style={{ fontSize: 12, color: '#888', marginTop: 2 }}>
                    {count} medarbejder{count !== 1 ? 'e' : ''}
                  </div>
                </div>
                <div style={{
                  width: 24, height: 24, borderRadius: '50%', background: '#F4F2EA',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 12, fontWeight: 600, color: '#7B8A6B',
                }}>{count}</div>
              </button>
            );
          })}
        </div>
      </div>

      {/* Right: department detail */}
      {selected ? (
        <div style={{ flex: 1, overflow: 'auto', padding: '32px 40px', maxWidth: 900 }}>
          {/* Header */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 28 }}>
            {editingId === selected.id ? (
              <>
                <input
                  autoFocus value={editingName}
                  onChange={e => setEditingName(e.target.value)}
                  onKeyDown={e => { if (e.key === 'Enter') handleRename(selected.id); if (e.key === 'Escape') setEditingId(null); }}
                  style={{
                    ...inputStyle,
                    fontSize: 22, fontFamily: 'Fraunces, serif', fontWeight: 500,
                    padding: '8px 12px', flex: 1, maxWidth: 320,
                  }}
                />
                <button onClick={() => handleRename(selected.id)} style={{
                  background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 8,
                  padding: '9px 16px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
                }}>Gem</button>
                <button onClick={() => setEditingId(null)} style={{
                  background: '#fff', color: '#888', border: '1px solid #DDD9CE', borderRadius: 8,
                  padding: '9px 16px', fontSize: 13, cursor: 'pointer', fontFamily: 'inherit',
                }}>Annuller</button>
              </>
            ) : (
              <>
                <h2 style={{ fontFamily: 'Fraunces, serif', fontSize: 28, fontWeight: 500, margin: 0, flex: 1 }}>
                  {selected.name}
                </h2>
                <button onClick={() => { setEditingId(selected.id); setEditingName(selected.name); }} style={{
                  background: '#fff', color: '#3F4A3A', border: '1.5px solid #DDD9CE', borderRadius: 8,
                  padding: '9px 14px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
                  display: 'flex', alignItems: 'center', gap: 6,
                }}>
                  <IconEdit size={13} /> Omdøb
                </button>
                <button onClick={() => handleDelete(selected.id)} style={{
                  background: '#FEF2F2', color: '#A03838', border: '1.5px solid #FECACA', borderRadius: 8,
                  padding: '9px 14px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
                }}>Slet afdeling</button>
              </>
            )}
          </div>

          <div style={{ fontSize: 13, fontWeight: 600, color: '#1a1a1a', marginBottom: 6 }}>Medarbejdere</div>
          <div style={{ fontSize: 12, color: '#888', marginBottom: 20 }}>
            Klik på en medarbejder for at tilføje eller fjerne dem fra afdelingen.
            En medarbejder kan kun tilhøre én afdeling ad gangen.
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(260px, 1fr))', gap: 12 }}>
            {staff.map(s => {
              const inThisDept = s.departmentId === selected.id;
              const otherDept = !inThisDept && s.departmentId
                ? departments.find(d => d.id === s.departmentId)
                : null;
              return (
                <button key={s.id} onClick={() => handleToggleStaff(s.id)} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '14px 16px',
                  background: inThisDept ? '#F4F7F0' : '#fff',
                  border: `1.5px solid ${inThisDept ? '#C2D6B4' : '#EFEDE5'}`,
                  borderRadius: 12, cursor: 'pointer', textAlign: 'left',
                  fontFamily: 'inherit', transition: 'all 120ms',
                }}
                onMouseEnter={e => { if (!inThisDept) { e.currentTarget.style.borderColor = '#DDD9CE'; e.currentTarget.style.background = '#FBFAF6'; } }}
                onMouseLeave={e => { if (!inThisDept) { e.currentTarget.style.borderColor = '#EFEDE5'; e.currentTarget.style.background = '#fff'; } }}>
                  <StaffAvatar s={s} size={42} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 14, fontWeight: 500, color: '#1a1a1a' }}>{s.name}</div>
                    <div style={{ fontSize: 12, color: '#888', marginTop: 2 }}>{s.role}</div>
                    {otherDept && (
                      <div style={{
                        fontSize: 11, color: '#B45309', marginTop: 3,
                        background: '#FEF3C7', padding: '1px 6px', borderRadius: 4, display: 'inline-block',
                      }}>
                        Tilhører {otherDept.name}
                      </div>
                    )}
                  </div>
                  <div style={{
                    width: 22, height: 22, borderRadius: '50%', flexShrink: 0,
                    background: inThisDept ? '#3F4A3A' : '#F4F2EA',
                    border: `2px solid ${inThisDept ? '#3F4A3A' : '#DDD9CE'}`,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    transition: 'all 120ms',
                  }}>
                    {inThisDept && <IconCheck size={12} stroke="#fff" />}
                  </div>
                </button>
              );
            })}
          </div>
        </div>
      ) : (
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#aaa', fontSize: 14 }}>
          {departments.length > 0 ? 'Vælg en afdeling til venstre' : 'Opret din første afdeling med knappen ovenfor'}
        </div>
      )}
    </div>
  );
};

Object.assign(window, { Sidebar, StaffAvatar, CustomersView, ServicesView, ProductsView, StatsView, PlaceholderView, StaffView, DepartmentsView });
