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

let calMonth = null;
let calDates = new Set();
let selectedDate = '';
let onDateChange = null;
let popListenerAttached = false;

export function getSelectedDate() { return selectedDate; }

export function setOnDateChange(fn) { onDateChange = fn; }

export function resetCalendar() {
  selectedDate = '';
  document.getElementById('cal-label').textContent = 'All dates';
  document.getElementById('cal-pop').classList.add('hidden');
}

export function updateCalDates() {
  calDates = new Set();
  const DATA = getData();
  const name = document.getElementById('dev-select').value;
  const cli = document.getElementById('cli-select').value;
  if (!name || !DATA.developers[name]) return;
  let sessions = DATA.developers[name].sessions;
  if (cli) sessions = sessions.filter(s => s.source === cli);
  for (const s of sessions) calDates.add(s.start.slice(0, 10));
}

export function setDateFilter(dateStr) {
  if (selectedDate === dateStr) dateStr = '';
  selectedDate = dateStr;
  document.getElementById('date-select').value = dateStr;
  document.getElementById('cal-label').textContent = dateStr ? formatDate(dateStr) : 'All dates';
  if (onDateChange) onDateChange();
  renderCalendar();
}

export function toggleCalendar() {
  const pop = document.getElementById('cal-pop');
  if (!pop.classList.contains('hidden')) { pop.classList.add('hidden'); return; }
  const DATA = getData();
  if (selectedDate) {
    calMonth = new Date(selectedDate + 'T00:00:00');
  } else {
    const name = document.getElementById('dev-select').value;
    if (name && DATA.developers[name]) {
      const sessions = DATA.developers[name].sessions;
      const last = sessions[sessions.length - 1];
      calMonth = last ? new Date(last.start.slice(0, 10) + 'T00:00:00') : new Date();
    } else {
      calMonth = new Date();
    }
  }
  calMonth.setDate(1);
  updateCalDates();
  pop.classList.remove('hidden');
  renderCalendar();
  attachPopupListener();
  // Close on outside click
  setTimeout(() => document.addEventListener('click', closeCalendar, { once: true }), 0);
}

function attachPopupListener() {
  if (popListenerAttached) return;
  popListenerAttached = true;
  const pop = document.getElementById('cal-pop');
  // Handle all clicks inside the calendar popup directly
  pop.addEventListener('click', (e) => {
    // Stop propagation so closeCalendar doesn't interfere
    e.stopPropagation();

    const target = e.target.closest('[data-action]');
    if (!target) return;

    const action = target.dataset.action;
    if (action === 'cal-nav') {
      calNav(parseInt(target.dataset.dir));
    } else if (action === 'cal-pick') {
      setDateFilter(target.dataset.date);
      if (!target.dataset.date) document.getElementById('cal-pop').classList.add('hidden');
    } else if (action === 'cal-today') {
      calToday();
    }
  });
}

function closeCalendar(e) {
  const wrap = document.getElementById('cal-wrap');
  if (wrap && !wrap.contains(e?.target)) {
    document.getElementById('cal-pop').classList.add('hidden');
  } else if (wrap) {
    setTimeout(() => document.addEventListener('click', closeCalendar, { once: true }), 0);
  }
}

export function calNav(dir) {
  calMonth.setMonth(calMonth.getMonth() + dir);
  renderCalendar();
}

export function calToday() {
  calMonth = new Date();
  calMonth.setDate(1);
  renderCalendar();
}

export function renderCalendar() {
  const pop = document.getElementById('cal-pop');
  if (pop.classList.contains('hidden')) return;
  const year = calMonth.getFullYear();
  const month = calMonth.getMonth();
  const todayStr = new Date().toISOString().slice(0, 10);

  const monthName = calMonth.toLocaleString('en-US', { month: 'long', year: 'numeric' });

  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();
  const daysInPrev = new Date(year, month, 0).getDate();

  let html = `<div class="cal-nav">
    <button data-action="cal-nav" data-dir="-1" title="Previous month">&#9664;</button>
    <span class="cal-month">${monthName}</span>
    <button data-action="cal-nav" data-dir="1" title="Next month">&#9654;</button>
  </div>`;
  html += '<div class="cal-grid">';
  for (const d of ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']) {
    html += `<div class="cal-hdr">${d}</div>`;
  }

  for (let i = firstDay - 1; i >= 0; i--) {
    const day = daysInPrev - i;
    const m = month === 0 ? 12 : month;
    const y = month === 0 ? year - 1 : year;
    const ds = `${y}-${String(m).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    const has = calDates.has(ds);
    html += `<div class="cal-day outside${has ? ' has-data' : ''}" data-action="cal-pick" data-date="${ds}">${day}</div>`;
  }

  for (let day = 1; day <= daysInMonth; day++) {
    const ds = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    const has = calDates.has(ds);
    const isSel = ds === selectedDate;
    const isToday = ds === todayStr;
    html += `<div class="cal-day${has ? ' has-data' : ''}${isSel ? ' selected' : ''}${isToday ? ' today' : ''}" data-action="cal-pick" data-date="${ds}">${day}</div>`;
  }

  const totalCells = firstDay + daysInMonth;
  const trailing = totalCells % 7 === 0 ? 0 : 7 - (totalCells % 7);
  for (let day = 1; day <= trailing; day++) {
    const m = month + 2 > 12 ? 1 : month + 2;
    const y = month + 2 > 12 ? year + 1 : year;
    const ds = `${y}-${String(m).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
    const has = calDates.has(ds);
    html += `<div class="cal-day outside${has ? ' has-data' : ''}" data-action="cal-pick" data-date="${ds}">${day}</div>`;
  }
  html += '</div>';

  html += `<div class="flex items-center gap-1.5 mt-2 pt-2 border-t border-gray-100">
    <button data-action="cal-pick" data-date="" class="text-[10px] px-2 py-0.5 rounded hover:bg-gray-100 text-gray-500">All dates</button>
    <button data-action="cal-today" class="text-[10px] px-2 py-0.5 rounded hover:bg-[#f0fdfa] ml-auto" style="color:#009689">Today</button>
  </div>`;

  pop.innerHTML = html;
}

export function updateDateSelect() {
  const DATA = getData();
  const name = document.getElementById('dev-select').value;
  const cli = document.getElementById('cli-select').value;
  const ds = document.getElementById('date-select');
  ds.innerHTML = '<option value="">All dates</option>';
  if (!name || !DATA.developers[name]) return;
  let sessions = DATA.developers[name].sessions;
  if (cli) sessions = sessions.filter(s => s.source === cli);
  const dates = new Set();
  for (const s of sessions) dates.add(s.start.slice(0, 10));
  for (const d of [...dates].sort().reverse()) {
    const opt = document.createElement('option');
    opt.value = d; opt.textContent = formatDate(d);
    ds.appendChild(opt);
  }
}
