/*
 This file is part of GNU Taler
 (C) 2021-2024 Taler Systems S.A.

 GNU Taler 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; either version 3, or (at your option) any later version.

 GNU Taler 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
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

/**
 *
 * @author Sebastian Javier Marchano (sebasjm)
 */
import { TranslatedString } from "@gnu-taler/taler-util";
import { ComponentChildren, h, VNode } from "preact";
import { useEffect, useRef } from "preact/hooks";

/**
 * Css tooltip finds the way to be outside of the screen.
 *
 * This js implementation adds the --pos-x css variable that
 * can be used with the translate css-function to move the
 * tooltip to the left but not too much and not too little.
 *
 *   transform: translateX(var(--pos-x));
 *
 * Assumed tooltip size 200px
 *
 * @param param0
 * @returns
 */
export function Tooltip({
  text,
  children,
}: {
  text: TranslatedString;
  children: ComponentChildren;
}): VNode {
  const iRef = useRef<HTMLElement>(null);
  const screenPadding = 8;
  const TOOLTIP_CSS_WIDTH = 200; // as defined in css
  const desiredMoveLeft = TOOLTIP_CSS_WIDTH / 2;

  useEffect(() => {
    const el = iRef.current;
    if (!el) return;
    const maxWidth = window.innerWidth;

    const { x } = el.getBoundingClientRect();

    const maxMoveLeft = x - screenPadding;
    const minMoveLeft = maxWidth - screenPadding - x;

    const leftOverflow = Math.max(desiredMoveLeft - maxMoveLeft, 0);
    const rightOverflow = Math.max(desiredMoveLeft - minMoveLeft, 0);

    const xPos = desiredMoveLeft - leftOverflow + rightOverflow;

    el.style.setProperty("--pos-x", `-${xPos}px`);
    // dev mode
    el.style.setProperty("--debug-max-move-left", String(maxMoveLeft));
    el.style.setProperty("--debug-min-move-left", String(minMoveLeft));
    el.style.setProperty("--debug-left-overflow", String(leftOverflow));
    el.style.setProperty("--debug-right-overflow", String(rightOverflow));

    el.style.setProperty("--debug-x", String(x));
    el.style.setProperty("--debug-width", String(maxWidth));
  });
  return (
    <span
      ref={iRef}
      class="has-tooltip-custom "
      onTouchStart={() => {}}
      data-tooltip={text}
    >
      {children}
    </span>
  );
}
