'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { PromoBannerSettings } from '@/lib/settings';

interface PromoBannerProps {
  settings?: PromoBannerSettings;
  fallbackImages?: string[];
  className?: string;
  style?: React.CSSProperties;
}

export default function PromoBanner({
  settings,
  fallbackImages = ['/promo5.webp'],
  className = '',
  style = {},
}: PromoBannerProps) {
  // If explicitly disabled in settings, do not render
  if (settings && settings.enabled === false) {
    return null;
  }

  // Extract visible images
  const images = useMemo(() => {
    const rawList = settings?.images && Array.isArray(settings.images) && settings.images.length > 0
      ? settings.images
      : fallbackImages;

    const visibleList = rawList
      .map((item: any) => {
        if (typeof item === 'string') return item.trim();
        if (item && typeof item === 'object') {
          const isVis = item.visible !== false && item.visible !== 0 && item.visible !== '0';
          return isVis && item.url ? String(item.url).trim() : '';
        }
        return '';
      })
      .filter((url): url is string => Boolean(url && url.length > 0));

    return visibleList.length > 0 ? visibleList : ['/promo5.webp'];
  }, [settings?.images, fallbackImages]);

  const [currentIndex, setCurrentIndex] = useState(0);

  // Auto-slide carousel if there are multiple images (no arrows or buttons needed)
  useEffect(() => {
    if (images.length <= 1) return;

    const interval = setInterval(() => {
      setCurrentIndex((prev) => (prev + 1) % images.length);
    }, 4500); // 4.5 seconds per slide for a comfortable reading rhythm

    return () => clearInterval(interval);
  }, [images.length]);

  return (
    <div
      className={`promo-banner-wrapper ${className}`.trim()}
      style={{
        width: '100%',
        margin: '0 0 20px 0',
        overflow: 'hidden',
        borderRadius: '16px',
        boxShadow: '0 2px 10px rgba(0, 0, 0, 0.04)',
        aspectRatio: '2033 / 774',
        position: 'relative',
        backgroundColor: '#f1f5f9',
        ...style,
      }}
    >
      {images.map((imgSrc, idx) => {
        const isActive = idx === currentIndex;
        return (
          <div
            key={`${imgSrc}-${idx}`}
            style={{
              position: 'absolute',
              inset: 0,
              width: '100%',
              height: '100%',
              opacity: images.length === 1 ? 1 : isActive ? 1 : 0,
              transition: 'opacity 0.8s ease-in-out',
              pointerEvents: isActive ? 'auto' : 'none',
            }}
          >
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={imgSrc}
              alt="Promotion Banner"
              width={2033}
              height={774}
              loading={idx === 0 ? 'eager' : 'lazy'}
              style={{
                width: '100%',
                height: '100%',
                objectFit: 'cover',
                display: 'block',
              }}
              onError={(e) => {
                const target = e.currentTarget;
                if (!target.src.endsWith('/promo5.webp')) {
                  target.src = '/promo5.webp';
                }
              }}
            />
          </div>
        );
      })}
      {/* Optional text overlay from plugin settings */}
      {(settings?.title || settings?.subtitle || settings?.btn_text) && (
        <div
          style={{
            position: 'absolute',
            inset: 0,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center',
            padding: 'clamp(20px, 5vw, 48px)',
            background: 'linear-gradient(90deg, rgba(0,0,0,0.45) 0%, rgba(0,0,0,0.15) 55%, transparent 100%)',
            color: '#fff',
            pointerEvents: 'none',
          }}
        >
          {settings?.title && (
            <h2 style={{ fontSize: 'clamp(20px, 3.5vw, 34px)', fontWeight: 800, margin: '0 0 8px', pointerEvents: 'auto' }}>
              {settings.title}
            </h2>
          )}
          {settings?.subtitle && (
            <p style={{ fontSize: 'clamp(13px, 1.8vw, 16px)', margin: '0 0 14px', maxWidth: '52ch', pointerEvents: 'auto' }}>
              {settings.subtitle}
            </p>
          )}
          {settings?.btn_text && (
            <a
              href={settings.btn_link || '/shop'}
              className="btn btn-pri"
              style={{ alignSelf: 'flex-start', pointerEvents: 'auto' }}
            >
              {settings.btn_text}
            </a>
          )}
        </div>
      )}
    </div>
  );
}
