'use client';

/* eslint @suno-custom/no-tailwind-color-in-classnames: warn */
import { useEffect, useState } from 'react';

interface SectionInfo {
  ref: React.RefObject<HTMLDivElement | null>;
  key: string;
  bgColor: string;
  hasBlur: boolean;
  fadeStart: number;
  fadeEnd: number;
  fadeMode: 'percentage' | 'viewport';
}

interface ScrollPercentageDebugProps {
  sections: SectionInfo[];
  enabled?: boolean;
}

interface SectionScrollData {
  key: string;
  scrollPercent: number;
  fadeStart: number;
  fadeEnd: number;
  fadeMode: 'percentage' | 'viewport';
  isActive: boolean;
  isInFadeZone: boolean;
  nextSectionDistance?: number; // Distance to next section (for viewport mode)
}

export const ScrollPercentageDebug: React.FC<ScrollPercentageDebugProps> = ({
  sections,
  enabled = true,
}) => {
  const [sectionData, setSectionData] = useState<SectionScrollData[]>([]);

  useEffect(() => {
    if (!enabled) return;

    const scrollContainer = document.querySelector(
      '.h-dvh.w-full.overflow-x-hidden'
    );
    if (!scrollContainer) return;

    const handleScroll = () => {
      const scrollTop = scrollContainer.scrollTop;
      const containerHeight = scrollContainer.clientHeight;
      const newSectionData: SectionScrollData[] = [];

      sections.forEach((section, index) => {
        if (!section.ref.current) return;

        const sectionTop = section.ref.current.offsetTop;
        const sectionHeight = section.ref.current.offsetHeight;
        const sectionBottom = sectionTop + sectionHeight;
        const nextSection = sections[index + 1];

        // Calculate scroll percentage within the section
        let scrollPercent = 0;
        if (scrollTop >= sectionTop && scrollTop <= sectionBottom) {
          scrollPercent = Math.min(
            ((scrollTop - sectionTop) / sectionHeight) * 100,
            100
          );
        } else if (scrollTop > sectionBottom) {
          scrollPercent = 100;
        }

        // Check if section is currently active (visible in viewport)
        const isActive =
          sectionTop <= scrollTop + containerHeight &&
          sectionBottom >= scrollTop;

        // Calculate fade zone based on mode
        let fadeStartPoint: number;
        let fadeEndPoint: number;
        let nextSectionDistance: number | undefined;

        if (section.fadeMode === 'viewport' && nextSection?.ref.current) {
          // Viewport mode: based on next section position
          const nextSectionTop = nextSection.ref.current.offsetTop;
          nextSectionDistance = Math.max(
            0,
            nextSectionTop - scrollTop - containerHeight
          );

          fadeStartPoint =
            nextSectionTop - containerHeight * (1 - section.fadeStart);
          fadeEndPoint =
            nextSectionTop - containerHeight * (1 - section.fadeEnd);
        } else {
          // Percentage mode: based on current section
          fadeStartPoint = sectionTop + sectionHeight * section.fadeStart;
          fadeEndPoint = sectionTop + sectionHeight * section.fadeEnd;
        }

        const isInFadeZone =
          scrollTop >= fadeStartPoint && scrollTop <= fadeEndPoint;

        newSectionData.push({
          key: section.key,
          scrollPercent: Math.round(scrollPercent),
          fadeStart: Math.round(section.fadeStart * 100),
          fadeEnd: Math.round(section.fadeEnd * 100),
          fadeMode: section.fadeMode,
          isActive,
          isInFadeZone,
          nextSectionDistance: nextSectionDistance
            ? Math.round(nextSectionDistance)
            : undefined,
        });
      });

      setSectionData(newSectionData);
    };

    handleScroll();
    scrollContainer.addEventListener('scroll', handleScroll, { passive: true });
    return () => scrollContainer.removeEventListener('scroll', handleScroll);
  }, [sections, enabled]);

  if (!enabled) return null;

  return (
    <div className='fixed top-4 right-4 z-[9999] max-h-[80vh] overflow-y-auto rounded-lg border border-white/20 bg-black/90 p-4 font-mono text-xs text-white backdrop-blur-sm'>
      <div className='mb-2 text-sm font-bold text-white'>Scroll Debug</div>
      <div className='space-y-2'>
        {sectionData.map((data) => (
          <div
            key={data.key}
            className={`border-l-2 pl-2 ${
              data.isActive
                ? data.isInFadeZone
                  ? 'border-red-400 bg-red-500/10'
                  : 'border-green-400 bg-green-500/10'
                : 'border-gray-600 bg-gray-500/5'
            }`}
          >
            <div className='flex items-center justify-between'>
              <span className='font-semibold'>{data.key}</span>
              <span
                className={
                  data.isActive
                    ? 'text-foreground-primary'
                    : 'text-foreground-tertiary'
                }
              >
                {data.scrollPercent}%
              </span>
            </div>
            <div className='text-xs text-foreground-tertiary'>
              Mode: {data.fadeMode}
              {data.fadeMode === 'percentage'
                ? ` | Fade: ${data.fadeStart}%-${data.fadeEnd}%`
                : ` | Viewport: ${data.fadeStart}%-${data.fadeEnd}%`}
            </div>
            {data.fadeMode === 'viewport' &&
              data.nextSectionDistance !== undefined && (
                <div className='text-xs text-blue-400'>
                  Next section: {data.nextSectionDistance}px
                </div>
              )}
            {data.isInFadeZone && (
              <div className='text-xs font-bold text-red-400'>IN FADE ZONE</div>
            )}
          </div>
        ))}
      </div>
      <div className='mt-3 border-t border-white/20 pt-2'>
        <div className='text-xs text-foreground-tertiary'>
          <div>🟢 Active section</div>
          <div>🔴 Active + in fade zone</div>
          <div>⚫ Inactive section</div>
          <div className='mt-2'>
            <div>
              <strong>Modes:</strong>
            </div>
            <div>
              • percentage: Fade based on scroll % within current section
            </div>
            <div>
              • viewport: Fade based on next section's % position in viewport
            </div>
            <div className='mt-1 text-xs text-gray-500'>
              (viewport %: 0% = next section at bottom edge, 100% = at top edge)
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
