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

const TopBar = ({ department, onDeptChange, departments = [], staffFilter, onStaffFilterChange, date, onDateChange, onNewBooking, search, onSearchChange, allStaff, openDays, bookingDates }) => {
  // Weekday + dd/mm/yyyy — fx 'Mandag 11/05/2026'.
  const weekdayName = (window.DAY_NAMES || ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'])[date.getDay()];
  const dateLabel = `${weekdayName} ${formatDanishShortDate(date)}`;
  const [deptMenuOpen, setDeptMenuOpen] = React.useState(false);
  const [staffMenuOpen, setStaffMenuOpen] = React.useState(false);
  const [dateMenuOpen, setDateMenuOpen] = React.useState(false);
  const deptRef = React.useRef(null);
  const staffRef = React.useRef(null);
  const dateRef = React.useRef(null);
  React.useEffect(() => {
    if (!deptMenuOpen && !staffMenuOpen && !dateMenuOpen) return;
    const onDoc = (e) => {
      if (deptMenuOpen && deptRef.current && !deptRef.current.contains(e.target)) setDeptMenuOpen(false);
      if (staffMenuOpen && staffRef.current && !staffRef.current.contains(e.target)) setStaffMenuOpen(false);
      if (dateMenuOpen && dateRef.current && !dateRef.current.contains(e.target)) setDateMenuOpen(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [deptMenuOpen, staffMenuOpen, dateMenuOpen]);

  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>
      <div ref={staffRef} style={{ position: 'relative' }}>
        <FilterPill
          label="Medarbejder"
          value={staffFilter === 'all' ? 'Alle medarbejdere' : allStaff.find(s => s.id === staffFilter)?.name || 'Alle'}
          onClick={() => setStaffMenuOpen(o => !o)}
        />
        {staffMenuOpen && (
          <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,
            maxHeight: 360, overflow: 'auto',
          }}>
            <button onClick={() => { onStaffFilterChange('all'); setStaffMenuOpen(false); }} style={{
              display: 'flex', alignItems: 'center', gap: 8, width: '100%',
              padding: '9px 12px', textAlign: 'left',
              background: staffFilter === 'all' ? '#F4F2EA' : 'transparent',
              border: 'none', borderRadius: 6, cursor: 'pointer',
              fontFamily: 'inherit', fontSize: 13,
              fontWeight: staffFilter === 'all' ? 600 : 400,
            }}
            onMouseEnter={e => { if (staffFilter !== 'all') e.currentTarget.style.background = '#FBFAF6'; }}
            onMouseLeave={e => { if (staffFilter !== 'all') e.currentTarget.style.background = 'transparent'; }}>
              <span style={{ flex: 1 }}>Alle medarbejdere</span>
              {staffFilter === 'all' && <IconCheck size={13} stroke="#3F4A3A" />}
            </button>
            {allStaff.length > 0 && <div style={{ height: 1, background: '#EFEDE5', margin: '4px 0' }} />}
            {allStaff.map(s => (
              <button key={s.id} onClick={() => { onStaffFilterChange(s.id); setStaffMenuOpen(false); }} style={{
                display: 'flex', alignItems: 'center', gap: 8, width: '100%',
                padding: '9px 12px', textAlign: 'left',
                background: staffFilter === s.id ? '#F4F2EA' : 'transparent',
                border: 'none', borderRadius: 6, cursor: 'pointer',
                fontFamily: 'inherit', fontSize: 13,
              }}
              onMouseEnter={e => { if (staffFilter !== s.id) e.currentTarget.style.background = '#FBFAF6'; }}
              onMouseLeave={e => { if (staffFilter !== s.id) e.currentTarget.style.background = 'transparent'; }}>
                <span style={{ flex: 1, fontWeight: staffFilter === s.id ? 600 : 400 }}>{s.name}</span>
                {staffFilter === s.id && <IconCheck size={13} stroke="#3F4A3A" />}
              </button>
            ))}
            {allStaff.length === 0 && (
              <div style={{ padding: '12px', textAlign: 'center', fontSize: 12, color: '#aaa' }}>
                Ingen medarbejdere endnu
              </div>
            )}
          </div>
        )}
      </div>

      {/* 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>

        <div ref={dateRef} style={{ position: 'relative' }}>
          <button onClick={() => setDateMenuOpen(o => !o)} 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', color: '#1a1a1a',
          }} title="Klik for at vælge en bestemt dato">
            <IconCalendar size={14} stroke="#666" />
            {dateLabel}
          </button>
          {dateMenuOpen && (
            <MiniCalendarPopover
              date={date}
              onPick={(d) => { onDateChange(d); setDateMenuOpen(false); }}
              onToday={() => { onDateChange(new Date()); setDateMenuOpen(false); }}
              openDays={openDays}
              bookingDates={bookingDates}
            />
          )}
        </div>

        <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>
);

// ISO-8601 week number — Monday is the first day of the week.
function isoWeekNumber(date) {
  const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
  const dayNum = (d.getUTCDay() + 6) % 7; // Mon=0..Sun=6
  d.setUTCDate(d.getUTCDate() - dayNum + 3);
  const firstThursday = new Date(Date.UTC(d.getUTCFullYear(), 0, 4));
  const firstThursdayDayNum = (firstThursday.getUTCDay() + 6) % 7;
  firstThursday.setUTCDate(firstThursday.getUTCDate() - firstThursdayDayNum + 3);
  return 1 + Math.round((d - firstThursday) / (7 * 86400000));
}

// Same mapping as DAY_NAMES in data.jsx — JS Date.getDay() 0..6 (søndag..lørdag)
// → Danske ugedags-navne der bruges som nøgler i appSettings.openDays.
const MINI_CAL_DAY_NAMES = ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'];

const MiniCalendarPopover = ({ date, onPick, onToday, openDays, bookingDates }) => {
  const [viewMonth, setViewMonth] = React.useState(new Date(date.getFullYear(), date.getMonth(), 1));
  const monthLabel = viewMonth.toLocaleDateString('da-DK', { month: 'long', year: 'numeric' });
  const monthCap = monthLabel.charAt(0).toUpperCase() + monthLabel.slice(1);

  // Resolve booking-dates as a Set for O(1) lookup. bookingDates may be a Set,
  // an Array of YYYY-MM-DD strings, or undefined.
  const bookingDateSet = React.useMemo(() => {
    if (!bookingDates) return new Set();
    if (bookingDates instanceof Set) return bookingDates;
    return new Set(bookingDates);
  }, [bookingDates]);

  // Build weeks: each row starts on a Monday. Pad with previous/next month days so the grid is rectangular.
  const firstOfMonth = new Date(viewMonth.getFullYear(), viewMonth.getMonth(), 1);
  const startDayNum = (firstOfMonth.getDay() + 6) % 7; // Mon=0..Sun=6
  const gridStart = new Date(firstOfMonth);
  gridStart.setDate(gridStart.getDate() - startDayNum);

  const weeks = [];
  for (let w = 0; w < 6; w++) {
    const days = [];
    for (let d = 0; d < 7; d++) {
      const cellDate = new Date(gridStart);
      cellDate.setDate(gridStart.getDate() + w * 7 + d);
      days.push(cellDate);
    }
    weeks.push({ days, weekNum: isoWeekNumber(days[0]) });
  }

  const today = new Date();
  const isSameDay = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();

  const shiftMonth = (n) => {
    setViewMonth(new Date(viewMonth.getFullYear(), viewMonth.getMonth() + n, 1));
  };

  const cellSize = 32;

  return (
    <div style={{
      position: 'absolute', top: '100%', left: '50%', transform: 'translateX(-50%)',
      marginTop: 6, zIndex: 50, background: '#fff', border: '1px solid #DDD9CE',
      borderRadius: 10, boxShadow: '0 12px 32px rgba(0,0,0,0.15)',
      padding: 14, width: 320, fontFamily: 'inherit',
    }}>
      {/* Month header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <button onClick={() => shiftMonth(-1)} style={miniNavBtn} title="Forrige måned">
          <IconChevL size={14} />
        </button>
        <div style={{ fontFamily: 'Fraunces, serif', fontSize: 16, fontWeight: 500 }}>{monthCap}</div>
        <button onClick={() => shiftMonth(1)} style={miniNavBtn} title="Næste måned">
          <IconChevR size={14} />
        </button>
      </div>

      {/* Header row: empty + weekdays */}
      <div style={{ display: 'grid', gridTemplateColumns: `28px repeat(7, ${cellSize}px)`, gap: 2, marginBottom: 4 }}>
        <div style={{ fontSize: 9, color: '#aaa', fontWeight: 700, textAlign: 'center', letterSpacing: '0.04em' }}>UGE</div>
        {['M','T','O','T','F','L','S'].map((d, i) => (
          <div key={i} style={{ fontSize: 11, color: '#888', fontWeight: 600, textAlign: 'center' }}>{d}</div>
        ))}
      </div>

      {/* Weeks */}
      {weeks.map((w, wi) => (
        <div key={wi} style={{ display: 'grid', gridTemplateColumns: `28px repeat(7, ${cellSize}px)`, gap: 2, marginBottom: 2 }}>
          <div style={{
            fontSize: 10, color: '#A36F2E', fontWeight: 700, textAlign: 'center',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            background: '#FBF5E8', borderRadius: 5,
          }}>{w.weekNum}</div>
          {w.days.map((d, di) => {
            const inMonth = d.getMonth() === viewMonth.getMonth();
            const isToday = isSameDay(d, today);
            const isSelected = isSameDay(d, date);
            const dayName = MINI_CAL_DAY_NAMES[d.getDay()];
            const isClosed = openDays ? openDays[dayName] === false : (dayName === 'Søndag');
            const isoDate = `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
            const hasBookings = bookingDateSet.has(isoDate);

            // Defaultbaggrund — lukkedage nedtones med striber, åbne dage er transparente.
            const closedBg = 'repeating-linear-gradient(45deg, #F4F2EA, #F4F2EA 4px, #ECE9DD 4px, #ECE9DD 8px)';
            let bg;
            if (isSelected) bg = '#3F4A3A';
            else if (isToday) bg = '#F4F7F0';
            else if (isClosed && inMonth) bg = closedBg;
            else bg = 'transparent';

            // Tekstfarve — lukkedage og dage fra anden måned er mere bleg.
            let color;
            if (isSelected) color = '#fff';
            else if (!inMonth) color = '#ccc';
            else if (isClosed) color = '#aaa';
            else color = '#1a1a1a';

            return (
              <button key={di} onClick={() => onPick(new Date(d.getFullYear(), d.getMonth(), d.getDate()))}
                title={isClosed && inMonth ? `${dayName} — lukket` : undefined}
                style={{
                  width: cellSize, height: cellSize, borderRadius: 5,
                  background: bg, color,
                  border: isToday && !isSelected ? '1px solid #C9D8B5' : 'none',
                  cursor: 'pointer', fontSize: 13, fontFamily: 'inherit',
                  fontWeight: isSelected || isToday ? 600 : 400,
                  padding: 0, position: 'relative',
                }}
                onMouseEnter={e => {
                  if (!isSelected) e.currentTarget.style.background = isClosed && inMonth ? '#E5E2D5' : '#F4F2EA';
                }}
                onMouseLeave={e => {
                  if (isSelected) return;
                  if (isToday) e.currentTarget.style.background = '#F4F7F0';
                  else if (isClosed && inMonth) e.currentTarget.style.background = closedBg;
                  else e.currentTarget.style.background = 'transparent';
                }}>
                {d.getDate()}
                {hasBookings && inMonth && (
                  <span style={{
                    position: 'absolute', bottom: 3, left: '50%', transform: 'translateX(-50%)',
                    width: 5, height: 5, borderRadius: '50%',
                    background: isSelected ? '#fff' : '#3F5A30',
                  }} />
                )}
              </button>
            );
          })}
        </div>
      ))}

      {/* Legend */}
      <div style={{
        marginTop: 10, paddingTop: 10, borderTop: '1px solid #EFEDE5',
        display: 'flex', gap: 14, alignItems: 'center', fontSize: 10, color: '#888',
      }}>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
          <span style={{
            width: 12, height: 12, borderRadius: 3,
            background: 'repeating-linear-gradient(45deg, #F4F2EA, #F4F2EA 3px, #ECE9DD 3px, #ECE9DD 6px)',
          }} />
          Lukket
        </span>
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#3F5A30' }} />
          Bookinger
        </span>
      </div>

      {/* Today shortcut */}
      <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid #EFEDE5', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <span style={{ fontSize: 11, color: '#888' }}>
          Uge {isoWeekNumber(today)} · {formatDanishShortDate(today)}
        </span>
        <button onClick={onToday} style={{
          background: '#3F4A3A', color: '#fff', border: 'none', borderRadius: 6,
          padding: '6px 14px', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
        }}>I dag</button>
      </div>
    </div>
  );
};

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

Object.assign(window, { TopBar });
