/*
 * Copyright (C) 2025 StApps
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
import {Animation, AnimationController} from '@ionic/angular';

/**
 * Defines the animation for showing a modal as a right-hand sidebar.
 * @param baseElement The root element of the modal (including Shadow DOM).
 * @param animationCtrl The Ionic AnimationController.
 * @returns The configured Ionic animation.
 */
export const enterAnimation = (baseElement: HTMLElement, animationCtrl: AnimationController): Animation => {
  const root = baseElement.shadowRoot;

  const backdrop = root?.querySelector('ion-backdrop');
  const wrapper = root?.querySelector('.modal-wrapper');

  // The wrapper needs to be positioned on the right side
  if (wrapper instanceof HTMLElement) {
    Object.assign(wrapper.style, {
      position: 'absolute',
      top: '0',
      right: '0',
      height: '100%',
      width: '304px',
      maxWidth: '75%',
      opacity: '1',
    });
  }

  const backdropAnimation = animationCtrl
    .create()
    .addElement(backdrop!)
    .fromTo('opacity', '0.01', 'var(--backdrop-opacity)');

  const wrapperAnimation = animationCtrl
    .create()
    .addElement(wrapper!)
    .fromTo('transform', 'translateX(100%)', 'translateX(0)');

  return animationCtrl
    .create()
    .addElement(baseElement)
    .duration(400)
    .easing('ease-out')
    .addAnimation([backdropAnimation, wrapperAnimation]);
};

/**
 * Defines the animation for hiding a modal by sliding it out to the right.
 * @param baseElement The root element of the modal.
 * @param animationCtrl The Ionic AnimationController.
 * @returns The configured Ionic animation (reverse of enterAnimation).
 */
export const leaveAnimation = (baseElement: HTMLElement, animationCtrl: AnimationController): Animation => {
  return enterAnimation(baseElement, animationCtrl).direction('reverse');
};
