import { IRenderer, IRenderContext } from '../../core/IGroupingRenderer';
import { DateService } from '../../core/DateService';

export class DateRenderer implements IRenderer {
  readonly type = 'date';

  constructor(private dateService: DateService) {}

  render(context: IRenderContext): void {
    const dates = context.filter['date'] || [];
    const resourceIds = context.filter['resource'] || [];

    // Check if date headers should be hidden (e.g., in day view)
    const dateGrouping = context.groupings?.find(g => g.type === 'date');
    const hideHeader = dateGrouping?.hideHeader === true;

    // Render dates for HVER resource (eller 1 gang hvis ingen resources)
    const iterations = resourceIds.length || 1;
    let columnCount = 0;

    for (let r = 0; r < iterations; r++) {
      const resourceId = resourceIds[r]; // undefined hvis ingen resources

      for (const dateStr of dates) {
        const date = this.dateService.parseISO(dateStr);

        // Build columnKey for uniform identification
        const segments: Record<string, string> = { date: dateStr };
        if (resourceId) segments.resource = resourceId;
        const columnKey = this.dateService.buildColumnKey(segments);

        // Header
        const header = document.createElement('swp-day-header');
        header.dataset.date = dateStr;
        header.dataset.columnKey = columnKey;
        if (resourceId) {
          header.dataset.resourceId = resourceId;
        }
        if (hideHeader) {
          header.dataset.hidden = 'true';
        }
        header.innerHTML = `
          <swp-day-name>${this.dateService.getDayName(date, 'short')}</swp-day-name>
          <swp-day-date>${date.getDate()}</swp-day-date>
        `;
        context.headerContainer.appendChild(header);

        // Column
        const column = document.createElement('swp-day-column');
        column.dataset.date = dateStr;
        column.dataset.columnKey = columnKey;
        if (resourceId) {
          column.dataset.resourceId = resourceId;
        }
        column.innerHTML = '<swp-events-layer></swp-events-layer>';
        context.columnContainer.appendChild(column);

        columnCount++;
      }
    }

    // Set grid columns on container
    const container = context.columnContainer.closest('swp-calendar-container');
    if (container) {
      (container as HTMLElement).style.setProperty('--grid-columns', String(columnCount));
    }
  }
}
