// Admin extras: staff editor (with photo), notifications dropdown, settings panel,
// PIN-timeout chooser

// ---------- PIN first-time setup ----------
// Shown to the salon owner on first login when no PIN has been set yet.
// Blocks the entire app until a 6-digit PIN is chosen + confirmed.
const PinSetupModal = ({ salonName, onSetPin }) => {
  const [step, setStep] = React.useState('enter'); // 'enter' | 'confirm'
  const [enteredPin, setEnteredPin] = React.useState('');
  const [confirmPin, setConfirmPin] = React.useState('');
  const [error, setError] = React.useState('');

  const target = step === 'enter' ? enteredPin : confirmPin;
  const setTarget = step === 'enter' ? setEnteredPin : setConfirmPin;

  const press = (d) => {
    if (target.length >= 6) return;
    setError('');
    setTarget(target + d);
  };
  const back = () => setTarget(target.slice(0, -1));
  const reset = () => {
    setEnteredPin(''); setConfirmPin(''); setError(''); setStep('enter');
  };

  React.useEffect(() => {
    if (step === 'enter' && enteredPin.length === 6) {
      const t = setTimeout(() => setStep('confirm'), 250);
      return () => clearTimeout(t);
    }
    if (step === 'confirm' && confirmPin.length === 6) {
      const t = setTimeout(() => {
        if (confirmPin === enteredPin) {
          onSetPin(enteredPin);
        } else {
          setError('Koderne matcher ikke. Prøv igen.');
          setEnteredPin(''); setConfirmPin(''); setStep('enter');
        }
      }, 250);
      return () => clearTimeout(t);
    }
  }, [enteredPin, confirmPin, step]);

  // Keyboard support
  React.useEffect(() => {
    const onKey = (e) => {
      if (/^[0-9]$/.test(e.key)) press(e.key);
      else if (e.key === 'Backspace') back();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  });

  const dotColor = error ? '#A03838' : (target.length === 6 ? '#3F5A30' : '#3F4A3A');
  const subtitle = step === 'enter'
    ? 'Vælg en 6-cifret PIN. Den beskytter prisændringer, sletninger og medarbejderoplysninger.'
    : 'Indtast PIN-koden igen for at bekræfte.';

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9999,
      background: 'linear-gradient(145deg, #FBFAF6 0%, #ECE8DF 100%)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: "'Manrope', sans-serif", padding: 20,
      animation: 'fadeIn 0.3s ease',
    }}>
      <div style={{
        width: 420, padding: '40px 36px',
        background: '#fff', borderRadius: 20,
        boxShadow: '0 12px 48px rgba(0,0,0,0.12)',
        animation: 'slideUp 0.3s ease',
      }}>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{
            width: 56, height: 56, margin: '0 auto 16px',
            background: '#3F4A3A', borderRadius: 14,
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff',
          }}>
            <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
              <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
            </svg>
          </div>
          <div style={{ fontSize: 11, color: '#7B8A6B', fontWeight: 700, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            Velkommen til {salonName}
          </div>
          <h1 style={{
            fontFamily: "'Fraunces', serif", fontSize: 26, fontWeight: 500,
            margin: '8px 0 10px',
          }}>
            {step === 'enter' ? 'Opret din PIN-kode' : 'Bekræft din PIN-kode'}
          </h1>
          <p style={{ fontSize: 13, color: '#666', margin: 0, lineHeight: 1.55 }}>{subtitle}</p>
        </div>

        {/* PIN dots */}
        <div style={{ display: 'flex', justifyContent: 'center', gap: 10, marginBottom: 18 }}>
          {Array(6).fill(0).map((_, i) => (
            <div key={i} style={{
              width: 38, height: 46, borderRadius: 9,
              border: `1.5px solid ${error ? '#FECACA' : '#DDD9CE'}`,
              background: '#FBFAF6',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 24, fontWeight: 700, color: dotColor,
              transition: 'border-color 0.15s',
            }}>{target[i] ? '•' : ''}</div>
          ))}
        </div>

        {error && (
          <div style={{
            padding: '10px 14px', marginBottom: 14, textAlign: 'center',
            background: '#FEF2F2', border: '1px solid #FECACA',
            borderRadius: 8, fontSize: 13, color: '#B91C1C',
          }}>{error}</div>
        )}

        {/* Keypad */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
          {[1,2,3,4,5,6,7,8,9].map(n => (
            <button key={n} onClick={() => press(String(n))} style={pinKeyStyle}>{n}</button>
          ))}
          <button onClick={back} style={{ ...pinKeyStyle, color: '#A03838', fontSize: 18 }}>←</button>
          <button onClick={() => press('0')} style={pinKeyStyle}>0</button>
          <button onClick={reset} style={{ ...pinKeyStyle, fontSize: 12, color: '#888' }}>Ryd</button>
        </div>

        <p style={{
          marginTop: 20, fontSize: 11, color: '#aaa', textAlign: 'center', lineHeight: 1.5,
        }}>
          Du kan ændre PIN-koden senere under Indstillinger.
          <br/>Saloniq er udviklet af{' '}
          <a href="https://ooniq.dk" target="_blank" rel="noopener noreferrer"
             style={{ color: '#888', textDecoration: 'none', fontWeight: 600, borderBottom: '1px dotted #ccc' }}>ooniq</a>.
        </p>
      </div>
    </div>
  );
};

const pinKeyStyle = {
  padding: '14px 0', background: '#FBFAF6', border: '1.5px solid #E5E2D5',
  borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit',
  fontSize: 19, fontWeight: 500, color: '#1a1a1a',
  transition: 'all 120ms',
};

// ---------- PIN timeout chooser ----------
const PIN_TIMEOUTS = [
  { value: 60_000,           label: '1 minut'   },
  { value: 5  * 60_000,      label: '5 minutter' },
  { value: 15 * 60_000,      label: '15 minutter' },
  { value: 60 * 60_000,      label: '1 time'    },
  { value: 0,                label: 'Indtil jeg lukker fanen' },
];

const PinTimeoutModal = ({ open, onClose, onChoose }) => {
  if (!open) return null;
  return (
    <Backdrop onClose={onClose} width={380}>
      <div style={{ padding: '24px 28px', borderBottom: '1px solid #EFEDE5' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
          <div style={{ width: 32, height: 32, borderRadius: 8, background: '#F4F7F0', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#3F5A30' }}>
            <IconCheck size={18} />
          </div>
          <div style={{ fontSize: 11, color: '#3F5A30', fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase' }}>PIN godkendt</div>
        </div>
        <div style={{ fontSize: 18, fontWeight: 600, color: '#1a1a1a', marginTop: 6 }}>Hvor længe skal låsen være åben?</div>
        <div style={{ fontSize: 13, color: '#888', marginTop: 4, lineHeight: 1.5 }}>Efter den valgte tid kræves PIN igen for admin-handlinger.</div>
      </div>
      <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 6 }}>
        {PIN_TIMEOUTS.map(t => (
          <button key={t.value} onClick={() => onChoose(t.value)} style={{
            background: '#fff', border: '1.5px solid #E5E2D5', borderRadius: 10,
            padding: '12px 16px', cursor: 'pointer', textAlign: 'left',
            fontFamily: 'inherit', fontSize: 14, fontWeight: 500, color: '#1a1a1a',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            transition: 'all 120ms',
          }} onMouseEnter={e => { e.currentTarget.style.borderColor = '#7B8A6B'; e.currentTarget.style.background = '#F4F7F0'; }}
             onMouseLeave={e => { e.currentTarget.style.borderColor = '#E5E2D5'; e.currentTarget.style.background = '#fff'; }}>
            <span>{t.label}</span>
            <IconChevR size={14} stroke="#888" />
          </button>
        ))}
      </div>
    </Backdrop>
  );
};

// ---------- Staff editor ----------
const TONE_PALETTE = ['#E8C8B4','#B4D2E8','#D8C0E0','#C8DCB4','#F0CFC0','#E8DBC8','#C8E2DC','#F2D8C0'];

// Wrapper avoids the rules-of-hooks violation: the inner form only mounts when
// staff is truthy, and the key forces a fresh mount when switching between
// different staff members so each one's data initializes correctly.
const StaffEditorModal = (props) => {
  if (!props.staff) return null;
  return <StaffEditorModalForm key={props.staff.id || '_new'} {...props} />;
};

const StaffEditorModalForm = ({ staff, onClose, onSave, onDelete }) => {
  const isNew = !staff.id || staff._isNew;
  const [name, setName] = React.useState(staff.name || '');
  const [role, setRole] = React.useState(staff.role || 'Frisør');
  const [phone, setPhone] = React.useState(staff.phone || '');
  const [email, setEmail] = React.useState(staff.email || '');
  const [tone, setTone] = React.useState(staff.tone || TONE_PALETTE[0]);
  const [photo, setPhoto] = React.useState(staff.photo || null);
  const [specialtiesStr, setSpecialtiesStr] = React.useState(
    Array.isArray(staff.specialties) ? staff.specialties.join(', ') : ''
  );
  const [schedule, setSchedule] = React.useState(staff.schedule || {
    man: '9–17', tir: '9–17', ons: '9–17', tor: '9–18', fre: '9–18', lor: '9–14'
  });
  const fileRef = React.useRef(null);
  const initials = (name || '').split(/\s+/).filter(Boolean).map(p => p[0]).slice(0, 2).join('').toUpperCase() || '?';

  const onPhotoChange = (e) => {
    const f = e.target.files?.[0];
    if (!f) return;
    const reader = new FileReader();
    reader.onload = ev => setPhoto(ev.target.result);
    reader.readAsDataURL(f);
  };

  const canSave = name.trim().length > 0;
  const submit = () => {
    if (!canSave) return;
    onSave({
      id: staff.id || ('s' + Date.now()),
      name: name.trim(),
      role,
      phone, email,
      tone,
      photo,
      initials,
      specialties: specialtiesStr.split(',').map(s => s.trim()).filter(Boolean),
      schedule,
    });
  };

  return (
    <Backdrop onClose={onClose} width={620}>
      <div style={{ padding: '20px 28px', borderBottom: '1px solid #EFEDE5', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <div style={{ fontSize: 11, color: '#888', fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase' }}>{isNew ? 'Ny medarbejder' : 'Rediger medarbejder'}</div>
          <div style={{ fontSize: 18, fontWeight: 600, color: '#1a1a1a', marginTop: 2 }}>{name || 'Uden navn'}</div>
        </div>
        <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#888' }}>
          <IconX size={20} />
        </button>
      </div>

      <div style={{ padding: 24, display: 'grid', gridTemplateColumns: '160px 1fr', gap: 24 }}>
        {/* Photo column */}
        <div>
          <div style={{
            width: 140, height: 140, borderRadius: 14,
            background: photo ? `url(${photo}) center/cover` : tone,
            border: '1.5px solid #E5E2D5',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'Fraunces, serif', fontSize: 44, fontWeight: 500,
            color: '#3F4A3A', marginBottom: 10,
            backgroundColor: tone,
          }}>
            {!photo && initials}
          </div>
          <input type="file" accept="image/*" ref={fileRef} onChange={onPhotoChange} style={{ display: 'none' }} />
          <button onClick={() => fileRef.current?.click()} style={{
            width: 140, background: '#fff', border: '1.5px solid #DDD9CE', borderRadius: 8,
            padding: '8px 10px', fontSize: 12, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
            color: '#3F4A3A', marginBottom: 6,
          }}>📷 {photo ? 'Skift billede' : 'Upload billede'}</button>
          {photo && (
            <button onClick={() => setPhoto(null)} style={{
              width: 140, background: 'transparent', border: 'none',
              padding: '4px 0', fontSize: 11, cursor: 'pointer', fontFamily: 'inherit',
              color: '#A03838',
            }}>Fjern billede</button>
          )}

          <div style={{ marginTop: 14, fontSize: 11, color: '#888', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6 }}>Avatarfarve</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 4 }}>
            {TONE_PALETTE.map(t => (
              <button key={t} onClick={() => setTone(t)} title={t} style={{
                width: '100%', aspectRatio: '1', borderRadius: 6,
                background: t, cursor: 'pointer',
                border: tone === t ? '2px solid #1a1a1a' : '1px solid #E5E2D5',
              }} />
            ))}
          </div>
        </div>

        {/* Form column */}
        <div>
          <Field label="Navn" required>
            <TextInput value={name} onChange={e => setName(e.target.value)} placeholder="Fornavn Efternavn" autoFocus />
          </Field>
          <Field label="Rolle">
            <select value={role} onChange={e => setRole(e.target.value)} style={{ ...inputStyle, width: '100%' }}>
              <option>Junior frisør</option>
              <option>Frisør</option>
              <option>Senior frisør</option>
              <option>Salonchef</option>
              <option>Lærling</option>
            </select>
          </Field>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <Field label="Telefon">
              <TextInput value={phone} onChange={e => setPhone(e.target.value)} placeholder="+45 ..." />
            </Field>
            <Field label="Email">
              <TextInput value={email} onChange={e => setEmail(e.target.value)} placeholder="navn@ooniq.dk" />
            </Field>
          </div>
          <Field label="Specialer (komma-adskilt)">
            <TextInput value={specialtiesStr} onChange={e => setSpecialtiesStr(e.target.value)} placeholder="Dameklip, Helfarve, Behandling" />
          </Field>

          <div style={{ fontSize: 12, color: '#666', fontWeight: 600, marginBottom: 6, marginTop: 4 }}>Vagtplan</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 4, marginBottom: 4 }}>
            {[['man','Man'],['tir','Tir'],['ons','Ons'],['tor','Tor'],['fre','Fre'],['lor','Lør']].map(([k,l]) => (
              <div key={k}>
                <div style={{ fontSize: 10, color: '#888', textAlign: 'center', marginBottom: 2 }}>{l}</div>
                <input
                  value={schedule[k]}
                  onChange={e => setSchedule({ ...schedule, [k]: e.target.value })}
                  placeholder="Fri"
                  style={{
                    width: '100%', padding: '6px 4px', textAlign: 'center',
                    border: '1px solid #DDD9CE', borderRadius: 6,
                    fontSize: 11, fontFamily: 'inherit', background: '#FBFAF6',
                  }}
                />
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={{ padding: '14px 24px', borderTop: '1px solid #EFEDE5', display: 'flex', justifyContent: 'space-between', background: '#FBFAF6' }}>
        <div>
          {!isNew && (
            <button onClick={() => onDelete(staff)} style={{
              background: 'transparent', color: '#A03838', border: 'none',
              padding: '8px 12px', fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
            }}>Slet medarbejder</button>
          )}
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <SecondaryBtn onClick={onClose}>Annullér</SecondaryBtn>
          <PrimaryBtn onClick={submit} disabled={!canSave}>{isNew ? 'Opret' : 'Gem ændringer'}</PrimaryBtn>
        </div>
      </div>
    </Backdrop>
  );
};

// ---------- Product editor ----------
const ProductEditorModal = (props) => {
  if (!props.product) return null;
  return <ProductEditorModalForm key={props.product.id || '_new'} {...props} />;
};

const ProductEditorModalForm = ({ product, onClose, onSave, onDelete }) => {
  const isNew = !product.id || product._isNew;
  const [name, setName] = React.useState(product.name || '');
  const [brand, setBrand] = React.useState(product.brand || '');
  const [price, setPrice] = React.useState(product.price ?? '');
  const [stock, setStock] = React.useState(product.stock ?? '');
  const [notes, setNotes] = React.useState(product.notes || '');

  const canSave = name.trim().length > 0 && price !== '' && !isNaN(Number(price));
  const submit = () => {
    if (!canSave) return;
    onSave({
      id: product.id || ('p' + Date.now()),
      name: name.trim(),
      brand: brand.trim(),
      price: Number(price),
      stock: stock === '' ? null : Number(stock),
      notes: notes.trim(),
    });
  };

  return (
    <Backdrop onClose={onClose} width={520}>
      <div style={{ padding: '20px 28px', borderBottom: '1px solid #EFEDE5', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <div>
          <div style={{ fontSize: 11, color: '#888', fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
            {isNew ? 'Nyt produkt' : 'Rediger produkt'}
          </div>
          <div style={{ fontSize: 18, fontWeight: 600, color: '#1a1a1a', marginTop: 2 }}>{name || 'Uden navn'}</div>
        </div>
        <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#888' }}>
          <IconX size={20} />
        </button>
      </div>

      <div style={{ padding: 24 }}>
        <Field label="Produktnavn" required>
          <TextInput value={name} onChange={e => setName(e.target.value)} placeholder="fx Argan-shampoo 250ml" autoFocus />
        </Field>
        <Field label="Brand / mærke">
          <TextInput value={brand} onChange={e => setBrand(e.target.value)} placeholder="fx Kérastase" />
        </Field>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Field label="Pris (kr)" required>
            <TextInput type="number" value={price} onChange={e => setPrice(e.target.value)} placeholder="0" />
          </Field>
          <Field label="På lager (stk)">
            <TextInput type="number" value={stock} onChange={e => setStock(e.target.value)} placeholder="Lad være tom hvis ikke styret" />
          </Field>
        </div>
        <Field label="Noter">
          <textarea value={notes} onChange={e => setNotes(e.target.value)} rows={3}
            placeholder="Fx hårtype, ingredienser eller særlige anbefalinger"
            style={{ ...inputStyle, width: '100%', resize: 'vertical', minHeight: 70, fontFamily: 'inherit' }}
          />
        </Field>
      </div>

      <div style={{ padding: '14px 24px', borderTop: '1px solid #EFEDE5', display: 'flex', justifyContent: 'space-between', background: '#FBFAF6' }}>
        <div>
          {!isNew && (
            <button onClick={() => onDelete(product)} style={{
              background: 'transparent', color: '#A03838', border: 'none',
              padding: '8px 12px', fontSize: 13, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit',
            }}>Slet produkt</button>
          )}
        </div>
        <div style={{ display: 'flex', gap: 10 }}>
          <SecondaryBtn onClick={onClose}>Annullér</SecondaryBtn>
          <PrimaryBtn onClick={submit} disabled={!canSave}>{isNew ? 'Opret' : 'Gem ændringer'}</PrimaryBtn>
        </div>
      </div>
    </Backdrop>
  );
};

// ---------- Notifications dropdown ----------
const SAMPLE_NOTIFICATIONS = [
  { id: 'n1', kind: 'cancel',  title: 'Aflysning via SMS-link',  body: 'Sofie Bredahl har aflyst sin tid kl. 14:30 hos Caroline.', time: 'For 4 min siden', unread: true,  reason: 'Jeg er syg' },
  { id: 'n2', kind: 'booking', title: 'Ny online booking',       body: 'Mads Pedersen har booket Herreklip i morgen kl. 10:30 hos Jakob.', time: 'For 18 min siden', unread: true },
  { id: 'n3', kind: 'reschedule', title: 'Ombooking via link',    body: 'Anna Lützhøft flyttede sin tid fra fredag til lørdag 10:00.', time: 'For 1 time siden', unread: true },
  { id: 'n4', kind: 'booking', title: 'Ny online booking',       body: 'Lars Nielsen har booket Skægtrim på lørdag kl. 13:15.', time: 'I går 19:42', unread: false },
  { id: 'n5', kind: 'cancel',  title: 'No-show registreret',     body: 'Emma Holst mødte ikke op til sin tid kl. 11:00.', time: 'I går 11:30', unread: false },
];

const NOTIF_ICON = {
  booking:    { bg: '#F4F7F0', fg: '#3F5A30', label: '＋' },
  cancel:     { bg: '#FBEEEE', fg: '#A03838', label: '✕' },
  reschedule: { bg: '#FEF7E8', fg: '#8A6B1F', label: '↻' },
};

const NotificationsDropdown = ({ open, onClose, items, onMarkAllRead, onClearAll }) => {
  if (!open) return null;
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 80 }} />
      <div style={{
        position: 'fixed', left: 70, bottom: 80, width: 380,
        background: '#fff', borderRadius: 14, boxShadow: '0 18px 60px rgba(0,0,0,0.18)',
        border: '1px solid #EFEDE5', zIndex: 90, overflow: 'hidden',
        animation: 'slideUp 180ms',
      }}>
        <div style={{ padding: '14px 18px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', borderBottom: '1px solid #EFEDE5' }}>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600 }}>Notifikationer</div>
            <div style={{ fontSize: 11, color: '#888' }}>{items.filter(i => i.unread).length} nye</div>
          </div>
          <button onClick={onMarkAllRead} style={{ background: 'transparent', border: 'none', color: '#3F4A3A', fontSize: 12, fontWeight: 500, cursor: 'pointer', fontFamily: 'inherit' }}>Markér alle som læst</button>
        </div>
        <div style={{ maxHeight: 420, overflow: 'auto' }}>
          {items.length === 0 ? (
            <div style={{ padding: '40px 20px', textAlign: 'center', color: '#aaa', fontSize: 13 }}>
              Ingen notifikationer
            </div>
          ) : items.map(n => {
            const ic = NOTIF_ICON[n.kind] || NOTIF_ICON.booking;
            return (
              <div key={n.id} style={{
                display: 'flex', gap: 12, padding: '12px 18px',
                borderBottom: '1px solid #F4F2EA',
                background: n.unread ? '#FBFAF6' : '#fff',
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 8, flexShrink: 0,
                  background: ic.bg, color: ic.fg,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 16, fontWeight: 700,
                }}>{ic.label}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
                    <div style={{ fontSize: 13, fontWeight: 600, color: '#1a1a1a' }}>{n.title}</div>
                    {n.unread && <div style={{ width: 6, height: 6, borderRadius: 6, background: '#D4654E', flexShrink: 0 }} />}
                  </div>
                  <div style={{ fontSize: 12, color: '#555', marginTop: 2, lineHeight: 1.4 }}>{n.body}</div>
                  {n.reason && (
                    <div style={{ marginTop: 4, fontSize: 11, color: '#A03838', background: '#FBEEEE', padding: '2px 8px', borderRadius: 4, display: 'inline-block' }}>
                      Årsag: {n.reason}
                    </div>
                  )}
                  <div style={{ fontSize: 11, color: '#999', marginTop: 4 }}>{n.time}</div>
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ padding: '10px 18px', borderTop: '1px solid #EFEDE5', display: 'flex', justifyContent: 'space-between', background: '#FBFAF6' }}>
          <button style={{ background: 'transparent', border: 'none', fontSize: 12, color: '#666', cursor: 'pointer', fontFamily: 'inherit' }} onClick={onClearAll}>Ryd alle</button>
          <span style={{ fontSize: 11, color: '#aaa' }}>Notifikationer fra online-bookinger og link-aflysninger</span>
        </div>
      </div>
    </>
  );
};

// ---------- Settings panel ----------
const SettingsPanel = ({ open, onClose, settings, onChange }) => {
  if (!open) return null;
  const set = (k, v) => onChange({ ...settings, [k]: v });
  return (
    <>
      <div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(20,18,14,0.45)', zIndex: 80, animation: 'fadeIn 160ms' }} />
      <div style={{
        position: 'fixed', left: 64, top: 0, bottom: 0, width: 440,
        background: '#fff', borderRight: '1px solid #EFEDE5', zIndex: 90,
        display: 'flex', flexDirection: 'column',
        boxShadow: '4px 0 24px rgba(0,0,0,0.08)',
        animation: 'fadeIn 200ms',
      }}>
        <div style={{ padding: '20px 24px', borderBottom: '1px solid #EFEDE5', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <h2 style={{ fontFamily: 'Fraunces, serif', fontSize: 24, fontWeight: 500, margin: 0 }}>Indstillinger</h2>
            <div style={{ fontSize: 12, color: '#888', marginTop: 2 }}>
              {(window.__SALONIQ_SALON__?.name) || settings.salonName || 'Salon'}
              {window.__SALONIQ_USER__?.username && ` · logget ind som ${window.__SALONIQ_USER__.username}`}
            </div>
          </div>
          <button onClick={onClose} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#888' }}>
            <IconX size={20} />
          </button>
        </div>

        <div style={{ flex: 1, overflow: 'auto', padding: '20px 24px' }}>
          <SettingsSection title="Salon-info">
            <SettingsRow label="Salonnavn">
              <TextInput value={settings.salonName} onChange={e => set('salonName', e.target.value)} />
            </SettingsRow>
            <SettingsRow label="Adresse">
              <TextInput value={settings.address} onChange={e => set('address', e.target.value)} />
            </SettingsRow>
            <SettingsRow label="Telefon">
              <TextInput value={settings.salonPhone} onChange={e => set('salonPhone', e.target.value)} />
            </SettingsRow>
          </SettingsSection>

          <SettingsSection title="Åbningstider">
            {['Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag','Søndag'].map(d => (
              <div key={d} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '6px 0' }}>
                <span style={{ width: 90, fontSize: 13, color: '#4a4a44' }}>{d}</span>
                <input type="checkbox" checked={settings.openDays?.[d] ?? true} onChange={e => set('openDays', { ...settings.openDays, [d]: e.target.checked })} />
                <input type="text" defaultValue={d === 'Lørdag' ? '9–14' : (d === 'Søndag' ? 'Lukket' : '9–18')} style={{ flex: 1, padding: '6px 10px', border: '1px solid #DDD9CE', borderRadius: 6, fontSize: 13, fontFamily: 'inherit', background: '#FBFAF6' }} />
              </div>
            ))}
          </SettingsSection>

          <SettingsSection title="Bekræftelser & påmindelser">
            <SettingsToggle label="Send SMS-bekræftelse ved booking" checked={settings.smsConfirm} onChange={v => set('smsConfirm', v)} />
            <SettingsToggle label="Send email-bekræftelse ved booking" checked={settings.emailConfirm} onChange={v => set('emailConfirm', v)} />
            <SettingsToggle label="Påmindelse 24 timer før" checked={settings.reminder24} onChange={v => set('reminder24', v)} />
            <SettingsToggle label="Påmindelse 2 timer før" checked={settings.reminder2} onChange={v => set('reminder2', v)} />
            <SettingsRow label="Aflysningsfrist (timer før)">
              <select value={settings.cancelWindow} onChange={e => set('cancelWindow', parseInt(e.target.value))} style={{ ...inputStyle, width: '100%' }}>
                <option value={6}>6 timer</option>
                <option value={12}>12 timer</option>
                <option value={24}>24 timer</option>
                <option value={48}>48 timer</option>
              </select>
            </SettingsRow>
          </SettingsSection>

          <SettingsSection title="Sikkerhed">
            <SettingsRow label="PIN-kode">
              <TextInput type="password" value={settings.adminPin} onChange={e => set('adminPin', e.target.value)} />
            </SettingsRow>
            <SettingsRow label="Standard timeout efter PIN">
              <select value={settings.defaultPinTimeout} onChange={e => set('defaultPinTimeout', parseInt(e.target.value))} style={{ ...inputStyle, width: '100%' }}>
                <option value={60_000}>1 minut</option>
                <option value={5*60_000}>5 minutter</option>
                <option value={15*60_000}>15 minutter</option>
                <option value={60*60_000}>1 time</option>
                <option value={0}>Indtil fanen lukkes</option>
              </select>
            </SettingsRow>
            <SettingsToggle label="Kræv PIN for at slette bookinger" checked={settings.pinForDelete} onChange={v => set('pinForDelete', v)} />
            <SettingsToggle label="Kræv PIN for kassesystem" checked={settings.pinForPos} onChange={v => set('pinForPos', v)} />
          </SettingsSection>

          <SettingsSection title="Visning">
            <SettingsToggle label="Vis ugenumre i kalender" checked={settings.showWeekNumber} onChange={v => set('showWeekNumber', v)} />
            <SettingsToggle label="15-minutters interval (ellers 30)" checked={settings.fineGrid} onChange={v => set('fineGrid', v)} />
          </SettingsSection>
        </div>

        <div style={{ padding: '14px 24px', borderTop: '1px solid #EFEDE5', display: 'flex', justifyContent: 'space-between', background: '#FBFAF6' }}>
          <button onClick={() => {
            onClose();
            window.dispatchEvent(new Event('saloniq-logout'));
          }} style={{ background: 'transparent', border: 'none', color: '#A03838', fontSize: 13, cursor: 'pointer', fontFamily: 'inherit', fontWeight: 500 }}>Log ud</button>
          <PrimaryBtn onClick={onClose}>Færdig</PrimaryBtn>
        </div>
      </div>
    </>
  );
};

const SettingsSection = ({ title, children }) => (
  <div style={{ marginBottom: 24 }}>
    <div style={{ fontSize: 11, color: '#888', fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 10, paddingBottom: 6, borderBottom: '1px solid #F4F2EA' }}>{title}</div>
    {children}
  </div>
);
const SettingsRow = ({ label, children }) => (
  <div style={{ marginBottom: 10 }}>
    <div style={{ fontSize: 12, color: '#4a4a44', fontWeight: 500, marginBottom: 4 }}>{label}</div>
    {children}
  </div>
);
const SettingsToggle = ({ label, checked, onChange }) => (
  <label style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '10px 0', cursor: 'pointer', borderBottom: '1px solid #F4F2EA' }}>
    <span style={{ fontSize: 13, color: '#1a1a1a' }}>{label}</span>
    <span style={{
      width: 36, height: 20, borderRadius: 10,
      background: checked ? '#3F4A3A' : '#DDD9CE',
      position: 'relative', transition: 'all 160ms',
    }} onClick={() => onChange(!checked)}>
      <span style={{
        position: 'absolute', top: 2, left: checked ? 18 : 2,
        width: 16, height: 16, borderRadius: '50%', background: '#fff',
        transition: 'all 160ms',
      }} />
    </span>
  </label>
);

Object.assign(window, {
  PinTimeoutModal, PIN_TIMEOUTS, PinSetupModal,
  StaffEditorModal, TONE_PALETTE,
  ProductEditorModal,
  NotificationsDropdown, SAMPLE_NOTIFICATIONS,
  SettingsPanel,
});
