import React, { useState, useEffect } from 'react';
import { useApp } from '../context/AppContext';
import { X, ExternalLink } from 'lucide-react';

export const FloatingScrollPopup: React.FC = () => {
  const { scrollPopup, openDeveloperModal } = useApp();
  const [isVisible, setIsVisible] = useState(false);
  const [isDismissed, setIsDismissed] = useState(false);

  useEffect(() => {
    if (!scrollPopup.is_enabled || isDismissed) {
      setIsVisible(false);
      return;
    }

    const thresholdPercent = scrollPopup.scroll_threshold_percent ?? 20;

    const handleScroll = () => {
      // Calculate scroll percentage
      const scrollTop = window.scrollY || document.documentElement.scrollTop;
      const docHeight = document.documentElement.scrollHeight - document.documentElement.clientHeight;
      
      if (docHeight <= 0) {
        // Short page or immediate
        setIsVisible(true);
        return;
      }

      const scrollPercentage = (scrollTop / docHeight) * 100;

      if (scrollPercentage >= thresholdPercent) {
        setIsVisible(true);
      } else {
        setIsVisible(false);
      }
    };

    // Run initial check
    handleScroll();

    window.addEventListener('scroll', handleScroll, { passive: true });
    return () => window.removeEventListener('scroll', handleScroll);
  }, [scrollPopup.is_enabled, scrollPopup.scroll_threshold_percent, isDismissed]);

  if (!scrollPopup.is_enabled || isDismissed || !isVisible) {
    return null;
  }

  const handleClick = (e: React.MouseEvent) => {
    if (scrollPopup.target_url && scrollPopup.target_url.trim()) {
      window.open(scrollPopup.target_url, '_blank', 'noopener,noreferrer');
      return;
    }
    openDeveloperModal();
  };

  return (
    <div
      id="floating-scroll-popup"
      className="fixed bottom-5 right-5 z-40 transition-all duration-300 animate-in fade-in slide-in-from-bottom-4 group select-none"
    >
      <div
        onClick={handleClick}
        className="flex items-center gap-2.5 px-4 py-2 sm:px-5 sm:py-2.5 rounded-full shadow-2xl hover:shadow-[0_20px_35px_-5px_rgba(0,0,0,0.3)] hover:scale-105 active:scale-95 transition-all duration-200 cursor-pointer border relative"
        style={{
          backgroundColor: scrollPopup.bg_color || '#FFFFFF',
          borderColor: scrollPopup.border_color || '#F4ECE7',
        }}
      >
        {/* Close Button on Hover */}
        {scrollPopup.show_close_button !== false && (
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              setIsDismissed(true);
            }}
            className="absolute -top-1.5 -left-1.5 w-5 h-5 rounded-full bg-slate-800 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-rose-600 shadow-md cursor-pointer text-xs"
            title="Dismiss popup"
          >
            <X className="w-3 h-3" />
          </button>
        )}

        {/* Text Content */}
        <div className="flex items-center gap-1.5 font-medium text-xs sm:text-sm tracking-tight whitespace-nowrap">
          <span
            style={{ color: scrollPopup.prefix_color || '#64748B' }}
            className="font-medium"
          >
            {scrollPopup.prefix_text || 'Built by'}
          </span>
          <span
            style={{ color: scrollPopup.author_color || '#E07A5F' }}
            className="font-semibold hover:underline"
          >
            {scrollPopup.author_text || '@jonathanwilke'}
          </span>
        </div>

        {/* Avatar Image */}
        {scrollPopup.avatar_image_url && (
          <img
            src={scrollPopup.avatar_image_url}
            alt={scrollPopup.author_text || 'Avatar'}
            referrerPolicy="no-referrer"
            className="w-7 h-7 sm:w-8 sm:h-8 rounded-full object-cover shrink-0 border border-black/10 shadow-sm"
          />
        )}
      </div>
    </div>
  );
};
