// Mock data for Saloniq booking system
// services have: duration (active minutes), pauseAfter (gap/mellemrum minutes — medarbejderen er fri og kan tage en anden kunde)
const SERVICES = [
  { id: 'herreklip',    name: 'Herreklip',      duration: 30, pauseAfter: 0,  price: 350, color: 'red' },
  { id: 'dameklip',     name: 'Dameklip',       duration: 60, pauseAfter: 0,  price: 525, color: 'green' },
  { id: 'helfarve',     name: 'Helfarve',       duration: 45, pauseAfter: 60, price: 695, color: 'purple' },
  { id: 'striber',      name: 'Striber/folie',  duration: 60, pauseAfter: 45, price: 850, color: 'pink' },
  { id: 'boerneklip',   name: 'Børneklip',      duration: 30, pauseAfter: 0,  price: 250, color: 'blue' },
  { id: 'pensionist',   name: 'Pensionistklip', duration: 30, pauseAfter: 0,  price: 295, color: 'yellow' },
  { id: 'behandling',   name: 'Behandling/kur', duration: 30, pauseAfter: 15, price: 395, color: 'purple' },
  { id: 'permanent',    name: 'Permanent',      duration: 60, pauseAfter: 30, price: 895, color: 'pink' },
  { id: 'haarvask',     name: 'Hårvask',        duration: 15, pauseAfter: 0,  price: 95,  color: 'blue' },
];

let SERVICE_BY_ID = Object.fromEntries(SERVICES.map(s => [s.id, s]));
const refreshServiceById = () => {
  for (const k in SERVICE_BY_ID) delete SERVICE_BY_ID[k];
  for (const s of SERVICES) SERVICE_BY_ID[s.id] = s;
};

// Convert a color value (named like 'red' OR hex like '#FF6B6B') to a palette
// object { bg, border, text } that matches what SERVICE_COLORS provides for
// named colors. For hex inputs we derive bg via low-alpha overlay on white,
// border = the hex itself, text = a darkened version of the hex.
function paletteFromHex(hex) {
  const m = String(hex || '').match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
  if (!m) return { bg: '#F4F2EA', border: '#888', text: '#1a1a1a' };
  const r = parseInt(m[1], 16);
  const g = parseInt(m[2], 16);
  const b = parseInt(m[3], 16);
  // Mix with white at 82% to get a soft pastel-ish bg
  const mix = (c) => Math.round(c + (255 - c) * 0.78);
  const dark = (c) => Math.round(c * 0.4);
  return {
    bg:     `rgb(${mix(r)}, ${mix(g)}, ${mix(b)})`,
    border: '#' + m[1] + m[2] + m[3],
    text:   `rgb(${dark(r)}, ${dark(g)}, ${dark(b)})`,
  };
}

// Unified service-palette resolver — works for both named ('green') and hex
// ('#3F4A3A') colors. All calendar/booking views go through this.
function getServicePalette(color, palette) {
  const p = palette || 'pastel';
  if (typeof color === 'string' && color.startsWith('#')) {
    return paletteFromHex(color);
  }
  return SERVICE_COLORS[p]?.[color] || SERVICE_COLORS[p]?.green || { bg: '#F4F2EA', border: '#888', text: '#1a1a1a' };
}

// Pastel palette — rolig stil ligesom screenshottet
const SERVICE_COLORS = {
  pastel: {
    red:    { bg: '#FAD4D4', border: '#E68A8A', text: '#7A2E2E' },
    green:  { bg: '#D4E9D4', border: '#86B886', text: '#2F5E2F' },
    blue:   { bg: '#D4E4F2', border: '#7FAAD2', text: '#2A4A6E' },
    yellow: { bg: '#F8EFC8', border: '#D9C26B', text: '#6A5320' },
    purple: { bg: '#E0D4ED', border: '#A48DC8', text: '#43306C' },
    pink:   { bg: '#F2D4E2', border: '#D08AAA', text: '#6E2A4A' },
  },
  vivid: {
    red:    { bg: '#FFB3B3', border: '#E14F4F', text: '#5A0E0E' },
    green:  { bg: '#B5E3B5', border: '#4FA84F', text: '#1A4A1A' },
    blue:   { bg: '#A8D0EE', border: '#3D7DB8', text: '#0F2E4F' },
    yellow: { bg: '#F5E396', border: '#C9A828', text: '#4A3800' },
    purple: { bg: '#CFB8E8', border: '#7E5BB3', text: '#2D1A50' },
    pink:   { bg: '#F2B8D2', border: '#C25D89', text: '#511A36' },
  },
  muted: {
    red:    { bg: '#EFDADA', border: '#B89494', text: '#6A4040' },
    green:  { bg: '#DCE6DC', border: '#94B094', text: '#465F46' },
    blue:   { bg: '#DCE4EC', border: '#94A8BC', text: '#3A4D63' },
    yellow: { bg: '#EEE7CE', border: '#BBA875', text: '#5D4F2C' },
    purple: { bg: '#E0D9E8', border: '#A095B0', text: '#473F58' },
    pink:   { bg: '#EBD7E0', border: '#B591A1', text: '#5C3A4A' },
  },
};

const STAFF = [
  { id: 's1', name: 'Caroline Hansen', initials: 'CH', tone: '#E8C8B4', role: 'Senior frisør',  departmentId: 'osterbro',  specialties: ['Dameklip', 'Helfarve', 'Behandling'], phone: '+45 50 92 02 01', email: 'caroline@ooniq.dk', schedule: { man: '9-17', tir: '9-17', ons: 'Fri',   tor: '9-17', fre: '9-15', lor: '10-14' }, color: '#A56B4A' },
  { id: 's2', name: 'Jakob Carlsen',   initials: 'JC', tone: '#B4D2E8', role: 'Frisør',         departmentId: 'vesterbro', specialties: ['Herreklip', 'Skægtrim'],              phone: '+45 50 92 02 01', email: 'jakob@ooniq.dk',    schedule: { man: '10-18', tir: '10-18', ons: '10-18', tor: '10-18', fre: '10-16', lor: 'Fri' }, color: '#3D7DB8' },
  { id: 's3', name: 'Katrine Jensen',  initials: 'KJ', tone: '#D8C0E0', role: 'Senior frisør',  departmentId: 'norrebro',  specialties: ['Dameklip', 'Striber', 'Permanent'],   phone: '+45 50 92 02 01', email: 'katrine@ooniq.dk',  schedule: { man: 'Fri', tir: '9-17', ons: '9-17', tor: '11-19', fre: '9-15', lor: '10-14' }, color: '#7E5BB3' },
  { id: 's4', name: 'Christian Holm',  initials: 'CH', tone: '#C8DCB4', role: 'Frisør',         departmentId: 'osterbro',  specialties: ['Herreklip', 'Børneklip'],              phone: '+45 50 92 02 01', email: 'christian@ooniq.dk', schedule: { man: '9-17', tir: 'Fri', ons: '9-17', tor: '9-17', fre: '9-17', lor: 'Fri' }, color: '#4FA84F' },
  { id: 's5', name: 'Mette Lund',      initials: 'ML', tone: '#F0CFC0', role: 'Junior frisør',  departmentId: 'vesterbro', specialties: ['Dameklip', 'Børneklip', 'Hårvask'],   phone: '+45 50 92 02 01', email: 'mette@ooniq.dk',    schedule: { man: '11-19', tir: '11-19', ons: '11-19', tor: '11-19', fre: 'Fri', lor: '10-14' }, color: '#D08AAA' },
];

const DEPARTMENTS = [
  { id: 'osterbro', name: 'Østerbro' },
  { id: 'vesterbro', name: 'Vesterbro' },
  { id: 'norrebro', name: 'Nørrebro' },
];

// Customer database with history
const CUSTOMERS = [
  { id: 'c1',  name: 'Mathias Knudsen',  phone: '+45 50 92 02 01', email: 'mathias.k@ooniq.dk',     visits: 8,  lastService: 'herreklip',  favoriteStaffId: 's1', notes: 'Foretrækker fade i siderne. Allergisk over for parfumeret shampoo.' },
  { id: 'c2',  name: 'Laura Sørensen',   phone: '+45 50 92 02 01', email: 'laura.s@ooniq.dk',     visits: 14, lastService: 'dameklip',   favoriteStaffId: 's2', notes: 'Vil altid have helfarve, mørkebrun (6.0). Drikker kaffe med mælk.' },
  { id: 'c3',  name: 'Henrik Madsen',    phone: '+45 50 92 02 01', email: 'henrik.madsen@ooniq.dk',   visits: 22, lastService: 'herreklip',  favoriteStaffId: 's1', notes: '' },
  { id: 'c4',  name: 'Patrick Hansen',   phone: '+45 50 92 02 01', email: 'patrick.h@ooniq.dk',     visits: 5,  lastService: 'herreklip',  favoriteStaffId: 's2', notes: '' },
  { id: 'c5',  name: 'Thomas Juul',      phone: '+45 50 92 02 01', email: 'thomas.juul@ooniq.dk',     visits: 11, lastService: 'herreklip',  favoriteStaffId: 's3', notes: 'Møder ofte 5 min. for sent.' },
  { id: 'c6',  name: 'Kirsten Andersen', phone: '+45 50 92 02 01', email: 'kirsten.a@ooniq.dk',     visits: 33, lastService: 'behandling', favoriteStaffId: 's1', notes: 'Stamkunde siden 2015. Foretrækker olivenfarve.' },
  { id: 'c7',  name: 'Svend Karlsen',    phone: '+45 50 92 02 01', email: 'svend.k@ooniq.dk',     visits: 4,  lastService: 'pensionist', favoriteStaffId: 's2', notes: '' },
  { id: 'c8',  name: 'Cecilie Larsen',   phone: '+45 50 92 02 01', email: 'cecilie.l@ooniq.dk',       visits: 17, lastService: 'dameklip',   favoriteStaffId: 's3', notes: 'Bestiller altid hårvask + behandling.' },
  { id: 'c9',  name: 'Anders Thomsen',   phone: '+45 50 92 02 01', email: 'anders.t@ooniq.dk',      visits: 9,  lastService: 'herreklip',  favoriteStaffId: 's1', notes: '' },
  { id: 'c10', name: 'Hanne Alling',     phone: '+45 50 92 02 01', email: 'hanne.alling@ooniq.dk',    visits: 19, lastService: 'dameklip',   favoriteStaffId: 's2', notes: 'Klipper kort hver 6. uge.' },
  { id: 'c11', name: 'Line Malling',     phone: '+45 50 92 02 01', email: 'line.m@ooniq.dk',        visits: 6,  lastService: 'dameklip',   favoriteStaffId: 's3', notes: '' },
  { id: 'c12', name: 'Sofie Olsen',      phone: '+45 50 92 02 01', email: 'sofie.olsen@ooniq.dk', visits: 12, lastService: 'dameklip',   favoriteStaffId: 's1', notes: '' },
  { id: 'c13', name: 'Simone Larsen',    phone: '+45 50 92 02 01', email: 'simone.l@ooniq.dk',        visits: 8,  lastService: 'dameklip',   favoriteStaffId: 's3', notes: '' },
  { id: 'c14', name: 'Marie Knudsen',    phone: '+45 50 92 02 01', email: 'marie.k@ooniq.dk',       visits: 25, lastService: 'behandling', favoriteStaffId: 's4', notes: 'VIP. Får et glas vand uden is.' },
  { id: 'c15', name: 'Jesper Hansen',    phone: '+45 50 92 02 01', email: 'jesper.h@ooniq.dk',    visits: 7,  lastService: 'herreklip',  favoriteStaffId: 's4', notes: '' },
  { id: 'c16', name: 'Casper Lund',      phone: '+45 50 92 02 01', email: 'casper.lund@ooniq.dk',     visits: 3,  lastService: 'herreklip',  favoriteStaffId: 's4', notes: '' },
  { id: 'c17', name: 'Katrine Mogensen', phone: '+45 50 92 02 01', email: 'katrine.m@ooniq.dk',     visits: 16, lastService: 'dameklip',   favoriteStaffId: 's4', notes: '' },
];

// Initial bookings — Torsdag 6. juni 2024
// Each booking: { id, staffId, start, serviceIds: [...], customerId, note }
const INITIAL_BOOKINGS = [
  { id: 'b1',  staffId: 's1', start: 9*60,     serviceIds: ['herreklip'],            customerId: 'c1' },
  { id: 'b2',  staffId: 's1', start: 10*60+30, serviceIds: ['herreklip'],            customerId: 'c3' },
  { id: 'b3',  staffId: 's1', start: 11*60+30, serviceIds: ['behandling'],           customerId: 'c6' },
  { id: 'b4',  staffId: 's1', start: 13*60+45, serviceIds: ['herreklip'],            customerId: 'c9' },
  { id: 'b5',  staffId: 's1', start: 15*60,    serviceIds: ['dameklip'],             customerId: 'c12' },

  // Laura: dameklip + helfarve — combo med pause
  { id: 'b6',  staffId: 's2', start: 9*60,     serviceIds: ['helfarve','dameklip'],  customerId: 'c2' },
  { id: 'b7',  staffId: 's2', start: 12*60+15, serviceIds: ['herreklip'],            customerId: 'c4' },
  { id: 'b8',  staffId: 's2', start: 13*60,    serviceIds: ['herreklip'],            customerId: 'c7' },
  { id: 'b9',  staffId: 's2', start: 14*60,    serviceIds: ['dameklip'],             customerId: 'c10' },

  { id: 'b10', staffId: 's3', start: 11*60,    serviceIds: ['herreklip'],            customerId: 'c5' },
  { id: 'b11', staffId: 's3', start: 12*60+15, serviceIds: ['behandling'],           customerId: 'c8' },
  // Cecilie: striber + dameklip
  { id: 'b12', staffId: 's3', start: 14*60,    serviceIds: ['striber','dameklip'],   customerId: 'c11' },

  { id: 'b14', staffId: 's4', start: 9*60,     serviceIds: ['behandling'],           customerId: 'c14' },
  { id: 'b15', staffId: 's4', start: 10*60+30, serviceIds: ['herreklip'],            customerId: 'c15' },
  { id: 'b16', staffId: 's4', start: 12*60,    serviceIds: ['herreklip'],            customerId: 'c16' },
  { id: 'b17', staffId: 's4', start: 13*60,    serviceIds: ['pensionist'],           customerId: 'c17' },

  { id: 'b18', staffId: 's5', start: 9*60+30,  serviceIds: ['dameklip'],             customerId: 'c2' },
  { id: 'b19', staffId: 's5', start: 11*60,    serviceIds: ['boerneklip'],           customerId: 'c11' },
  { id: 'b20', staffId: 's5', start: 13*60,    serviceIds: ['herreklip'],            customerId: 'c4' },
  { id: 'b21', staffId: 's5', start: 14*60+15, serviceIds: ['dameklip','haarvask'],  customerId: 'c8' },
];

// Helpers for multi-service bookings
// Each booking can have multiple services run sequentially with their pauses.
// We store: { id, staffId, start, serviceIds: [...], customerId, note }

function getBookingSegments(booking) {
  // Returns [{ kind: 'work'|'gap', serviceId, name, start, end, color }]
  // 'gap' = mellemrum — frisøren er fri og kan booke andre kunder ind i tiden
  const ids = booking.serviceIds || (booking.serviceId ? [booking.serviceId] : []);
  let t = booking.start;
  const segs = [];
  ids.forEach((id, i) => {
    const s = SERVICE_BY_ID[id];
    if (!s) return;
    segs.push({ kind: 'work', serviceId: id, name: s.name, start: t, end: t + s.duration, color: s.color });
    t += s.duration;
    if (s.pauseAfter > 0) {
      segs.push({ kind: 'gap', serviceId: id, name: 'Mellemrum', start: t, end: t + s.pauseAfter });
      t += s.pauseAfter;
    }
  });
  return segs;
}

// Returns the busy intervals (work segments only) for a staff member.
// Used to show only available timeslots in the new-booking picker.
function getStaffBusyIntervals(staffId, bookings) {
  const intervals = [];
  bookings.filter(b => b.staffId === staffId).forEach(b => {
    getBookingSegments(b).forEach(seg => {
      if (seg.kind === 'work') intervals.push({ start: seg.start, end: seg.end });
    });
  });
  return intervals.sort((a, b) => a.start - b.start);
}

// Check if a proposed booking (start, serviceIds) clashes with existing work segments
// for the given staff. Optionally exclude a booking id (for moves).
function hasConflict(staffId, start, serviceIds, bookings, excludeId) {
  const others = bookings.filter(b => b.staffId === staffId && b.id !== excludeId);
  const busy = [];
  others.forEach(b => {
    getBookingSegments(b).forEach(seg => {
      if (seg.kind === 'work') busy.push({ start: seg.start, end: seg.end });
    });
  });
  // Build proposed work intervals
  const proposed = [];
  let t = start;
  for (const id of serviceIds) {
    const s = SERVICE_BY_ID[id];
    if (!s) continue;
    proposed.push({ start: t, end: t + s.duration });
    t += s.duration + (s.pauseAfter || 0);
  }
  for (const p of proposed) {
    for (const b of busy) {
      if (p.start < b.end && p.end > b.start) return true;
    }
  }
  return false;
}

function getBookingDuration(booking) {
  const segs = getBookingSegments(booking);
  if (!segs.length) return 30;
  return segs[segs.length - 1].end - booking.start;
}

function getBookingPrice(booking) {
  const ids = booking.serviceIds || (booking.serviceId ? [booking.serviceId] : []);
  return ids.reduce((sum, id) => sum + (SERVICE_BY_ID[id]?.price || 0), 0);
}

function getBookingPrimary(booking) {
  const ids = booking.serviceIds || (booking.serviceId ? [booking.serviceId] : []);
  return SERVICE_BY_ID[ids[0]];
}

function getBookingTitle(booking) {
  const ids = booking.serviceIds || (booking.serviceId ? [booking.serviceId] : []);
  return ids.map(id => SERVICE_BY_ID[id]?.name || '?').join(' + ');
}

// YYYY-MM-DD in local time (NOT toISOString — that's UTC and shifts the date).
function toISODate(d) {
  const yr = d.getFullYear();
  const mo = String(d.getMonth() + 1).padStart(2, '0');
  const dy = String(d.getDate()).padStart(2, '0');
  return yr + '-' + mo + '-' + dy;
}

const DAY_NAMES = ['Søndag','Mandag','Tirsdag','Onsdag','Torsdag','Fredag','Lørdag'];
const MONTH_NAMES = ['januar','februar','marts','april','maj','juni','juli','august','september','oktober','november','december'];

function formatDanishDate(d) {
  return DAY_NAMES[d.getDay()] + ' ' + d.getDate() + '. ' + MONTH_NAMES[d.getMonth()] + ' ' + d.getFullYear();
}

Object.assign(window, {
  SERVICES, SERVICE_BY_ID, SERVICE_COLORS,
  STAFF, DEPARTMENTS, CUSTOMERS, INITIAL_BOOKINGS,
  refreshServiceById, getBookingSegments, getBookingDuration,
  getBookingPrice, getBookingPrimary, getBookingTitle,
  getStaffBusyIntervals, hasConflict,
  paletteFromHex, getServicePalette,
  toISODate, formatDanishDate, DAY_NAMES, MONTH_NAMES,
});
