import React, { useEffect, useRef } from 'react';

import { ModuleStyles } from './module-styles';
import { ModuleScriptData } from './module-script-data';
import { moduleClassnames } from './module-classnames';
import { getGalleryData } from './dynamic-options';

const { ModuleContainer } = window?.divi?.module ?? {};

const attrValue = (attrs, name, fallback = '') =>
  attrs?.[name]?.innerContent?.desktop?.value ?? fallback;

const isVideoUrl = (url) =>
  /\.(mp4|m4v|mov|webm|ogv|ogg|avi|wmv|mpg|mpeg|3gp)(\?.*)?(#.*)?$/i.test(url || '');

const buildItemsHtml = (images, itemStyle) =>
  images
    .map((url, index) => {
      const isVideo = isVideoUrl(url);
      const media = isVideo
        ? `<video src="${url}#t=0.1" preload="metadata" muted playsinline style="${itemStyle} object-fit: cover;"></video>`
        : `<img src="${url}" alt="Gallery Image ${index + 1}" style="${itemStyle}">`;

      return `<div class="gallery-item"><button type="button" class="gallery-button" data-url="${url}" data-type="${isVideo ? 'video' : 'image'}">${media}</button></div>`;
    })
    .join('');

/**
 * Apply the per-card hover highlight in the Divi 5 editor.
 *
 * In the Visual Builder's app window Divi sets `pointer-events: none` on module
 * media and overlays the module with `et-vb-module-mousetrap`, so the per-card
 * CSS `:hover` can never fire there. We instead track the pointer (capture
 * phase, so the mousetrap doesn't hide it) and toggle a class on the card under
 * the cursor, giving the same "grow" feedback as the frontend.
 *
 * The hit test uses the media box (`img` / `video`), not the `.gallery-item`
 * wrapper — the wrapper has padding, which would make the effect trigger before
 * the cursor actually reaches the image.
 */
const useGalleryItemHover = (ref, signature) => {
  useEffect(() => {
    const root = ref.current;

    if (!root) {
      return undefined;
    }

    const targets = () => Array.from(root.querySelectorAll('.gallery-item')).map((item) => ({
      item,
      media: item.querySelector('img, video') || item,
    }));
    let frame = 0;
    let last = null;

    const clear = () => {
      if (last) {
        last.classList.remove('lknscf-item-hover');
        last = null;
      }
    };

    const onMove = (event) => {
      const { clientX: x, clientY: y } = event;

      cancelAnimationFrame(frame);
      frame = requestAnimationFrame(() => {
        const hit = targets().find(({ media }) => {
          const rect = media.getBoundingClientRect();
          return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
        });
        const found = hit ? hit.item : null;

        if (found === last) {
          return;
        }

        if (last) {
          last.classList.remove('lknscf-item-hover');
        }

        last = found;

        if (last) {
          last.classList.add('lknscf-item-hover');
        }
      });
    };

    document.addEventListener('mousemove', onMove, true);
    document.addEventListener('mouseleave', clear, true);

    return () => {
      document.removeEventListener('mousemove', onMove, true);
      document.removeEventListener('mouseleave', clear, true);
      cancelAnimationFrame(frame);
      clear();
    };
  }, [ref, signature]);
};

/**
 * Initialize (or destroy) the slick carousel on the gallery element whenever the
 * relevant attributes change, mirroring the Divi 4 builder component so the
 * "Gallery Style" toggle switches the preview to a slider immediately.
 */
const useGallerySlider = (ref, config) => {
  const {
    style,
    enabled,
    imagesCount,
    dots,
    autoplay,
    arrows,
    delay,
    count,
    identity,
  } = config;

  useEffect(() => {
    const el = ref.current;
    const $ = window.jQuery;

    if (!el || !$ || !$.fn || !$.fn.slick) {
      return undefined;
    }

    const unslick = () => {
      if ($(el).hasClass('slick-initialized')) {
        try {
          $(el).slick('unslick');
        } catch (err) {
          // Ignore.
        }
      }
    };

    unslick();

    if (!enabled || style !== 'slider' || count < 2 || imagesCount >= count) {
      return undefined;
    }

    try {
      $(el).slick({
        dots,
        infinite: true,
        speed: 500,
        slidesToShow: imagesCount,
        slidesToScroll: 1,
        autoplay,
        autoplaySpeed: delay,
        prevArrow: arrows ? '<button type="button" class="slick-prev"><span><</span></button>' : '',
        nextArrow: arrows ? '<button type="button" class="slick-next"><span>></span></button>' : '',
      });
    } catch (err) {
      // Keep the gallery rendered even if slick fails.
    }

    return unslick;
    // `identity` must be part of the deps: the gallery element carries a `key`
    // that changes when the source changes (Current Page <-> a specific field),
    // which remounts the DOM node. Even when the other options are unchanged
    // (e.g. both sources have the same number of images), the fresh node needs
    // slick to be re-initialized on it — otherwise the slider silently renders
    // as a plain grid (images side by side).
  }, [style, enabled, imagesCount, dots, autoplay, arrows, delay, count, identity]);
};

const GalleryPreview = ({ attrs }) => {
  const galleryRef = useRef(null);

  const currentPage = attrValue(attrs, 'galleryCurrentPage', 'off') === 'on';
  const fieldLabel = attrValue(attrs, 'galleryField', 'empty');
  const style = attrValue(attrs, 'galleryStyle', 'grid') === 'slider' ? 'slider' : 'grid';
  const imageWidth = attrValue(attrs, 'galleryImageWidth', '250px') || '250px';
  const imageHeight = attrValue(attrs, 'galleryImageHeight', '250px') || '250px';

  const imagesCount = parseInt(attrValue(attrs, 'galleryImagesCount', '1'), 10) || 1;
  const dots = attrValue(attrs, 'galleryDots', 'on') === 'on';
  const autoplay = attrValue(attrs, 'galleryAutoplay', 'on') === 'on';
  const arrows = attrValue(attrs, 'galleryArrows', 'on') === 'on';
  const delay = parseInt(attrValue(attrs, 'galleryDelay', '7000'), 10) || 7000;

  const data = getGalleryData();
  const images = currentPage ? data.currentPage : (data.fields?.[fieldLabel] ?? []);

  const itemStyle = `width:${imageWidth}; height:${imageHeight};`;

  const isSlider = style === 'slider';
  const tooFew = isSlider && images.length === 1;
  const tooMany = isSlider && images.length > 1 && imagesCount >= images.length;

  // Identity of the rendered source. Used as the gallery element's React key
  // (so a source switch remounts a clean node, avoiding the external-DOM
  // (slick) reconciliation issue) and passed to the effects so they re-run on
  // that remount.
  const identity = `${style}-${currentPage ? 'current' : fieldLabel}-${images.length}`;

  useGallerySlider(galleryRef, {
    style,
    enabled: !tooFew && !tooMany,
    imagesCount,
    dots,
    autoplay,
    arrows,
    delay,
    count: images.length,
    identity,
  });

  useGalleryItemHover(galleryRef, identity);

  if (images.length === 0) {
    return (
      <div className={`lknscf-gallery-main lknscf-gallery-container-${style}`}>
        <p className="no-images" style={{ textAlign: 'center', width: '100%' }}>
          No images found
        </p>
      </div>
    );
  }

  if (tooFew) {
    return (
      <div className={`lknscf-gallery-main lknscf-gallery-container-${style}`}>
        <p className="no-images" style={{ textAlign: 'center', width: '100%' }}>
          Minimum 2 images required to use this slider style
        </p>
      </div>
    );
  }

  if (tooMany) {
    return (
      <div className={`lknscf-gallery-main lknscf-gallery-container-${style}`}>
        <p className="no-images" style={{ textAlign: 'center', width: '100%' }}>
          Number of Images per section must be less than the total number of images
        </p>
      </div>
    );
  }

  return (
    <div className={`lknscf-gallery-main lknscf-gallery-container-${style}`}>
      <div
        key={identity}
        ref={galleryRef}
        className={`lknscf-gallery lknscf-gallery-${style}`}
        // eslint-disable-next-line react/no-danger
        dangerouslySetInnerHTML={{ __html: buildItemsHtml(images, itemStyle) }}
      />
    </div>
  );
};

export const GalleryEdit = ({ attrs, elements, id, name }) => (
  <ModuleContainer
    attrs={attrs}
    elements={elements}
    id={id}
    name={name}
    scriptDataComponent={ModuleScriptData}
    stylesComponent={ModuleStyles}
    classnamesFunction={moduleClassnames}
  >
    {elements.styleComponents({ attrName: 'module' })}
    <div className="et_pb_module_inner">
      <GalleryPreview attrs={attrs} />
    </div>
  </ModuleContainer>
);
