/* global Gantt */
(() => {
  const dateOnly = d => String(d.getFullYear()).padStart(4, '0') + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
  let mounted = false;
  addEventListener('message', event => {
    if (event.source !== parent || event.data?.type !== 'essential-plan-render' || mounted) return;
    mounted = true;
    try {
      new Gantt('#chart', event.data.tasks, {
        // Frappe 1.2.2 resets view_mode to view_modes[0] when both are supplied.
        // The parent UI already limits the available views.
        view_mode: event.data.view,
        popup: false, move_dependencies: false, ignore: [], infinite_padding: false,
        readonly_progress: true, readonly_dates: false, readonly: false,
        // With finite padding, 'start' opens at Frappe's padded month boundary.
        // Open at the earliest task so the visitor immediately sees their plan.
        scroll_to: event.data.tasks.map(task => task.start).sort()[0], container_height: 430, bar_height: 30,
        view_mode_select: false, today_button: false, auto_move_label: false,
        on_date_change(task, start, end) {
          parent.postMessage({ type: 'essential-plan-date', id: task.id, start: dateOnly(start), end: dateOnly(end) }, '*');
        },
      });
      const scrollRegion = document.querySelector('.gantt-container');
      scrollRegion?.setAttribute('tabindex', '0');
      scrollRegion?.setAttribute('role', 'region');
      scrollRegion?.setAttribute('aria-label', 'Project timeline, scroll to see all dates and tasks');
      parent.postMessage({ type: 'essential-plan-mounted' }, '*');
    } catch { parent.postMessage({ type: 'essential-plan-error' }, '*'); }
  });
  parent.postMessage({ type: 'essential-plan-ready' }, '*');
})();
