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

// ---------- 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'];

const StaffEditorModal = ({ staff, onClose, onSave, onDelete }) => {
  if (!staff) return null;
  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@klipperiet.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>
  );
};

// ---------- 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 }}>Klipperiet Østerbro</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 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,
  StaffEditorModal, TONE_PALETTE,
  NotificationsDropdown, SAMPLE_NOTIFICATIONS,
  SettingsPanel,
});
