// Top bar: department + staff filter, date nav, new booking button

const TopBar = ({ department, onDeptChange, departments = [], staffFilter, onStaffFilterChange, date, onDateChange, onNewBooking, search, onSearchChange, allStaff }) => {
  const fmt = new Intl.DateTimeFormat('da-DK', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
  const dateLabel = fmt.format(date).replace(/^./, c => c.toUpperCase());
  const [deptMenuOpen, setDeptMenuOpen] = React.useState(false);
  const deptRef = React.useRef(null);
  React.useEffect(() => {
    if (!deptMenuOpen) return;
    const onDoc = (e) => { if (deptRef.current && !deptRef.current.contains(e.target)) setDeptMenuOpen(false); };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [deptMenuOpen]);

  const isToday = (d) => {
    const t = new Date();
    return d.getFullYear() === t.getFullYear() && d.getMonth() === t.getMonth() && d.getDate() === t.getDate();
  };

  const shiftDay = (n) => {
    const d = new Date(date);
    d.setDate(d.getDate() + n);
    onDateChange(d);
  };

  return (
    <div style={{
      height: 56, flexShrink: 0,
      borderBottom: '1px solid #EAEAE3',
      background: '#fff',
      display: 'flex', alignItems: 'center',
      padding: '0 16px', gap: 12,
    }}>
      {/* Left: filters */}
      <div ref={deptRef} style={{ position: 'relative' }}>
        <FilterPill
          label="Afdeling"
          value={department?.name || 'Ingen afdeling'}
          onClick={departments.length > 1 ? () => setDeptMenuOpen(o => !o) : undefined}
        />
        {deptMenuOpen && (
          <div style={{
            position: 'absolute', top: '100%', left: 0, marginTop: 4, zIndex: 50,
            background: '#fff', border: '1px solid #DDD9CE', borderRadius: 8,
            boxShadow: '0 8px 24px rgba(0,0,0,0.12)', minWidth: 220, padding: 4,
          }}>
            {departments.map(d => (
              <button key={d.id} onClick={() => { onDeptChange(d); setDeptMenuOpen(false); }} style={{
                display: 'flex', alignItems: 'center', gap: 8, width: '100%',
                padding: '9px 12px', textAlign: 'left',
                background: department?.id === d.id ? '#F4F2EA' : 'transparent',
                border: 'none', borderRadius: 6, cursor: 'pointer',
                fontFamily: 'inherit', fontSize: 13,
              }}
              onMouseEnter={e => { if (department?.id !== d.id) e.currentTarget.style.background = '#FBFAF6'; }}
              onMouseLeave={e => { if (department?.id !== d.id) e.currentTarget.style.background = 'transparent'; }}>
                <span style={{ flex: 1, fontWeight: department?.id === d.id ? 600 : 400 }}>{d.name}</span>
                {d.isDefault && (
                  <span style={{
                    fontSize: 9, fontWeight: 700, color: '#3F5A30',
                    background: '#F4F7F0', border: '1px solid #DCE6CC',
                    padding: '1px 5px', borderRadius: 8, letterSpacing: '0.04em',
                  }}>HOVED</span>
                )}
                {department?.id === d.id && <IconCheck size={13} stroke="#3F4A3A" />}
              </button>
            ))}
          </div>
        )}
      </div>
      <FilterPill label="Medarbejder" value={staffFilter === 'all' ? 'Alle medarbejdere' : allStaff.find(s => s.id === staffFilter)?.name || 'Alle'}
                   onClick={allStaff.length > 0 ? () => onStaffFilterChange(staffFilter === 'all' ? allStaff[0].id : 'all') : undefined} />

      {/* Center: date nav */}
      <div style={{ flex: 1, display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 8 }}>
        <button onClick={() => shiftDay(-1)} title="Forrige dag" style={navBtnStyle}><IconChevL size={18} /></button>

        {/* Date label is also a click-target that opens the native date picker
            via a hidden input — works on desktop and mobile alike. */}
        <label style={{
          background: '#FBFAF6', border: '1px solid #EAEAE3', borderRadius: 8,
          padding: '7px 16px', fontSize: 13, fontWeight: 500, cursor: 'pointer',
          display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'inherit',
          minWidth: 220, justifyContent: 'center', position: 'relative',
        }} title="Klik for at vælge en bestemt dato">
          <IconCalendar size={14} stroke="#666" />
          {dateLabel}
          <input type="date"
            value={`${date.getFullYear()}-${String(date.getMonth()+1).padStart(2,'0')}-${String(date.getDate()).padStart(2,'0')}`}
            onChange={e => {
              if (!e.target.value) return;
              const [y, m, d] = e.target.value.split('-').map(Number);
              onDateChange(new Date(y, m - 1, d));
            }}
            style={{ position: 'absolute', inset: 0, opacity: 0, cursor: 'pointer' }}
          />
        </label>

        <button onClick={() => shiftDay(1)} title="Næste dag" style={navBtnStyle}><IconChevR size={18} /></button>

        {/* "I dag" only when not on today */}
        {!isToday(date) && (
          <button onClick={() => onDateChange(new Date())} title="Hop til i dag" style={{
            ...navBtnStyle, padding: '7px 14px', fontSize: 12, fontWeight: 600,
            color: '#3F4A3A', width: 'auto',
          }}>I dag</button>
        )}
      </div>

      {/* Right: search + new booking */}
      <div style={{ position: 'relative' }}>
        <div style={{ position: 'absolute', left: 10, top: 9, color: '#999' }}><IconSearch size={14} /></div>
        <input value={search} onChange={e => onSearchChange(e.target.value)} placeholder="Søg kunde…"
          style={{ ...inputStyle, paddingLeft: 32, padding: '7px 10px 7px 32px', width: 180, fontSize: 13, background: '#FBFAF6' }} />
      </div>
      <button style={navBtnStyle}><IconEye size={16} /></button>
      <PrimaryBtn onClick={() => onNewBooking()}>
        <IconPlus size={14} style={{ marginRight: 6, verticalAlign: 'middle' }} />
        Ny booking
      </PrimaryBtn>
    </div>
  );
};

const navBtnStyle = {
  background: '#FBFAF6', border: '1px solid #EAEAE3', borderRadius: 8,
  width: 34, height: 34, cursor: 'pointer',
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  color: '#555', fontFamily: 'inherit',
};

const FilterPill = ({ label, value, onClick }) => (
  <button onClick={onClick} style={{
    background: '#FBFAF6', border: '1px solid #EAEAE3', borderRadius: 8,
    padding: '7px 12px', cursor: onClick ? 'pointer' : 'default',
    display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'inherit', fontSize: 13,
  }}>
    <span style={{ color: '#888' }}>{label}:</span>
    <span style={{ fontWeight: 500, color: '#1a1a1a' }}>{value}</span>
    <IconChevD size={12} stroke="#888" />
  </button>
);

Object.assign(window, { TopBar });
