import { getData } from './data.js';

let heatmapOpen = false;

export function isHeatmapOpen() { return heatmapOpen; }

export function toggleHeatmap() {
  heatmapOpen = !heatmapOpen;
  document.getElementById('heatmap-body').classList.toggle('open', heatmapOpen);
  document.getElementById('heatmap-arrow').style.transform = heatmapOpen ? 'rotate(90deg)' : '';
  document.getElementById('heatmap-legend').classList.toggle('hidden', !heatmapOpen);
  if (heatmapOpen) {
    const wrap = document.querySelector('.heatmap-wrap');
    requestAnimationFrame(() => { wrap.scrollLeft = wrap.scrollWidth; });
  }
}

export function resetHeatmap() {
  heatmapOpen = false;
  document.getElementById('heatmap-body').classList.remove('open');
  document.getElementById('heatmap-arrow').style.transform = '';
  document.getElementById('heatmap-legend').classList.add('hidden');
}

export function renderHeatmap() {
  const toggle = document.getElementById('heatmap-toggle');
  const grid = document.getElementById('heatmap-grid');
  const statsEl = document.getElementById('heatmap-stats');
  const DATA = getData();
  const name = document.getElementById('dev-select').value;
  if (!name || !DATA.developers[name]) { toggle.classList.add('hidden'); return; }
  toggle.classList.remove('hidden');

  const sessions = DATA.developers[name].sessions;
  const dayCounts = {};
  let totalSessions = 0;
  for (const s of sessions) {
    const d = s.start.slice(0, 10);
    dayCounts[d] = (dayCounts[d] || 0) + 1;
    totalSessions++;
  }
  const activeDays = Object.keys(dayCounts).length;
  const maxCount = Math.max(...Object.values(dayCounts), 1);

  const allDates = Object.keys(dayCounts).sort();
  const earliest = new Date(allDates[0] + 'T00:00:00');
  const today = new Date();
  today.setHours(0, 0, 0, 0);

  const startDate = new Date(earliest);
  startDate.setDate(startDate.getDate() - startDate.getDay());

  const totalWeeks = Math.ceil((today - startDate) / (7 * 86400000)) + 1;
  const cellSize = 10;
  const cellGap = 2;
  const step = cellSize + cellGap;
  const dayLabelWidth = 24;
  const svgWidth = dayLabelWidth + totalWeeks * step + 4;
  const headerHeight = 14;
  const svgHeight = headerHeight + 7 * step;

  const COLORS = ['#e0f2f1', '#80cbc4', '#009689', '#00796b', '#004d40'];
  function getColor(count) {
    if (count === 0) return COLORS[0];
    const q = count / maxCount;
    if (q <= 0.25) return COLORS[1];
    if (q <= 0.5) return COLORS[2];
    if (q <= 0.75) return COLORS[3];
    return COLORS[4];
  }

  const DAY_LABELS = ['', 'M', '', 'W', '', 'F', ''];
  let svg = `<svg width="${svgWidth}" height="${svgHeight}" class="block">`;

  for (let d = 0; d < 7; d++) {
    if (DAY_LABELS[d]) {
      svg += `<text x="0" y="${headerHeight + d * step + 8}" class="fill-gray-400" font-size="8" font-family="system-ui">${DAY_LABELS[d]}</text>`;
    }
  }

  let lastMonth = -1;
  for (let w = 0; w < totalWeeks; w++) {
    const weekStart = new Date(startDate);
    weekStart.setDate(weekStart.getDate() + w * 7);
    if (weekStart.getMonth() !== lastMonth) {
      lastMonth = weekStart.getMonth();
      const monthName = weekStart.toLocaleString('en-US', { month: 'short' });
      svg += `<text x="${dayLabelWidth + w * step}" y="9" class="fill-gray-400" font-size="8" font-family="system-ui">${monthName}</text>`;
    }
  }

  for (let w = 0; w < totalWeeks; w++) {
    for (let d = 0; d < 7; d++) {
      const cellDate = new Date(startDate);
      cellDate.setDate(cellDate.getDate() + w * 7 + d);
      if (cellDate > today) continue;
      const dateStr = cellDate.toISOString().slice(0, 10);
      const count = dayCounts[dateStr] || 0;
      const color = getColor(count);
      const x = dayLabelWidth + w * step;
      const y = headerHeight + d * step;
      const label = `${cellDate.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })}: ${count} session${count !== 1 ? 's' : ''}`;
      svg += `<rect class="hm-cell" x="${x}" y="${y}" width="${cellSize}" height="${cellSize}" fill="${color}" rx="2" data-action="heatmap-click" data-date="${dateStr}"><title>${label}</title></rect>`;
    }
  }
  svg += '</svg>';

  grid.innerHTML = svg;
  statsEl.textContent = `${totalSessions} sessions · ${activeDays} days`;

  if (heatmapOpen) {
    const wrap = grid.closest('.heatmap-wrap');
    requestAnimationFrame(() => { wrap.scrollLeft = wrap.scrollWidth; });
  }
}
