/**
 * GalleryElement Component
 *
 * Gallery element with header image, title, info spans, and grid of image cards.
 * Renders with unified wrapper styling + content.
 */

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

interface GalleryElementProps {
  element: CanvasElement;
  resolveUrl?: (url: string | undefined) => string;
  className: string;
  style: CSSProperties;
  onCardClick?: (cardIndex: number) => void;
}

const GalleryElement: React.FC<GalleryElementProps> = ({
  element,
  resolveUrl,
  className,
  style,
  onCardClick,
}) => {
  const resolve = resolveUrl ?? resolveAssetPlaybackUrl;
  const cards: GalleryCard[] = element.galleryCards || [];
  const infoSpans: GalleryInfoSpan[] = element.galleryInfoSpans || [];
  const headerImageUrl = element.galleryHeaderImageUrl;
  const title = element.galleryTitle;
  const columns = element.galleryColumns || 3;

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

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

  // Extract backgroundColor from style to apply to inner content wrapper
  const { backgroundColor, ...outerStyle } = style;

  return (
    <div className={className} style={outerStyle}>
      <div
        className='flex flex-col gap-2 p-3 rounded-xl min-w-[200px] backdrop-blur-sm'
        style={{ backgroundColor: backgroundColor || 'rgba(0, 0, 0, 0.6)' }}
      >
        {/* Header image */}
        {headerImageUrl && (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={resolve(headerImageUrl)}
            alt=''
            className='w-full h-auto object-cover rounded-lg'
            draggable={false}
          />
        )}

        {/* Title */}
        {title && (
          <div
            className='bg-amber-50 text-slate-800 text-center py-2 px-3 rounded-lg font-semibold text-sm'
            style={titleFontStyle}
          >
            {title}
          </div>
        )}

        {/* Info spans */}
        {infoSpans.length > 0 && (
          <div
            className='grid gap-2'
            style={{ gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
          >
            {infoSpans.map((span) => (
              <div
                key={span.id}
                className='bg-slate-700 text-amber-50 text-center py-2 px-2 rounded-lg text-xs font-medium'
                style={textFontStyle}
              >
                {span.text}
              </div>
            ))}
          </div>
        )}

        {/* Gallery cards */}
        {cards.length > 0 && (
          <div
            className='grid gap-2 w-full'
            style={{ gridTemplateColumns: `repeat(${columns}, 1fr)` }}
          >
            {cards.map((card, index) => (
              <div
                key={card.id}
                className={`relative aspect-[4/3] min-w-[50px] min-h-[40px] ${
                  onCardClick
                    ? 'cursor-pointer hover:ring-2 hover:ring-white hover:ring-offset-1 hover:ring-offset-black/50 transition-all'
                    : ''
                }`}
                onClick={(e) => {
                  if (onCardClick) {
                    e.stopPropagation();
                    onCardClick(index);
                  }
                }}
              >
                {card.imageUrl && (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={resolve(card.imageUrl)}
                    alt={card.title || ''}
                    className='absolute inset-0 w-full h-full object-cover rounded-lg'
                    draggable={false}
                  />
                )}
                {card.title && (
                  <div className='absolute inset-0 flex items-center justify-center'>
                    <span
                      className='text-white text-xs font-bold drop-shadow-lg'
                      style={textFontStyle}
                    >
                      {card.title}
                    </span>
                  </div>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

export default GalleryElement;
