'use client';

import { useMemo } from 'react';
import { getPricingPlans, getCountries } from './data';
import Image from 'next/image';
import { motion } from 'framer-motion';
import { Cpu, Gauge, HardDrive, MemoryStick, Server } from 'lucide-react';
import { useTranslator } from '@/contexts/TranslatorContext';
import { useCurrency } from '@/contexts/CurrencyContext';
import { useLivePrices } from '@/hooks/useLivePrices';

export default function Pricing() {
  const { translations, lang } = useTranslator();
  const { symbol, priceFor } = useCurrency();
  
  // Ensure translations object exists
  const safeTranslations = translations || {};
  
  const basePlans = useMemo(() => getPricingPlans(safeTranslations), [lang]);
  const pricingPlans = useLivePrices(basePlans);
  const navCountries = getCountries(safeTranslations);

  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.1,
        delayChildren: 0.2,
      },
    },
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: {
      opacity: 1,
      y: 0,
      transition: { duration: 0.6 },
    },
  };

  const specIcons = [Cpu, HardDrive, MemoryStick, Gauge, MemoryStick, Server];

  return (
    <motion.section 
      id="plans" 
      className="pb-12 sm:pb-16 md:pb-20 pt-28 sm:pt-36 md:pt-44 relative overflow-hidden" 
      dir="rtl" 
      initial={{ opacity: 0 }}
      whileInView={{ opacity: 1 }}
      transition={{ duration: 0.6 }}
      viewport={{ once: true, margin: '-100px' }}
    >
      <Image
        src="/images/bg.svg"
        alt=""
        width={1432}
        height={573}
        priority
        className="absolute -top-32 sm:-top-48 md:-top-64 w-full h-auto pointer-events-none select-none -z-10 opacity-90"
        aria-hidden
      />
      <div className="absolute inset-0 bg-white/5 z-0"></div>

      <div className="max-w-[1240px] mx-auto px-4 sm:px-6 md:px-8 relative z-10">
        {/* Section Header */}
        <motion.div 
          className="text-center mb-10 sm:mb-12"
          initial={{ opacity: 0, y: 30 }}
          whileInView={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.6 }}
          viewport={{ once: true }}>
          <div className="flex items-center justify-center gap-3 mb-8 sm:mb-10">
            <span className="inline-flex items-center justify-center w-10 h-10 rounded-full bg-[#0d1e4e]/10 text-[#0d1e4e]">
              <Server className="w-5 h-5" />
            </span>
            <h2 className="text-xl sm:text-[32px] font-bold text-[#092346]">
              {safeTranslations?.['full_servers']?.['header'] || 
               safeTranslations?.['full_servers.header'] || 
               'خطط و أسعار استضافة الخادم المخصص'}
            </h2>
          </div>

          {/* Country Flags Selector */}
          <div className="flex justify-center">
            <motion.div 
              className="inline-flex items-center gap-2 sm:gap-4 bg-white rounded-full px-6 py-3 shadow-md border border-gray-100"
              initial={{ opacity: 0, scale: 0.9 }}
              whileInView={{ opacity: 1, scale: 1 }}
              transition={{ duration: 0.5, delay: 0.2 }}
              viewport={{ once: true }}>
              {navCountries.map((country, index) => (
                <button
                  key={country.code}
                  className={`flex items-center gap-3 px-4 py-2 rounded-full transition-all duration-300 ${
                    index === 0 ? 'bg-[#2563eb] text-white' : 'text-[#4b5563] hover:bg-gray-50'
                  }`}
                >
                  <span className="text-[14px] font-bold hidden sm:inline">{country.name}</span>
                  <div className="w-8 h-8 rounded-full overflow-hidden flex-shrink-0 shadow-sm border border-gray-100">
                    <Image
                      src={country.flag}
                      width={32}
                      height={32}
                      className="w-full h-full object-cover"
                      alt={country.name}
                    />
                  </div>
                </button>
              ))}
            </motion.div>
          </div>
        </motion.div>

        {/* Pricing Cards Container */}
        <motion.div 
          className="space-y-4 sm:space-y-5 md:space-y-6 relative z-10"
          variants={containerVariants}
          initial="hidden"
          whileInView="visible"
          viewport={{ once: true }}
        >
          {pricingPlans.map((plan) => (
            <motion.div
              key={plan.id}
              className="border border-[#e2e9ee] bg-white rounded-lg overflow-hidden"
              variants={itemVariants}
              whileHover={{ scale: 1.01, boxShadow: '0 10px 30px rgba(0,0,0,0.1)' }}
            >
              {/* Top Row: 3 Columns from Right to Left */}
              <div className="grid grid-cols-1 md:grid-cols-3 border-b border-[#e2e9ee]">
                {/* Right Column: Server Info */}
                <div className="p-4 sm:p-5 md:p-6 flex flex-col justify-between items-start text-right border-b md:border-b-0 md:border-l border-[#e2e9ee] min-h-auto md:min-h-[160px]">
                  <div className="flex flex-col items-start w-full h-full justify-center">
                    <h3 className="font-bold text-[#2b2b2b] text-base sm:text-lg mb-1">{plan.name}</h3>
                    <span className="text-[11px] font-medium text-[#3e3e3e] mb-3 sm:mb-4">{plan.category}</span>
                    <div className="flex items-center gap-2 mt-3">
                        {plan.flags.map((flag, idx) => (
                             <div
                               key={idx}
                               className="w-8 h-8 sm:w-9 sm:h-9 rounded-full overflow-hidden border border-gray-200 shadow-sm"
                             >
                               <Image 
                                 src={flag} 
                                 width={36} 
                                 height={36} 
                                 alt="Flag" 
                                 className="w-full h-full object-cover"
                               />
                             </div>
                        ))}
                    </div>
                  </div>
                </div>

                 {/* Combined Price & Action Column */}
                 <div className="col-span-1 md:col-span-2 p-4 sm:p-5 md:p-6 flex flex-col justify-center items-center text-center min-h-auto md:min-h-[160px]">
                  <div className="flex flex-col items-center justify-center w-full max-w-lg">
                     <div className="flex items-baseline gap-1 mb-1" dir="ltr">
                        <span className="text-[10px] sm:text-[11px] text-[#3e3e3e] font-medium align-top">
                          {symbol}
                        </span>
                        <span className="text-2xl sm:text-3xl font-bold text-[#2b2b2b]">{priceFor(plan.prices)}</span>
                     </div>
                     <span className="text-[9px] sm:text-[10px] text-[#717171] mb-4 sm:mb-6">
                       {safeTranslations?.['full_servers']?.['renewal_note'] || 
                        safeTranslations?.['full_servers.renewal_note'] || 
                        '20 ر.س/ش عند التجديد'}
                     </span>
                     
                     <div className="flex flex-col sm:flex-row w-full gap-3 sm:gap-4">
                       {plan.link ? (
                         <motion.a
                           href={plan.link}
                           target="_blank"
                           rel="noopener noreferrer"
                           className="w-full sm:flex-1 py-2 sm:py-2.5 bg-[#092346] text-white font-bold text-xs sm:text-[13px] rounded hover:bg-[#1a3a6c] transition-all duration-300 shadow-md hover:shadow-lg text-center"
                           whileHover={{ scale: 1.02 }}
                           whileTap={{ scale: 0.98 }}>
                            {safeTranslations?.['full_servers']?.['buttons']?.['subscribe'] || 
                             safeTranslations?.['full_servers.buttons.subscribe'] || 
                             'اشترك الان'}
                         </motion.a>
                       ) : (
                         <motion.button 
                           className="w-full sm:flex-1 py-2 sm:py-2.5 bg-[#092346] text-white font-bold text-xs sm:text-[13px] rounded hover:bg-[#1a3a6c] transition-all duration-300 shadow-md hover:shadow-lg"
                           whileHover={{ scale: 1.02 }}
                           whileTap={{ scale: 0.98 }}>
                            {safeTranslations?.['full_servers']?.['buttons']?.['subscribe'] || 
                             safeTranslations?.['full_servers.buttons.subscribe'] || 
                             'اشترك الان'}
                         </motion.button>
                       )}
                       <motion.button 
                         className="w-full sm:flex-1 py-2 sm:py-2.5 border border-[#0d1e4e] text-[#0d1e4e] font-medium text-[11px] sm:text-[12px] rounded hover:bg-[#0d1e4e] hover:text-white transition-all duration-300"
                         whileHover={{ scale: 1.02 }}
                         whileTap={{ scale: 0.98 }}>
                          {safeTranslations?.['full_servers']?.['buttons']?.['features'] || 
                           safeTranslations?.['full_servers.buttons.features'] || 
                           'المميزات'}
                       </motion.button>
                     </div>
                  </div>
                </div>
              </div>

               {/* Specs Grid */}
               <div className="bg-[#e2e9ee] gap-[1px] grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3" dir="rtl">
                  {plan.specs.map((spec, idx) => (
                      <motion.div 
                       key={idx} 
                       className="bg-[#fcfcfc] p-4 sm:p-5 md:p-6 flex items-center gap-2 sm:gap-3 hover:bg-white transition-colors duration-300"
                       initial={{ opacity: 0, y: 20 }}
                       whileInView={{ opacity: 1, y: 0 }}
                       transition={{ duration: 0.4, delay: idx * 0.05 }}
                       viewport={{ once: true }}
                       whileHover={{ scale: 1.02, transition: { duration: 0.2 } }}>
                        {(() => {
                          const Icon = specIcons[idx] || Server;
                          return (
                           <motion.div
                            className="w-8 h-8 sm:w-10 sm:h-10 flex-shrink-0 flex items-center justify-center text-[#2563eb]"
                            whileHover={{ rotate: 360 }}
                            transition={{ duration: 0.5 }}>
                            <Icon className="w-6 h-6" aria-hidden />
                           </motion.div>
                          );
                        })()}
                        <div className="flex-1 flex flex-col text-right">
                          <span className="text-[12px] sm:text-[13px] font-bold text-[#2b2b2b] mb-1">{spec.label}</span>
                          <span className="text-[10px] sm:text-[11px] text-[#717171] leading-tight">{spec.value}</span>
                          {spec.subValue && (
                            <span className="text-[9px] sm:text-[10px] text-[#9ca3af] leading-tight mt-0.5">{spec.subValue}</span>
                          )}
                        </div>
                      </motion.div>
                  ))}
               </div>
            </motion.div>
          ))}
        </motion.div>
      </div>
    </motion.section>
  );
}
