"use client";
import React, { useState, useEffect, useRef } from 'react';
import Image from 'next/image';
import { useCurrency } from "../app/context/CurrencyContext"; 

const parsePrice = (value: any): number => {
  const parsed = parseFloat(String(value ?? "0"));
  return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
};

const formatPrice = (value: number, curr: string): string => {
  return value.toLocaleString(curr === "PKR" ? "en-PK" : "en-US", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });
};

const SkeletonCard = () => (
  <div className="min-w-full sm:min-w-[48%] lg:min-w-[31.5%] bg-white border border-gray-100 rounded-[40px] p-8 md:p-10 shadow-sm animate-pulse">
    <div className="h-10 w-32 bg-gray-200 rounded-md mb-4"></div>
    <div className="h-12 w-full bg-gray-200 rounded-lg mb-8"></div>
  </div>
);

const WordPressPricing: React.FC = () => {
  const [plans, setPlans] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeIndex, setActiveIndex] = useState(0);
  const carouselRef = useRef<HTMLDivElement>(null);
  const { currency, symbol, isLoading: isCurrencyLoading } = useCurrency();

  const categories = [
    { name: "Shared Hosting", active: false },
    { name: "WordPress Hosting", active: true },
    { name: "Cloud Hosting", active: false },
    { name: "VPS Hosting", active: false },
    { name: "Dedicated Server", active: false },
  ];

  const cleanDescription = (html: string) => {
    if (!html) return "";
    return html.replace(/-{3,}/g, "").replace(/<hr\s*\/?>/gi, "");
  };

  useEffect(() => {
    const fetchWordPressPlans = async () => {
      setLoading(true);
      try {
        const response = await fetch("/api/zt-hosting?keyword=wordpress");
        const data = await response.json();
        if (data.packages) {
          const formatted = data.packages.map((pkg: any) => {
            const selectedPricing = pkg.pricing?.[currency] || pkg.pricing?.PKR;
            const monthlyNormal = selectedPricing ? parsePrice(selectedPricing.monthly) : parsePrice(pkg.price);
            const triennialTotal = selectedPricing ? parsePrice(selectedPricing.triennially) : 0;
            const annualTotal = selectedPricing ? parsePrice(selectedPricing.annually) : monthlyNormal * 12;
            let mainMonthlyPrice = monthlyNormal;
            if (triennialTotal > 0) mainMonthlyPrice = triennialTotal / 36;
            else if (annualTotal > 0) mainMonthlyPrice = annualTotal / 12;
            const discount = monthlyNormal > 0 && mainMonthlyPrice > 0 && mainMonthlyPrice < monthlyNormal
              ? Math.round(((monthlyNormal - mainMonthlyPrice) / monthlyNormal) * 100)
              : 0;
            return {
              ...pkg,
              displayPrice: formatPrice(mainMonthlyPrice, currency),
              oldPrice: formatPrice(monthlyNormal, currency),
              discountTag: discount > 0 ? `Save ${discount}%` : null,
            };
          });
          setPlans(formatted);
        }
      } catch (error) {
        console.error("Fetch Error:", error);
      } finally {
        setLoading(false);
      }
    };
    fetchWordPressPlans();
  }, [currency]);

  const repeatedPlans = [...plans, ...plans, ...plans];

  useEffect(() => {
    let ticking = false;

    const handleScroll = () => {
      if (!carouselRef.current) return;

      if (!ticking) {
        window.requestAnimationFrame(() => {
          const container = carouselRef.current;
          if (!container) {
            ticking = false;
            return;
          }
          
          const center = container.scrollLeft + container.clientWidth / 2;
          const children = Array.from(container.children);
          
          let closestIndex = 0;
          let minDistance = Infinity;

          children.forEach((child: any, index) => {
            const childCenter = child.offsetLeft + child.clientWidth / 2;
            const distance = Math.abs(center - childCenter);
            if (distance < minDistance) {
              minDistance = distance;
              closestIndex = index;
            }
          });
          
          setActiveIndex(closestIndex);
          ticking = false;
        });

        ticking = true;
      }
    };

    const container = carouselRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll, { passive: true });
      // Trigger once on mount to establish the correct active card
      handleScroll();
      return () => container.removeEventListener('scroll', handleScroll);
    }
  }, [plans]);

  const PricingCard = ({ plan, index }: { plan: any; index: number }) => {
    const isActive = activeIndex === index;
    return (
      <div 
        className={`min-w-[85%] sm:min-w-[48%] lg:min-w-[31.5%] border rounded-[30px] md:rounded-[40px] p-6 md:p-10 relative overflow-hidden flex flex-col transition-transform transition-shadow transition-colors duration-700 ease-out will-change-transform snap-center
        ${isActive 
            ? 'scale-[1.03] md:scale-[1.06] shadow-[0_30px_60px_rgba(127,0,255,0.25)] z-20 border-transparent bg-[#7F00FF] text-white' 
            : 'scale-100 shadow-sm z-10 border-gray-100 bg-white text-[#1E1B4B]'}`}
      >
        <div className={`absolute inset-0 w-full h-full pointer-events-none z-0 transition-opacity duration-1000 ${isActive ? 'opacity-20' : 'opacity-40'}`}>
           <Image src="/Frame 290.png" alt="BG" fill className="object-cover" />
        </div>

        {plan.discountTag && (
          <div className={`absolute top-4 md:top-8 right-4 md:right-8 text-[10px] font-black px-3 md:px-4 py-1.5 rounded-full uppercase tracking-widest z-10 shadow-lg transition-colors duration-700 ${isActive ? 'bg-[#FFCE1A] text-black' : 'bg-[#4C0099] text-white'}`}>
            {plan.discountTag}
          </div>
        )}

        <div className="mb-6 md:mb-2 relative z-10 mt-10">
          <div className="flex items-baseline gap-1">
            <span className={`text-xl md:text-2xl font-bold transition-colors duration-700 ${isActive ? 'text-white' : 'text-[#1E1B4B]'}`}>{symbol}</span>
            <span className={`text-4xl md:text-5xl font-black tracking-tighter transition-colors duration-700 ${isActive ? 'text-white' : 'text-[#1E1B4B]'}`}>{plan.displayPrice}</span>
            <span className={`text-lg md:text-xl font-medium transition-colors duration-700 ${isActive ? 'text-white' : 'text-[#1E1B4B]'}`}>/month</span>
          </div>
          {parsePrice(plan.oldPrice.replace(/,/g, "")) > parsePrice(plan.displayPrice.replace(/,/g, "")) && (
            <div className={`text-sm md:text-base font-medium mt-1 transition-colors duration-700 ${isActive ? 'text-white/60' : 'text-gray-400'}`}>
               was <span className="line-through">{symbol} {plan.oldPrice} /month</span>
            </div>
          )}
        </div>

        <h3 className={`text-xl md:text-2xl font-black mb-4 md:mb-6 tracking-tight relative z-10 min-h-[50px] md:min-h-[60px] flex items-center transition-colors duration-700 ${isActive ? 'text-white' : 'text-[#1E1B4B]'}`}>
          {plan.name}
        </h3>

        <div className="relative z-10 mb-6 md:mb-8 pr-2">
          <div className="overflow-y-auto custom-features-scrollbar h-[200px] md:h-[250px]" style={{ scrollBehavior: 'smooth' }}>
            <div className={`prose prose-sm font-bold pricing-list transition-colors duration-700 ${isActive ? 'text-white/90 active-card-list' : 'text-[#1E1B4B]/80'}`} dangerouslySetInnerHTML={{ __html: cleanDescription(plan.description) }} />
          </div>
        </div>

        <a href={plan.product_url || "#"} className={`mt-auto w-full rounded-full py-3 md:py-4 text-center text-sm md:text-base font-black transition-all duration-300 shadow-sm active:scale-95 relative z-10 ${isActive ? 'bg-[#FFCE1A] text-black hover:bg-white hover:text-[#7F00FF]' : 'bg-[#F3E8FF] text-[#7F00FF] hover:bg-[#7F00FF] hover:text-white'}`}>
          Choose Plan
        </a>
      </div>
    );
  };

  return (
    <section className="py-10 md:py-24 bg-[#FDF4FF] font-sans overflow-hidden px-4 sm:px-6 lg:px-[100px]">
      <div className="container mx-auto max-w-[1400px]">
        <div className="max-w-2xl mb-8">
            <h2 className="text-3xl md:text-5xl font-black text-[#1E1B4B] mb-3 md:mb-4">WordPress Optimized Hosting</h2>
            <p className="text-sm md:text-base text-gray-500 font-medium">Ultra-fast NVMe storage with pre-configured WordPress Toolkit for maximum performance.</p>
        </div>
        
        <div 
          ref={carouselRef}
          className="flex flex-row overflow-x-auto pt-12 pb-16 gap-6 md:gap-10 items-center snap-x snap-mandatory scrollbar-premium scroll-smooth px-[5%] sm:px-0"
          style={{ WebkitOverflowScrolling: 'touch' }}
        >
          {loading || isCurrencyLoading ? (
            <>
              <SkeletonCard />
              <SkeletonCard />
              <SkeletonCard />
            </>
          ) : (
            repeatedPlans.map((plan, index) => (
              <PricingCard key={`${plan.pid}-${index}`} plan={plan} index={index} />
            ))
          )}
        </div>

        <div className="text-center mt-12 md:mt-20">
            <h2 className="text-3xl md:text-5xl lg:text-[64px] font-black text-[#1E1B4B] mb-8 md:mb-16 tracking-tight leading-tight">Our All Hosting Plans And Packages</h2>
            <div className="flex flex-nowrap lg:flex-wrap justify-start lg:justify-center gap-3 md:gap-5 max-w-[1200px] mx-auto overflow-x-auto pb-6 lg:pb-0 lg:overflow-x-visible scrollbar-hide px-2">
                {categories.map((cat, idx) => (
                    <button key={idx} className={`px-6 md:px-12 py-3 md:py-5 rounded-full text-[11px] md:text-base font-bold whitespace-nowrap flex-shrink-0 lg:flex-shrink transition-all duration-300 transform hover:-translate-y-1 hover:shadow-2xl ${cat.active ? 'bg-[#7F00FF] text-white border-2 border-[#7F00FF] shadow-xl shadow-[#7F00FF]/30' : 'bg-[#FFCE1A]/10 border-2 border-[#FFCE1A] text-[#1E1B4B] hover:bg-[#7F00FF] hover:text-white hover:border-[#7F00FF] hover:shadow-[#7F00FF]/40'}`}>{cat.name}</button>
                ))}
            </div>
        </div>
      </div>

      <style jsx global>{`
        .pricing-list li { position: relative; padding-left: 28px; margin-bottom: 10px; font-size: 13px; line-height: 1.4; transition: color 0.7s ease; }
        .pricing-list li::before { content: '✓'; position: absolute; left: 0; top: 2px; width: 18px; height: 18px; background: rgba(127, 0, 255, 0.1); color: #7F00FF; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 9px; font-weight: bold; transition: all 0.7s ease; }
        
        .active-card-list li::before { background: rgba(255, 255, 255, 0.2); color: white; }

        .custom-features-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-features-scrollbar::-webkit-scrollbar-thumb { background: #dcd0ff; border-radius: 10px; }
        .scrollbar-premium::-webkit-scrollbar { height: 4px; }
        .scrollbar-premium::-webkit-scrollbar-thumb { background: #7F00FF; border-radius: 10px; }
        .scrollbar-hide::-webkit-scrollbar { display: none; }
        .scrollbar-hide { -ms-overflow-style: none; scrollbar-width: none; }
      `}</style>
    </section>
  );
};

export default WordPressPricing;