/**
 * TooltipElement Component
 *
 * Tooltip element with icon or text content.
 * Renders with unified wrapper styling + content.
 */

import React, { useMemo } from 'react';
import type { CSSProperties } from 'react';
import type { CanvasElement } from '../../../types/constructor';
import { resolveAssetPlaybackUrl } from '../../../lib/assetUrl';
import { getFontByKey, getFontStyle } from '../../../lib/fonts';

interface TooltipElementProps {
  element: CanvasElement;
  resolveUrl?: (url: string | undefined) => string;
  className: string;
  style: CSSProperties;
}

const TooltipElement: React.FC<TooltipElementProps> = ({
  element,
  resolveUrl,
  className,
  style,
}) => {
  const resolve = resolveUrl ?? resolveAssetPlaybackUrl;

  // Resolve font keys to full CSS styles (including fontStretch for condensed variants)
  const titleFontStyle = useMemo(() => {
    const fontKey = element.tooltipTitleFontFamily;
    if (!fontKey) return {};
    const font = getFontByKey(fontKey);
    return font ? getFontStyle(font) : { fontFamily: fontKey };
  }, [element.tooltipTitleFontFamily]);

  const textFontStyle = useMemo(() => {
    const fontKey = element.tooltipTextFontFamily;
    if (!fontKey) return {};
    const font = getFontByKey(fontKey);
    return font ? getFontStyle(font) : { fontFamily: fontKey };
  }, [element.tooltipTextFontFamily]);

  // With icon: render image
  if (element.iconUrl) {
    const imgStyle: CSSProperties = {
      width: element.width ? '100%' : 'auto',
      height: element.height ? '100%' : 'auto',
      objectFit: 'contain',
    };

    return (
      <div className={className} style={style}>
        {/* eslint-disable-next-line @next/next/no-img-element */}
        <img
          src={resolve(element.iconUrl)}
          alt='Tooltip'
          style={imgStyle}
          draggable={false}
        />
      </div>
    );
  }

  // Without icon: render text tooltip
  return (
    <div className={className} style={style}>
      <div className='p-3 max-w-[200px]'>
        <p className='font-bold text-sm' style={titleFontStyle}>
          {element.tooltipTitle}
        </p>
        <p className='text-xs opacity-70' style={textFontStyle}>
          {element.tooltipText}
        </p>
      </div>
    </div>
  );
};

export default TooltipElement;
