export function escapeHtml(str) {
  const d = document.createElement('div');
  d.textContent = str;
  return d.innerHTML;
}

export function formatDate(d) {
  const dt = new Date(d + 'T00:00:00');
  return dt.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' });
}

export function timeToMinutes(ts) {
  const h = parseInt(ts.slice(11, 13));
  const m = parseInt(ts.slice(14, 16));
  return h * 60 + m;
}

export function stripTags(text) {
  return text.replace(/<([a-zA-Z_][a-zA-Z0-9_ -]*)>[\s\S]*?<\/\1>/g, '').replace(/\n{3,}/g, '\n\n').trim();
}

export function showToast(msg) {
  const el = document.createElement('div');
  el.className = 'fixed bottom-6 left-1/2 -translate-x-1/2 bg-gray-900 text-white text-sm px-4 py-2 rounded-lg shadow-xl z-50 transition-opacity duration-300';
  el.textContent = msg;
  document.body.appendChild(el);
  setTimeout(() => { el.style.opacity = '0'; setTimeout(() => el.remove(), 300); }, 1500);
}

export function detectOverlaps(sessions) {
  const sorted = [...sessions].sort((a, b) => new Date(a.start) - new Date(b.start));
  for (let i = 0; i < sorted.length; i++) {
    for (let j = i + 1; j < sorted.length; j++) {
      if (new Date(sorted[j].start) < new Date(sorted[i].end)) return true;
    }
  }
  return false;
}

export function assignLanes(sessions) {
  const sorted = [...sessions].sort((a, b) => new Date(a.start) - new Date(b.start));
  const lanes = [];
  const assignments = new Map();
  for (const s of sorted) {
    const sStart = new Date(s.start);
    let placed = false;
    for (let i = 0; i < lanes.length; i++) {
      if (sStart >= lanes[i]) {
        lanes[i] = new Date(s.end);
        assignments.set(s.id, i);
        placed = true;
        break;
      }
    }
    if (!placed) {
      assignments.set(s.id, lanes.length);
      lanes.push(new Date(s.end));
    }
  }
  return { assignments, laneCount: lanes.length };
}
