// This file was moved from the `server` package to here and `server` has `strictNullChecks` disabled.
// This code was originally written with the assumption that `widget.children` is never undefined, despite the type saying otherwise.
// So we are using `!` to assert that `widget.children` is never undefined.
// Note that `!` does not change the runtime behavior of the code so the code will work the same way as before.

import { cloneDeep } from 'lodash';
import type { PageDSL6, WidgetProps6 } from '../../../types/index.js';

enum ModalSize {
  EXTRA_SMALL = 'EXTRA_SMALL',
  SMALL = 'SMALL',
  MEDIUM = 'MEDIUM',
  LARGE = 'LARGE',
  FULLSCREEN = 'FULLSCREEN'
}

const MODAL_ROWS_PRESETS_NEW = {
  [ModalSize.EXTRA_SMALL]: 13,
  [ModalSize.SMALL]: 22,
  [ModalSize.MEDIUM]: 31,
  [ModalSize.LARGE]: 47,
  [ModalSize.FULLSCREEN]: 72
};

export const adjustModalCanvases = (dsl: PageDSL6): PageDSL6 => {
  const newDsl = cloneDeep(dsl);
  const adjustChildren = (widget: WidgetProps6, parent?: WidgetProps6) => {
    if (parent && parent.type === 'MODAL_WIDGET') {
      const heightPreset = parent.heightPreset as ModalSize;
      if (widget.type === 'CANVAS_WIDGET') {
        const bottomChildRow = widget.children!.reduce((max, child) => {
          if (child.bottomRow) {
            return Math.max(max, child.bottomRow);
          }
          return max;
        }, 0);

        if (bottomChildRow <= MODAL_ROWS_PRESETS_NEW[heightPreset]) {
          widget.bottomRow = MODAL_ROWS_PRESETS_NEW[heightPreset];
        }
      }
    }
    if (Array.isArray(widget.children)) {
      for (const child of widget.children) {
        adjustChildren(child, widget);
      }
    }
  };

  adjustChildren(newDsl);
  return newDsl;
};
