import { getBeatsFromZero } from '@suno/studiokit/timeMapping';

import logWebUserEvent from '@/logging/logWebUserEvent';

import { getAnalyticsToolName } from '../EditModeContext';
import { getEditCategory } from '../SelectionContext';
import { CanvasRegion } from './CanvasRenderer';
import { EditCanvasRenderContext } from './EditCanvasRenderContext';
import makeRoundedRectRegion from './makeRoundedRectRegion';

export default function makeSectionRegions({
  songEndSeconds,
  timing,
  pxPerBeat,
  scrollX,
  previewEdit,
  sectionY,
  sectionHeight,
  waveformY,
  waveformHeight,
  playbackContext,
  setSelection,
  editMode,
  editSessionId,
  clipId,
  frameCountRef,
  sortedSectionEntries,
}: EditCanvasRenderContext): CanvasRegion[] {
  return sortedSectionEntries
    .map(([sectionStartSeconds, section], index, list) => {
      const sectionEndSeconds = Math.min(
        list[index + 1]?.[0] || songEndSeconds,
        songEndSeconds
      );
      const startBeats = getBeatsFromZero(sectionStartSeconds, timing);
      const endBeats = getBeatsFromZero(sectionEndSeconds, timing);
      const baseParams = {
        startBeats,
        endBeats,
        pxPerBeat,
        scrollX,
        color: section.color,
        isLast: index === list.length - 1,
      };
      return [
        makeRoundedRectRegion({
          ...baseParams,
          color: section.color + (previewEdit ? '88' : ''),
          y: sectionY + 2,
          height: sectionHeight - 2,
          text: section.name.toUpperCase(),
          onMouseDown: previewEdit
            ? undefined
            : () => {
                playbackContext.seek(sectionStartSeconds);
                frameCountRef.current++;
                if (getEditCategory(editMode) !== 'no-selection') {
                  setSelection([sectionStartSeconds, sectionEndSeconds]);
                  logWebUserEvent({
                    actionName: 'MakeWaveformSelection',
                    context: {
                      startSeconds: sectionStartSeconds,
                      endSeconds: sectionEndSeconds,
                      editTool: getAnalyticsToolName(editMode),
                      editSessionId: editSessionId || 'MISSING_EDIT_SESSION_ID',
                      editingClipId: clipId,
                      actionIndex: -1, // todo?
                      inputType: 'timeline-section-click',
                    },
                  });
                }
              },
        }),
        ...(editMode === 'stems'
          ? []
          : [
              makeRoundedRectRegion({
                ...baseParams,
                color: section.color + (previewEdit ? '22' : '88'),
                y: waveformY + 1,
                height: waveformHeight,
              }),
            ]),
      ];
    })
    .flat();
}
