'use client';

import { AnimatePresence, motion } from 'framer-motion';
import { FC } from 'react';

import ImageWithFallback from '@/components/image/ImageWithFallback';
import { useBreakpointLg, useBreakpointMd } from '@/hooks/useBreakpoint';
import logWebUserEvent from '@/logging/logWebUserEvent';

import { DecorativeGraphic } from '../HomePageClient';

interface DecorativeGraphicsLayerProps {
  graphics?: DecorativeGraphic[];
  scope?: 'hero' | 'global' | string;
}

const DecorativeGraphicsLayer: FC<DecorativeGraphicsLayerProps> = ({
  graphics,
  scope = 'global',
}) => {
  const isDesktop = useBreakpointLg();
  const isTablet = useBreakpointMd();

  if (!graphics || graphics.length === 0) return null;

  return (
    <div
      className='pointer-events-none absolute inset-0 overflow-hidden'
      data-scope={scope}
    >
      <AnimatePresence>
        {graphics.map((graphic) => (
          <DecorativeGraphicItem
            key={graphic.id}
            graphic={graphic}
            isDesktop={isDesktop}
            isTablet={isTablet}
          />
        ))}
      </AnimatePresence>
    </div>
  );
};

interface DecorativeGraphicItemProps {
  graphic: DecorativeGraphic;
  isDesktop: boolean;
  isTablet: boolean;
}

const DecorativeGraphicItem: FC<DecorativeGraphicItemProps> = ({
  graphic,
  isDesktop,
  isTablet,
}) => {
  // Determine current breakpoint position/size
  const position = isDesktop
    ? graphic.position.desktop
    : isTablet && graphic.position.tablet
      ? graphic.position.tablet
      : graphic.position.mobile || graphic.position.desktop;

  const size = isDesktop
    ? graphic.size.desktop
    : isTablet && graphic.size.tablet
      ? graphic.size.tablet
      : graphic.size.mobile || graphic.size.desktop;

  // Hide if breakpoint specifies display: none
  if (position.display === 'none') return null;

  // Build animation based on type
  const getAnimation = () => {
    if (!graphic.animation || graphic.animation.type === 'none') {
      return {};
    }

    if (graphic.animation.custom) {
      return graphic.animation.custom;
    }

    const {
      type,
      duration = 3,
      delay = 0,
      easing = 'easeInOut',
    } = graphic.animation;

    switch (type) {
      case 'float':
        return {
          initial: { y: 0 },
          animate: {
            y: [-10, 10, -10],
            transition: {
              duration,
              delay,
              ease: easing,
              repeat: Infinity,
            },
          },
        };
      case 'pulse':
        return {
          initial: { scale: 1, opacity: 1 },
          animate: {
            scale: [1, 1.05, 1],
            opacity: [1, 0.8, 1],
            transition: {
              duration,
              delay,
              ease: easing,
              repeat: Infinity,
            },
          },
        };
      case 'rotate':
        return {
          initial: { rotate: 0 },
          animate: {
            rotate: 360,
            transition: {
              duration,
              delay,
              ease: 'linear',
              repeat: Infinity,
            },
          },
        };
      default:
        return {};
    }
  };

  const animation = getAnimation();

  const handleClick = () => {
    if (graphic.interactive?.clickable && graphic.interactive.onClick) {
      logWebUserEvent({
        actionName: 'HomePageDecorativeGraphicClicked',
        context: {
          graphicId: graphic.id,
          action: graphic.interactive.onClick,
          target: graphic.interactive.target,
        },
      });

      if (
        graphic.interactive.onClick === 'open-url' &&
        graphic.interactive.target
      ) {
        window.open(graphic.interactive.target, '_blank');
      } else if (
        graphic.interactive.onClick === 'scroll-to' &&
        graphic.interactive.target
      ) {
        const element = document.getElementById(graphic.interactive.target);
        element?.scrollIntoView({ behavior: 'smooth' });
      }
    }
  };

  return (
    <div
      className='absolute'
      style={{
        top: position.top,
        left: position.left,
        right: position.right,
        bottom: position.bottom,
        transform: position.transform,
        width: size.width,
        height: size.height,
        zIndex: graphic.zIndex || 1,
        opacity: graphic.opacity || 1,
        pointerEvents: graphic.interactive?.clickable ? 'auto' : 'none',
      }}
      onClick={graphic.interactive?.clickable ? handleClick : undefined}
      onKeyDown={
        graphic.interactive?.clickable
          ? (e) => {
              if (e.key === 'Enter' || e.key === ' ') {
                e.preventDefault();
                handleClick();
              }
            }
          : undefined
      }
      role={graphic.interactive?.clickable ? 'button' : undefined}
      tabIndex={graphic.interactive?.clickable ? 0 : undefined}
    >
      <motion.div className='h-full w-full' {...animation}>
        {graphic.type === 'video' ? (
          <video
            autoPlay
            loop
            muted
            playsInline
            className='h-full w-full object-contain'
            src={graphic.src}
          />
        ) : (
          <ImageWithFallback
            src={graphic.src}
            alt={graphic.alt || ''}
            className='h-full w-full object-contain'
            width={parseInt(size.width || '100')}
            height={parseInt(size.height || '100')}
          />
        )}
      </motion.div>
    </div>
  );
};

export default DecorativeGraphicsLayer;
