import { loadIndex, getData } from './data.js';
import { showToast } from './utils.js';
import { renderSessions, showMessages, jumpMsg, jumpCompact, getLastCompactJump, jumpInterrupt, getLastInterruptJump, splitJump, setupScrollTracking, ganttHover, ganttClick } from './sessions.js';
import { renderHeatmap, toggleHeatmap, resetHeatmap } from './heatmap.js';
import { toggleCalendar, setDateFilter, getSelectedDate, resetCalendar, updateDateSelect, setOnDateChange, renderCalendar } from './calendar.js';
import { toggleExportMenu, exportSession } from './export.js';
import { setupMinimapInteractions } from './minimap.js';

async function init() {
  await loadIndex();

  // Populate developer select
  const devSelect = document.getElementById('dev-select');
  const DATA = getData();
  for (const name of Object.keys(DATA.developers).sort()) {
    const opt = document.createElement('option');
    opt.value = name; opt.textContent = name;
    devSelect.appendChild(opt);
  }

  // Wire up date change callback
  setOnDateChange(() => {
    renderSessions(getSelectedDate());
    renderCalendar();
  });

  // Developer change
  devSelect.addEventListener('change', () => {
    resetCalendar();
    updateDateSelect();
    renderSessions(getSelectedDate());
    resetHeatmap();
    renderHeatmap();
    document.getElementById('session-header').classList.add('hidden');
    document.getElementById('message-panel').innerHTML = '<div class="flex items-center justify-center h-full text-gray-300 text-sm">Select a session from the timeline</div>';
  });

  // CLI filter change
  document.getElementById('cli-select').addEventListener('change', () => {
    updateDateSelect();
    renderSessions(getSelectedDate());
    renderHeatmap();
  });

  // Calendar button
  document.getElementById('cal-btn').addEventListener('click', toggleCalendar);

  // Heatmap button
  document.getElementById('heatmap-btn').addEventListener('click', toggleHeatmap);

  // Jump bar buttons
  document.getElementById('jump-prev-btn').addEventListener('click', () => jumpMsg(-1));
  document.getElementById('jump-next-btn').addEventListener('click', () => jumpMsg(1));
  document.getElementById('jump-top-btn').addEventListener('click', () => {
    document.getElementById('message-panel').scrollTop = 0;
  });
  document.getElementById('jump-bottom-btn').addEventListener('click', () => {
    const panel = document.getElementById('message-panel');
    panel.scrollTop = panel.scrollHeight;
  });

  // Keyboard shortcuts
  document.addEventListener('keydown', (e) => {
    if (e.target.tagName === 'SELECT' || e.target.tagName === 'INPUT') return;
    if (e.key === 'j') jumpMsg(1);
    if (e.key === 'k') jumpMsg(-1);
  });

  // Global delegated event handler
  document.addEventListener('click', (e) => {
    const target = e.target.closest('[data-action]');
    if (!target) return;

    const action = target.dataset.action;

    switch (action) {
      case 'heatmap-click':
        e.stopPropagation();
        setDateFilter(target.dataset.date);
        break;

      // cal-pick, cal-nav, cal-today are handled directly by calendar module on #cal-pop

      case 'toggle-export':
        toggleExportMenu();
        break;

      case 'export':
        exportSession(target.dataset.mode, target.dataset.filter);
        break;

      case 'copy-session-id':
        navigator.clipboard.writeText(target.dataset.sessionId);
        showToast('Session ID copied');
        break;

      case 'jump-compact':
        jumpCompact(getLastCompactJump());
        break;

      case 'jump-interrupt':
        jumpInterrupt(getLastInterruptJump());
        break;

      case 'close-parallel':
        document.getElementById('message-panel').innerHTML = '<div class="flex items-center justify-center h-full text-gray-300 text-sm">Select a session from the timeline</div>';
        break;

      case 'open-session':
        showMessages(target.dataset.sid, target.dataset.source, null);
        break;

      case 'split-jump':
        splitJump(target.dataset.pane, parseInt(target.dataset.dir));
        break;
    }
  });

  // Collapsible tag toggle (delegated)
  document.addEventListener('click', (e) => {
    const btn = e.target.closest('.tag-toggle');
    if (!btn) return;
    const id = btn.dataset.collapseId;
    if (!id) return;
    document.getElementById(id).classList.toggle('open');
    btn.classList.toggle('open');
  });

  // Timeline node clicks (delegated)
  document.getElementById('session-list').addEventListener('click', (e) => {
    const node = e.target.closest('.tl-node');
    if (node) {
      showMessages(node.dataset.sid, node.dataset.source, node);
      return;
    }
  });

  // Gantt area interactions (delegated)
  document.getElementById('session-list').addEventListener('mousemove', (e) => {
    const area = e.target.closest('.gantt-area');
    if (area) ganttHover(e, parseInt(area.dataset.gidx), area);
  });
  document.getElementById('session-list').addEventListener('click', (e) => {
    const area = e.target.closest('.gantt-area');
    if (area && !e.target.closest('.tl-node')) {
      ganttClick(e, parseInt(area.dataset.gidx), area);
    }
  });

  // Setup scroll tracking and minimap
  setupScrollTracking();
  setupMinimapInteractions();
}

init();
