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

const Sidebar = ({ active, onChange, unreadCount, onBell, onSettings }) => {
  // Vælg ydelse-ikon baseret på salonens branche. INDUSTRY_OPTIONS i icons.jsx
  // mapper id → ikon-navn; vi slår selve ikon-komponenten op på window.
  const industry = window.__SALONIQ_SALON__?.industry || 'frisor';
  const industryDef = (window.INDUSTRY_OPTIONS || []).find(i => i.id === industry);
  const servicesIcon = (industryDef && window[industryDef.icon]) || IconScissors;
  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: servicesIcon,  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',
    }}>
      {(() => {
        const salon = window.__SALONIQ_SALON__ || {};
        // Show the salon's uploaded logo where the SRH-style letter pip would
        // otherwise sit. Falls back to the first letter on a brand-coloured
        // square if no logo is uploaded.
        if (salon.logo) {
          return (
            <div title={salon.name || 'Saloniq'} style={{
              width: 40, height: 40, borderRadius: 10,
              background: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              overflow: 'hidden', marginBottom: 24,
              padding: 3, boxSizing: 'border-box',
            }}>
              <img src={salon.logo} alt={salon.name || 'Salon'} style={{
                maxWidth: '100%', maxHeight: '100%', objectFit: 'contain',
              }} />
            </div>
          );
        }
        return (
          <div title={salon.name || 'Saloniq'} style={{
            width: 36, height: 36, borderRadius: 10,
            background: salon.color || '#7B8A6B',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontSize: 18, fontWeight: 700,
            marginBottom: 24, fontFamily: 'Fraunces, serif',
          }}>{(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, sales = [], onShowReceipt }) => {
  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)}
          sales={sales}
          onShowReceipt={onShowReceipt}
        />
      ) : (
        <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#888' }}>
          Vælg en kunde
        </div>
      )}
    </div>
  );
};

// Editor for a single farve-opskrift. Minimalt: blot et felt til formlen.
const RecipeEditor = ({ recipe, onSave, onCancel }) => {
  const [formula, setFormula] = React.useState(recipe?.formula || '');

  const canSave = formula.trim().length > 0;
  const handleSave = () => {
    if (!canSave) return;
    onSave({ formula: formula.trim() });
  };

  return (
    <div style={{
      background: '#fff', border: '1.5px solid #C9D8B5', borderRadius: 10,
      padding: 16, marginBottom: 8,
    }}>
      <div style={{ fontSize: 11, color: '#3F5A30', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 10 }}>
        {recipe ? 'Rediger opskrift' : 'Ny opskrift'}
      </div>
      <textarea value={formula} onChange={e => setFormula(e.target.value)} rows={4} autoFocus
        placeholder="Skriv opskriften her — fx 30g 8.1 + 30g 9.0, 6%, 35 min, ansatser + længder"
        style={{ ...recipeInputStyle, fontFamily: 'inherit', resize: 'vertical', minHeight: 100, marginBottom: 14 }} />

      <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
        <button onClick={onCancel} style={{
          background: '#fff', color: '#666', border: '1.5px solid #DDD9CE',
          padding: '7px 14px', borderRadius: 7, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit',
        }}>Annullér</button>
        <button onClick={handleSave} disabled={!canSave} style={{
          background: canSave ? '#3F4A3A' : '#D4D0C8', color: '#fff', border: 'none',
          padding: '7px 16px', borderRadius: 7, fontSize: 13, fontWeight: 600,
          cursor: canSave ? 'pointer' : 'not-allowed', fontFamily: 'inherit',
        }}>{recipe ? 'Gem ændringer' : 'Gem opskrift'}</button>
      </div>
    </div>
  );
};

const recipeInputStyle = {
  width: '100%', padding: '7px 10px',
  border: '1px solid #DDD9CE', borderRadius: 6, fontSize: 13,
  outline: 'none', background: '#FBFAF6', fontFamily: 'inherit',
  boxSizing: 'border-box',
};
const recipeLabelStyle = {
  display: 'block', fontSize: 11, fontWeight: 600, color: '#666', marginBottom: 4,
};

const RecipeCard = ({ recipe, isEditing, onEdit, onSave, onCancel, onDelete }) => {
  if (isEditing) {
    return <RecipeEditor recipe={recipe} onSave={onSave} onCancel={onCancel} />;
  }
  const dateLabel = (() => {
    try {
      const dt = new Date(recipe.updatedAt || recipe.createdAt);
      return formatDanishShortDate(dt);
    } catch { return ''; }
  })();
  return (
    <div style={{
      background: '#fff', border: '1px solid #EFEDE5', borderRadius: 10,
      padding: '14px 16px',
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 10, marginBottom: 8 }}>
        <div style={{ fontSize: 11, color: '#888', fontWeight: 600 }}>
          {dateLabel ? (recipe.updatedAt ? 'Opdateret ' : 'Oprettet ') + dateLabel : 'Opskrift'}
        </div>
        <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
          <button onClick={onEdit} title="Rediger" style={{
            background: 'transparent', border: 'none', color: '#666',
            cursor: 'pointer', padding: 4, lineHeight: 0,
          }}><IconEdit size={14} /></button>
          <button onClick={onDelete} title="Slet" style={{
            background: 'transparent', border: 'none', color: '#A03838',
            cursor: 'pointer', padding: 4, lineHeight: 0,
          }}><IconTrash size={14} /></button>
        </div>
      </div>
      <div style={{
        background: '#FBFAF6', borderRadius: 6, padding: '10px 12px',
        fontSize: 13, color: '#333', lineHeight: 1.55, whiteSpace: 'pre-wrap',
        fontFamily: 'ui-monospace, SF Mono, monospace',
      }}>{recipe.formula}</div>
    </div>
  );
};

const CustomerDetail = ({ customer, onUpdate, sales = [], onShowReceipt }) => {
  const [notes, setNotes] = React.useState(customer.notes || '');
  const [favStaff, setFavStaff] = React.useState(customer.favoriteStaffId || '');
  const [recipes, setRecipes] = React.useState(customer.recipes || []);
  const [showNewRecipe, setShowNewRecipe] = React.useState(false);
  const [showAllRecipes, setShowAllRecipes] = React.useState(false);
  const [editingRecipeId, setEditingRecipeId] = React.useState(null);
  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 || '');
    setRecipes(customer.recipes || []);
    setShowNewRecipe(false);
    setShowAllRecipes(false);
    setEditingRecipeId(null);
    dirtyRef.current = false;
  }, [customer.id]);

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

  const addRecipe = (recipe) => {
    setRecipes(prev => [...prev, { ...recipe, id: 'rcp_' + Date.now(), createdAt: new Date().toISOString() }]);
    dirtyRef.current = true;
    setShowNewRecipe(false);
  };
  const updateRecipe = (id, patch) => {
    setRecipes(prev => prev.map(r => r.id === id ? { ...r, ...patch, updatedAt: new Date().toISOString() } : r));
    dirtyRef.current = true;
  };
  const deleteRecipe = (id) => {
    if (!confirm('Slet denne opskrift?')) return;
    setRecipes(prev => prev.filter(r => r.id !== id));
    dirtyRef.current = true;
    setEditingRecipeId(null);
  };

  // Kundens kvitteringer — alle salg knyttet til denne customer.id
  const customerReceipts = React.useMemo(() => {
    return sales
      .filter(s => s.customerId === customer.id)
      .sort((a, b) => (b.paidAt || '').localeCompare(a.paidAt || ''));
  }, [sales, customer.id]);

  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>

      {/* Farve-opskrifter */}
      <div style={{ marginBottom: 28 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: '#1a1a1a' }}>
            Farve-opskrifter ({recipes.length})
          </div>
          <button onClick={() => setShowNewRecipe(true)} style={{
            background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 7,
            padding: '6px 12px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 5,
          }}>
            <IconPlus size={12} /> Ny opskrift
          </button>
        </div>
        <div style={{ fontSize: 12, color: '#888', marginBottom: 10 }}>
          Farveformler, mængder og udviklingstid. Hentes nemt frem ved næste besøg.
        </div>

        {showNewRecipe && (
          <RecipeEditor
            onSave={addRecipe}
            onCancel={() => setShowNewRecipe(false)}
          />
        )}

        {recipes.length === 0 && !showNewRecipe && (
          <div style={{
            background: '#fff', border: '1px dashed #DDD9CE', borderRadius: 10,
            padding: '18px', textAlign: 'center', fontSize: 13, color: '#888',
          }}>
            Ingen opskrifter endnu. Tilføj den første for at gemme farveformler til kunden.
          </div>
        )}

        {recipes.length > 0 && (() => {
          const newestFirst = [...recipes].reverse();
          const visible = showAllRecipes ? newestFirst : newestFirst.slice(0, 1);
          const olderCount = newestFirst.length - 1;
          return (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {visible.map(r => (
                <RecipeCard
                  key={r.id}
                  recipe={r}
                  isEditing={editingRecipeId === r.id}
                  onEdit={() => setEditingRecipeId(r.id)}
                  onSave={(patch) => { updateRecipe(r.id, patch); setEditingRecipeId(null); }}
                  onCancel={() => setEditingRecipeId(null)}
                  onDelete={() => deleteRecipe(r.id)}
                />
              ))}
              {olderCount > 0 && (
                <button
                  onClick={() => setShowAllRecipes(v => !v)}
                  style={{
                    background: '#fff', border: '1px solid #DDD9CE', borderRadius: 8,
                    padding: '10px 14px', fontSize: 13, fontWeight: 500, color: '#3F4A3A',
                    cursor: 'pointer', fontFamily: 'inherit',
                    display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
                  }}
                >
                  <IconChevD size={13} style={{ transform: showAllRecipes ? 'rotate(180deg)' : 'none', transition: 'transform 120ms' }} />
                  {showAllRecipes
                    ? 'Skjul tidligere opskrifter'
                    : `Hent tidligere opskrifter (${olderCount})`}
                </button>
              )}
            </div>
          );
        })()}
      </div>

      {/* Kvitteringer */}
      {customerReceipts.length > 0 && (
        <div style={{ marginBottom: 28 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: '#1a1a1a', marginBottom: 4 }}>
            Kvitteringer ({customerReceipts.length})
          </div>
          <div style={{ fontSize: 12, color: '#888', marginBottom: 10 }}>
            Alle køb knyttet til kunden. Klik for at se en kvittering.
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {customerReceipts.map(sale => {
              const dt = new Date(sale.paidAt || Date.now());
              const dateStr = formatDanishShortDate(dt);
              const timeStr = dt.toLocaleTimeString('da-DK', { hour: '2-digit', minute: '2-digit' });
              const itemSummary = (sale.items || []).map(i => i.qty > 1 ? `${i.qty}× ${i.name}` : i.name).join(', ');
              return (
                <button key={sale.id} onClick={() => onShowReceipt && onShowReceipt(sale)} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '10px 14px', background: '#fff',
                  border: '1px solid #EFEDE5', borderRadius: 10,
                  cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit',
                  transition: 'all 120ms',
                }}
                onMouseEnter={e => { e.currentTarget.style.borderColor = '#7B8A6B'; e.currentTarget.style.background = '#FBFAF6'; }}
                onMouseLeave={e => { e.currentTarget.style.borderColor = '#EFEDE5'; e.currentTarget.style.background = '#fff'; }}>
                  <div style={{ width: 70, fontSize: 11, color: '#888' }}>
                    <div style={{ fontWeight: 600, color: '#1a1a1a' }}>{dateStr}</div>
                    <div>{timeStr}</div>
                  </div>
                  <div style={{ flex: 1, minWidth: 0, fontSize: 12, color: '#666', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {itemSummary || 'Salg'}
                  </div>
                  <div style={{ fontFamily: 'Fraunces, serif', fontSize: 16, fontWeight: 500 }}>
                    {sale.total} kr
                  </div>
                  <IconChevR size={14} stroke="#aaa" />
                </button>
              );
            })}
          </div>
        </div>
      )}

      {/* No-shows */}
      {customer.noShows && customer.noShows.length > 0 && (
        <div style={{ marginBottom: 28 }}>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 8,
            fontSize: 13, fontWeight: 600, color: '#A03838', marginBottom: 6,
          }}>
            <IconAlert size={15} stroke="#A03838" strokeWidth={2} />
            Udeblivelser ({customer.noShows.length})
          </div>
          <div style={{ fontSize: 12, color: '#888', marginBottom: 10 }}>
            Tider hvor kunden ikke mødte op. Brug fx til at kræve depositum eller blokere
            online-booking efter for mange udeblivelser.
          </div>
          <div style={{
            background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 10,
            overflow: 'hidden',
          }}>
            {[...customer.noShows].sort((a, b) => (b.date || '').localeCompare(a.date || '')).map((ns, i) => {
              const svcNames = (ns.serviceIds || []).map(id => SERVICE_BY_ID[id]?.name || '?').join(' + ');
              const staffName = STAFF.find(s => s.id === ns.staffId)?.name || 'Ukendt';
              const dateText = (() => {
                if (!ns.date) return 'Ukendt dato';
                try {
                  const [y, m, d] = ns.date.split('-').map(Number);
                  return formatDanishDate(new Date(y, m - 1, d));
                } catch { return ns.date; }
              })();
              return (
                <div key={i} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: '12px 16px',
                  borderBottom: i < customer.noShows.length - 1 ? '1px solid #FECACA' : 'none',
                }}>
                  <div style={{
                    width: 28, height: 28, borderRadius: 8, background: '#FECACA',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    color: '#A03838', fontSize: 14, fontWeight: 700, flexShrink: 0,
                  }}>×</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: '#1a1a1a' }}>{dateText}</div>
                    <div style={{ fontSize: 12, color: '#666', marginTop: 2 }}>
                      {svcNames || 'Ydelse slettet'} · hos {staffName}
                    </div>
                  </div>
                </div>
              );
            })}
          </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' }}>
          {customer.lastService
            ? `${SERVICE_BY_ID[customer.lastService]?.name || 'Ukendt ydelse'} hos ${fav ? fav.name : 'salonen'}`
            : 'Ingen tidligere besøg endnu.'}
        </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 => {
          // Lav beholdning ved 10 eller derunder; udsolgt ved 0.
          const hasStock = typeof p.stock === 'number';
          const outOfStock = hasStock && p.stock <= 0;
          const lowStock = hasStock && p.stock > 0 && p.stock <= 10;
          return (
            <div key={p.id} onClick={() => onEdit(p)} style={{
              background: '#fff', borderRadius: 12,
              border: outOfStock ? '1.5px solid #FECACA' : (lowStock ? '1.5px solid #F0DC9C' : '1px solid #EFEDE5'),
              overflow: 'hidden', cursor: 'pointer', transition: 'transform 120ms, box-shadow 120ms',
              position: 'relative',
            }}
            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'; }}>
              {/* Lille marker hængende i øverste-højre hjørne ved lav/udsolgt */}
              {(outOfStock || lowStock) && (
                <div style={{
                  position: 'absolute', top: 10, right: 10, zIndex: 1,
                  padding: '4px 9px', borderRadius: 12, fontSize: 10, fontWeight: 700,
                  letterSpacing: '0.04em', textTransform: 'uppercase',
                  background: outOfStock ? '#A03838' : '#8A6B1F',
                  color: '#fff',
                  boxShadow: '0 2px 6px rgba(0,0,0,0.12)',
                }}>
                  {outOfStock ? 'Udsolgt' : `Lav beholdning · ${p.stock} stk`}
                </div>
              )}
              <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'),
                    }}>
                      {hasStock ? 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 && (
                  <div style={{ marginTop: 10, padding: '6px 10px', background: '#FEF6DC', border: '1px solid #F0DC9C', borderRadius: 6, fontSize: 11, color: '#8A6B1F' }}>
                    Lav beholdning — kun {p.stock} stk tilbage
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>
    )}
  </div>
);

// ---------- Stats ----------
// Period presets — each returns { fromISO, toISO } where fromISO is inclusive
// and toISO is also inclusive. `null` for either side means open-ended.
function computePeriodRange(period, customDate) {
  const today = new Date();
  const iso = (d) => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
  const todayISO = iso(today);
  if (period === 'today') return { fromISO: todayISO, toISO: todayISO, label: 'I dag' };
  if (period === 'specific' && customDate) return { fromISO: customDate, toISO: customDate, label: 'Valgt dato' };
  if (period === '7') {
    const from = new Date(today); from.setDate(today.getDate() - 6);
    return { fromISO: iso(from), toISO: todayISO, label: 'Seneste 7 dage' };
  }
  if (period === '30') {
    const from = new Date(today); from.setDate(today.getDate() - 29);
    return { fromISO: iso(from), toISO: todayISO, label: 'Seneste 30 dage' };
  }
  if (period === '90') {
    const from = new Date(today); from.setDate(today.getDate() - 89);
    return { fromISO: iso(from), toISO: todayISO, label: 'Seneste 3 måneder' };
  }
  if (period === '180') {
    const from = new Date(today); from.setDate(today.getDate() - 179);
    return { fromISO: iso(from), toISO: todayISO, label: 'Seneste 6 måneder' };
  }
  if (period === '365') {
    const from = new Date(today); from.setDate(today.getDate() - 364);
    return { fromISO: iso(from), toISO: todayISO, label: 'Seneste år' };
  }
  return { fromISO: null, toISO: null, label: 'Alle tiders' };
}

const StatsView = ({ bookings, customers, sales = [], staff = [], onShowReceipt }) => {
  const [period, setPeriod] = React.useState('30'); // default: seneste 30 dage
  const [customDate, setCustomDate] = React.useState('');
  const [staffFilter, setStaffFilter] = React.useState('all'); // 'all' | staff.id
  const [receiptSearch, setReceiptSearch] = React.useState('');

  // When picking a specific date, switch period accordingly.
  React.useEffect(() => {
    if (customDate) setPeriod('specific');
  }, [customDate]);

  const range = React.useMemo(() => computePeriodRange(period, customDate), [period, customDate]);

  const inRange = React.useCallback((isoDate) => {
    if (!isoDate) return false;
    if (range.fromISO && isoDate < range.fromISO) return false;
    if (range.toISO && isoDate > range.toISO) return false;
    return true;
  }, [range.fromISO, range.toISO]);

  const matchesStaff = React.useCallback((b) => {
    if (staffFilter === 'all') return true;
    return b.staffId === staffFilter;
  }, [staffFilter]);

  // Bookings filtered to the period + staff.
  const filteredBookings = React.useMemo(() => {
    return bookings.filter(b => {
      if (range.fromISO || range.toISO) {
        if (!b.date || !inRange(b.date)) return false;
      }
      if (!matchesStaff(b)) return false;
      return true;
    });
  }, [bookings, range.fromISO, range.toISO, inRange, matchesStaff]);

  // Sales filtered to the period + staff + optional text search.
  const filteredSales = React.useMemo(() => {
    const q = receiptSearch.trim().toLowerCase();
    return sales.filter(s => {
      if (range.fromISO || range.toISO) {
        const saleDate = (s.paidAt || s.date || '').slice(0, 10);
        if (!inRange(saleDate)) return false;
      }
      if (staffFilter !== 'all' && s.staffId !== staffFilter) return false;
      if (q) {
        const cust = customers.find(c => c.id === s.customerId);
        const hayName = (cust?.name || '').toLowerCase();
        const hayItems = (s.items || []).map(i => i.name || '').join(' ').toLowerCase();
        if (!hayName.includes(q) && !hayItems.includes(q)) return false;
      }
      return true;
    });
  }, [sales, range.fromISO, range.toISO, inRange, staffFilter, receiptSearch, customers]);

  // Revenue: sum af salg i perioden (fallback til bookings hvis ingen salg).
  const totalRevenue = filteredSales.length > 0
    ? filteredSales.reduce((sum, s) => sum + (s.total || 0), 0)
    : filteredBookings.reduce((sum, b) => sum + getBookingPrice(b), 0);

  // Unique customers active in the filtered period.
  const activeCustomerCount = React.useMemo(() => {
    const ids = new Set();
    filteredBookings.forEach(b => { if (b.customerId) ids.add(b.customerId); });
    filteredSales.forEach(s => { if (s.customerId) ids.add(s.customerId); });
    return ids.size;
  }, [filteredBookings, filteredSales]);

  // Services distribution — counted from filtered bookings.
  const byService = SERVICES.map(s => ({
    ...s,
    count: filteredBookings.filter(b => (b.serviceIds || [b.serviceId]).includes(s.id)).length,
  }));
  const maxCount = Math.max(1, ...byService.map(b => b.count));

  // Nye vs eksisterende kunder — 'ny' = oprettet inden for sidste 30 dage,
  // eller kunden har 1 eller færre visits. Beregnet ud fra de kunder som
  // har en booking eller et salg i den valgte periode.
  const customerBreakdown = React.useMemo(() => {
    const ids = new Set();
    filteredBookings.forEach(b => { if (b.customerId) ids.add(b.customerId); });
    filteredSales.forEach(s => { if (s.customerId) ids.add(s.customerId); });
    const thirtyDaysAgo = Date.now() - 30 * 86400000;
    let neu = 0, eks = 0, male = 0, female = 0, unknown = 0;
    ids.forEach(id => {
      const c = customers.find(x => x.id === id);
      if (!c) return;
      const created = c.createdAt ? new Date(c.createdAt).getTime() : 0;
      const isNew = (created && created > thirtyDaysAgo) || (c.visits || 0) <= 1;
      if (isNew) neu++; else eks++;
      if (c.gender === 'male') male++;
      else if (c.gender === 'female') female++;
      else unknown++;
    });
    const tot = neu + eks || 1;
    const totG = male + female + unknown || 1;
    return {
      total: ids.size,
      newCount: neu, newPct: Math.round((neu / tot) * 100),
      existingCount: eks, existingPct: Math.round((eks / tot) * 100),
      maleCount: male, malePct: Math.round((male / totG) * 100),
      femaleCount: female, femalePct: Math.round((female / totG) * 100),
      unknownCount: unknown,
    };
  }, [filteredBookings, filteredSales, customers]);

  // Estimeret omsætning på 'i dag' — pris-sum af alle bookings i dag uanset status.
  const todayISO = (() => {
    const t = new Date();
    return `${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,'0')}-${String(t.getDate()).padStart(2,'0')}`;
  })();
  const todayEstimate = React.useMemo(() => {
    return bookings.filter(b => b.date === todayISO)
      .reduce((sum, b) => sum + getBookingPrice(b), 0);
  }, [bookings, todayISO]);

  // Smiley-vurdering af omsætningen mod et target. Target sættes ud fra
  // periode-længde: 30 dage = ~150 000 kr, kvartal = ~450 000 kr.
  // Brugeren kan i fremtiden gøre dette konfigurerbart i Indstillinger.
  const revenueAssessment = React.useMemo(() => {
    let target = 5000; // i dag
    if (range.label.includes('7 dage')) target = 30000;
    else if (range.label.includes('30 dage')) target = 130000;
    else if (range.label.includes('3 mån') || range.label.includes('3 må')) target = 390000;
    else if (range.label.includes('6 mån') || range.label.includes('6 må')) target = 780000;
    else if (range.label.includes('år')) target = 1500000;
    else if (range.label === 'Alle tiders') target = totalRevenue; // ingen vurdering
    const pct = target > 0 ? Math.round((totalRevenue / target) * 100) : 100;
    let MoodIcon, color, label;
    if (pct >= 100)     { MoodIcon = IconSmileyHappy; color = '#3F5A30'; label = 'Mål nået'; }
    else if (pct >= 75) { MoodIcon = IconSmileyOk;    color = '#7B8A6B'; label = 'Godt på vej'; }
    else if (pct >= 50) { MoodIcon = IconSmileyFlat;  color = '#B45309'; label = 'Halvvejs'; }
    else                { MoodIcon = IconSmileySad;   color = '#A03838'; label = 'Under målet'; }
    return { target, pct, MoodIcon, color, label };
  }, [range.label, totalRevenue]);

  // Pretty header label
  const selectedStaffName = staffFilter === 'all'
    ? null
    : (staff.find(s => s.id === staffFilter)?.name || null);
  const headerLabel = `Statistik · ${range.label}${selectedStaffName ? ` · ${selectedStaffName}` : ''}`;

  const periodOptions = [
    { id: 'today',   label: 'I dag' },
    { id: '7',       label: 'Seneste 7 dage' },
    { id: '30',      label: 'Seneste 30 dage' },
    { id: '90',      label: 'Seneste 3 måneder' },
    { id: '180',     label: 'Seneste 6 måneder' },
    { id: '365',     label: 'Seneste år' },
    { id: 'all',     label: 'Alle tiders' },
  ];

  return (
    <div style={{ padding: '24px 32px', height: '100%', overflow: 'auto', background: '#FBFAF6' }}>
      {/* Header */}
      <h1 style={{ fontFamily: 'Fraunces, serif', fontSize: 28, fontWeight: 500, margin: '0 0 14px 0' }}>
        {headerLabel}
      </h1>

      {/* Filter-bar — periode, medarbejder, dato */}
      <div style={{
        background: '#fff', borderRadius: 12, border: '1px solid #EFEDE5',
        padding: 14, marginBottom: 18,
        display: 'flex', alignItems: 'center', gap: 14, flexWrap: 'wrap',
      }}>
        <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
          {periodOptions.map(opt => (
            <button key={opt.id}
              onClick={() => { setPeriod(opt.id); setCustomDate(''); }}
              style={{
                padding: '7px 12px', borderRadius: 7, fontSize: 12, fontFamily: 'inherit', fontWeight: 600,
                cursor: 'pointer', border: '1px solid',
                borderColor: period === opt.id && !customDate ? '#3F4A3A' : '#DDD9CE',
                background: period === opt.id && !customDate ? '#3F4A3A' : '#fff',
                color: period === opt.id && !customDate ? '#fff' : '#444',
              }}>{opt.label}</button>
          ))}
        </div>

        <div style={{ height: 24, width: 1, background: '#EFEDE5' }} />

        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ fontSize: 12, color: '#888' }}>Specifik dato:</span>
          <input
            type="date"
            value={customDate}
            onChange={e => setCustomDate(e.target.value)}
            style={{ ...inputStyle, fontSize: 13, padding: '6px 10px', width: 150 }}
          />
          {customDate && (
            <button onClick={() => setCustomDate('')} style={{
              background: 'transparent', color: '#888', border: 'none',
              padding: '4px 8px', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit',
            }}>Ryd</button>
          )}
        </div>

        <div style={{ height: 24, width: 1, background: '#EFEDE5' }} />

        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{ fontSize: 12, color: '#888' }}>Medarbejder:</span>
          <select
            value={staffFilter}
            onChange={e => setStaffFilter(e.target.value)}
            style={{ ...inputStyle, fontSize: 13, padding: '6px 10px', minWidth: 160 }}
          >
            <option value="all">Alle medarbejdere</option>
            {staff.map(s => (
              <option key={s.id} value={s.id}>{s.name}</option>
            ))}
          </select>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 16 }}>
        <StatCard label="Bookinger" value={filteredBookings.length} />
        <StatCard label="Omsætning" value={`${totalRevenue.toLocaleString('da-DK')} kr`} />
        <StatCard label="Kunder i perioden" value={activeCustomerCount} />
        <StatCard label="Salg" value={filteredSales.length} />
      </div>

      {/* Smiley-vurdering af omsætning */}
      {range.label !== 'Alle tiders' && (() => {
        const M = revenueAssessment.MoodIcon;
        return (
          <div style={{
            background: '#fff', borderRadius: 12, border: '1px solid #EFEDE5',
            padding: '18px 20px', marginBottom: 16,
            display: 'flex', alignItems: 'center', gap: 18,
          }}>
            <div style={{
              width: 56, height: 56, borderRadius: '50%', flexShrink: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: revenueAssessment.color + '14', // 8% alpha
              color: revenueAssessment.color,
            }}>
              <M size={36} strokeWidth={1.8} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13, color: revenueAssessment.color, fontWeight: 600, marginBottom: 4 }}>
                {revenueAssessment.label}
              </div>
              <div style={{
                height: 10, background: '#F4F2EA', borderRadius: 5,
                overflow: 'hidden', marginBottom: 6,
              }}>
                <div style={{
                  height: '100%', width: `${Math.min(100, revenueAssessment.pct)}%`,
                  background: revenueAssessment.color, transition: 'width 400ms',
                }} />
              </div>
              <div style={{ fontSize: 12, color: '#666' }}>
                <strong style={{ color: revenueAssessment.color }}>{revenueAssessment.pct}%</strong> af målet · {totalRevenue.toLocaleString('da-DK')} kr af {revenueAssessment.target.toLocaleString('da-DK')} kr
              </div>
            </div>
          </div>
        );
      })()}

      {/* Kunde-fordeling: nye vs eksisterende, og køn */}
      <div style={{
        background: '#fff', borderRadius: 12, border: '1px solid #EFEDE5',
        padding: '18px 20px', marginBottom: 16,
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 24,
      }}>
        <div>
          <div style={{ fontSize: 12, color: '#888', fontWeight: 600, marginBottom: 10, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
            Kunder
          </div>
          <div style={{ display: 'flex', height: 24, borderRadius: 6, overflow: 'hidden', background: '#F4F2EA', marginBottom: 8 }}>
            <div style={{ width: `${customerBreakdown.newPct}%`, background: '#C9D8B5' }} title={`Nye: ${customerBreakdown.newCount}`} />
            <div style={{ width: `${customerBreakdown.existingPct}%`, background: '#7B8A6B' }} title={`Eksisterende: ${customerBreakdown.existingCount}`} />
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
            <span><span style={{ display: 'inline-block', width: 9, height: 9, borderRadius: 2, background: '#C9D8B5', marginRight: 5 }} />Nye: <strong>{customerBreakdown.newCount}</strong> ({customerBreakdown.newPct}%)</span>
            <span><span style={{ display: 'inline-block', width: 9, height: 9, borderRadius: 2, background: '#7B8A6B', marginRight: 5 }} />Eksisterende: <strong>{customerBreakdown.existingCount}</strong> ({customerBreakdown.existingPct}%)</span>
          </div>
        </div>
        <div>
          <div style={{ fontSize: 12, color: '#888', fontWeight: 600, marginBottom: 10, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
            Kønsfordeling
          </div>
          <div style={{ display: 'flex', height: 24, borderRadius: 6, overflow: 'hidden', background: '#F4F2EA', marginBottom: 8 }}>
            <div style={{ width: `${customerBreakdown.femalePct}%`, background: '#E8B4D2' }} title={`Damer: ${customerBreakdown.femaleCount}`} />
            <div style={{ width: `${customerBreakdown.malePct}%`, background: '#B4C8E8' }} title={`Mænd: ${customerBreakdown.maleCount}`} />
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12 }}>
            <span><span style={{ display: 'inline-block', width: 9, height: 9, borderRadius: 2, background: '#E8B4D2', marginRight: 5 }} />Damer: <strong>{customerBreakdown.femaleCount}</strong> ({customerBreakdown.femalePct}%)</span>
            <span><span style={{ display: 'inline-block', width: 9, height: 9, borderRadius: 2, background: '#B4C8E8', marginRight: 5 }} />Mænd: <strong>{customerBreakdown.maleCount}</strong> ({customerBreakdown.malePct}%)</span>
          </div>
        </div>
      </div>

      {/* I dag — estimeret omsætning baseret på dagens bookings */}
      <div style={{
        background: '#fff', borderRadius: 12, border: '1px solid #EFEDE5',
        padding: '16px 20px', marginBottom: 24,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <div>
          <div style={{ fontSize: 12, color: '#888', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em' }}>
            Estimeret omsætning · i dag
          </div>
          <div style={{ fontSize: 13, color: '#666', marginTop: 2 }}>
            Baseret på {bookings.filter(b => b.date === todayISO).length} bookede aftaler i dag
          </div>
        </div>
        <div style={{ fontFamily: 'Fraunces, serif', fontSize: 28, fontWeight: 500, color: '#1a1a1a' }}>
          {todayEstimate.toLocaleString('da-DK')} kr
        </div>
      </div>

      <div style={{ background: '#fff', borderRadius: 12, border: '1px solid #EFEDE5', padding: 24 }}>
        <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 18 }}>
          Ydelser fordelt · {range.label}
        </div>
        {filteredBookings.length === 0 ? (
          <div style={{ fontSize: 13, color: '#888', textAlign: 'center', padding: '20px 0' }}>
            Ingen bookinger i den valgte periode.
          </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>

      {/* ── Sales / receipts ─────────────────────────────────────────── */}
      <div style={{ marginTop: 24, background: '#fff', borderRadius: 12, border: '1px solid #EFEDE5', padding: 24 }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14, flexWrap: 'wrap', gap: 10 }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>Køb og kvitteringer</div>
            <div style={{ fontSize: 12, color: '#888', marginTop: 2 }}>
              Klik på et salg for at se kvitteringen, printe den eller sende den på email.
            </div>
          </div>
          <div style={{ fontSize: 12, color: '#888' }}>
            {filteredSales.length} af {sales.length} salg ·{' '}
            <strong style={{ color: '#1a1a1a' }}>
              {filteredSales.reduce((s, x) => s + (x.total || 0), 0).toLocaleString('da-DK')} kr
            </strong>
          </div>
        </div>

        {/* Tekst-søgning i kvitteringer (dato kontrolleres af det globale filter ovenfor) */}
        <div style={{ display: 'flex', gap: 10, marginBottom: 14, flexWrap: 'wrap', alignItems: 'center' }}>
          <div style={{ position: 'relative', flex: '1 1 200px', minWidth: 200 }}>
            <div style={{ position: 'absolute', left: 10, top: 9, color: '#999' }}><IconSearch size={14} /></div>
            <input
              value={receiptSearch}
              onChange={e => setReceiptSearch(e.target.value)}
              placeholder="Søg kunde eller vare…"
              style={{ ...inputStyle, paddingLeft: 32, width: '100%', fontSize: 13, padding: '7px 10px 7px 32px' }}
            />
          </div>
          {receiptSearch && (
            <button onClick={() => setReceiptSearch('')} style={{
              background: '#fff', color: '#666', border: '1px solid #DDD9CE',
              borderRadius: 7, padding: '7px 12px', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit',
            }}>Ryd søgning</button>
          )}
        </div>

        {sales.length === 0 ? (
          <div style={{
            background: '#FBFAF6', border: '1px dashed #DDD9CE', borderRadius: 10,
            padding: '28px 20px', textAlign: 'center', fontSize: 13, color: '#888', lineHeight: 1.55,
          }}>
            Ingen salg endnu.<br/>
            Salg dukker op her når en booking går gennem kassen.
          </div>
        ) : filteredSales.length === 0 ? (
          <div style={{
            background: '#FBFAF6', border: '1px dashed #DDD9CE', borderRadius: 10,
            padding: '28px 20px', textAlign: 'center', fontSize: 13, color: '#888', lineHeight: 1.55,
          }}>
            Ingen salg matcher den valgte periode{receiptSearch ? ' eller søgning' : ''}.
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {[...filteredSales].sort((a, b) => (b.paidAt || '').localeCompare(a.paidAt || '')).slice(0, 100).map(sale => {
              const cust = customers.find(c => c.id === sale.customerId);
              const dateObj = new Date(sale.paidAt || Date.now());
              const dateStr = formatDanishShortDate(dateObj);
              const timeStr = dateObj.toLocaleTimeString('da-DK', { hour: '2-digit', minute: '2-digit' });
              const itemSummary = sale.items.map(i => i.qty > 1 ? `${i.qty}× ${i.name}` : i.name).join(', ');
              const methodIcon = sale.method === 'cash' ? '· Kontant'
                : sale.method === 'mobile' ? '· MobilePay' : '· Kort';
              return (
                <button key={sale.id} onClick={() => onShowReceipt && onShowReceipt(sale)} style={{
                  display: 'flex', alignItems: 'center', gap: 14,
                  padding: '12px 14px', background: '#FBFAF6',
                  border: '1px solid #EFEDE5', borderRadius: 10,
                  cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit',
                  transition: 'all 120ms',
                }}
                onMouseEnter={e => { e.currentTarget.style.borderColor = '#7B8A6B'; e.currentTarget.style.background = '#F4F7F0'; }}
                onMouseLeave={e => { e.currentTarget.style.borderColor = '#EFEDE5'; e.currentTarget.style.background = '#FBFAF6'; }}>
                  <div style={{ width: 60, fontSize: 11, color: '#888' }}>
                    <div style={{ fontWeight: 600, color: '#1a1a1a' }}>{dateStr}</div>
                    <div>{timeStr}</div>
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 13, fontWeight: 500, color: '#1a1a1a', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {cust?.name || 'Walk-in kunde'}
                    </div>
                    <div style={{ fontSize: 12, color: '#666', marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {itemSummary} {methodIcon}
                    </div>
                  </div>
                  <div style={{ fontFamily: 'Fraunces, serif', fontSize: 17, fontWeight: 500, fontVariantNumeric: 'tabular-nums' }}>
                    {sale.total} kr
                  </div>
                  <IconChevR size={14} stroke="#aaa" />
                </button>
              );
            })}
            {filteredSales.length > 100 && (
              <div style={{ fontSize: 12, color: '#888', textAlign: 'center', padding: 10 }}>
                Viser de seneste 100 af {filteredSales.length} matchende salg.
              </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 updateField = (deptId, patch) => {
    onUpdateDepartments(departments.map(d => d.id === deptId ? { ...d, ...patch } : d));
  };

  const setAsDefault = (deptId) => {
    // Only one department can be default; flip everyone else off
    onUpdateDepartments(departments.map(d => ({ ...d, isDefault: d.id === deptId })));
  };

  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', display: 'flex', alignItems: 'center', gap: 6 }}>
                    {d.name}
                    {d.isDefault && (
                      <span title="Hovedafdeling — vises som standard i kalenderen" style={{
                        fontSize: 10, fontWeight: 700, color: '#3F5A30',
                        background: '#F4F7F0', border: '1px solid #DCE6CC',
                        padding: '1px 6px', borderRadius: 10, letterSpacing: '0.04em',
                      }}>HOVED</span>
                    )}
                  </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>

          {/* Info-card: default flag, manager, phone, address */}
          <div style={{
            background: '#fff', border: '1px solid #EFEDE5', borderRadius: 12,
            padding: '20px 22px', marginBottom: 28,
          }}>
            <div style={{
              fontSize: 11, fontWeight: 700, color: '#888',
              letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 16,
            }}>Afdelings-oplysninger</div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
              {/* Manager */}
              <div>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: '#555', marginBottom: 6 }}>
                  Afdelingsleder
                </label>
                <select
                  value={selected.managerId || ''}
                  onChange={e => updateField(selected.id, { managerId: e.target.value || null })}
                  style={{ ...inputStyle, width: '100%', boxSizing: 'border-box' }}
                >
                  <option value="">— Ingen valgt —</option>
                  {staff.map(s => (
                    <option key={s.id} value={s.id}>
                      {s.name}{s.role ? ` (${s.role})` : ''}
                    </option>
                  ))}
                </select>
                {selected.managerId && !staff.find(s => s.id === selected.managerId) && (
                  <div style={{ fontSize: 11, color: '#B45309', marginTop: 4 }}>
                    Den valgte medarbejder er slettet — vælg en anden.
                  </div>
                )}
              </div>

              {/* Phone */}
              <div>
                <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: '#555', marginBottom: 6 }}>
                  Telefon
                </label>
                <input
                  type="tel"
                  value={selected.phone || ''}
                  onChange={e => updateField(selected.id, { phone: e.target.value })}
                  placeholder="+45 50 92 02 01"
                  style={{ ...inputStyle, width: '100%', boxSizing: 'border-box' }}
                />
              </div>
            </div>

            {/* Address (full width) */}
            <div style={{ marginBottom: 16 }}>
              <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: '#555', marginBottom: 6 }}>
                Adresse
              </label>
              <input
                type="text"
                value={selected.address || ''}
                onChange={e => updateField(selected.id, { address: e.target.value })}
                placeholder="Eksempelgade 12, 2100 København Ø"
                style={{ ...inputStyle, width: '100%', boxSizing: 'border-box' }}
              />
            </div>

            {/* Default toggle */}
            <div style={{
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              padding: '12px 14px', background: selected.isDefault ? '#F4F7F0' : '#FBFAF6',
              border: `1px solid ${selected.isDefault ? '#DCE6CC' : '#EFEDE5'}`, borderRadius: 8,
            }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: '#1a1a1a' }}>
                  Hovedafdeling
                </div>
                <div style={{ fontSize: 12, color: '#666', marginTop: 2 }}>
                  Vises som standard i kalenderen ved første login.
                </div>
              </div>
              {selected.isDefault ? (
                <span style={{
                  padding: '6px 14px', background: '#3F5A30', color: '#fff',
                  borderRadius: 16, fontSize: 12, fontWeight: 600,
                }}>✓ Aktiv</span>
              ) : (
                <button onClick={() => setAsDefault(selected.id)} style={{
                  background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 8,
                  padding: '8px 14px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
                }}>Gør til hovedafdeling</button>
              )}
            </div>
          </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 });
