"use client";

import { useState, useEffect, useRef } from "react";
import { useLanguage } from "@/contexts/LanguageContext";
import Link from "next/link";

interface PlanFeature {
  name: string;
  included: boolean;
  value?: string;
  infoKey: string;
}

interface Plan {
  id: string;
  name: string;
  monthlyPrice: number;
  yearlyPrice: number;
  description: string;
  popular?: boolean;
  features: PlanFeature[];
}

interface CurrencyRate {
  code: string;
  symbol: string;
  rate: number;
  name: string;
}

// Currency rates (USD as base = 1)
const currencyRates: Record<string, CurrencyRate> = {
  US: { code: "USD", symbol: "$", rate: 1, name: "US Dollar" },
  SA: { code: "SAR", symbol: "ر.س", rate: 3.75, name: "Saudi Riyal" },
  AE: { code: "AED", symbol: "د.إ", rate: 3.67, name: "UAE Dirham" },
  EG: { code: "EGP", symbol: "ج.م", rate: 30.9, name: "Egyptian Pound" },
  GB: { code: "GBP", symbol: "£", rate: 0.79, name: "British Pound" },
  EU: { code: "EUR", symbol: "€", rate: 0.92, name: "Euro" },
  KW: { code: "KWD", symbol: "د.ك", rate: 0.31, name: "Kuwaiti Dinar" },
  QA: { code: "QAR", symbol: "ر.ق", rate: 3.64, name: "Qatari Riyal" },
  BH: { code: "BHD", symbol: "د.ب", rate: 0.38, name: "Bahraini Dinar" },
  OM: { code: "OMR", symbol: "ر.ع", rate: 0.38, name: "Omani Rial" },
  JO: { code: "JOD", symbol: "د.أ", rate: 0.71, name: "Jordanian Dinar" },
  MA: { code: "MAD", symbol: "د.م", rate: 10.1, name: "Moroccan Dirham" },
  DZ: { code: "DZD", symbol: "د.ج", rate: 240, name: "Algerian Dinar" },
  TN: { code: "TND", symbol: "د.ت", rate: 3.1, name: "Tunisian Dinar" },
  IN: { code: "INR", symbol: "₹", rate: 83.1, name: "Indian Rupee" },
  PK: { code: "PKR", symbol: "Rs", rate: 278.5, name: "Pakistani Rupee" },
  TR: { code: "TRY", symbol: "₺", rate: 32.1, name: "Turkish Lira" },
  CA: { code: "CAD", symbol: "C$", rate: 1.36, name: "Canadian Dollar" },
  AU: { code: "AUD", symbol: "A$", rate: 1.53, name: "Australian Dollar" },
};

const defaultCurrency = currencyRates.US;

export default function PricingHomeTwo() {
  const { t, language } = useLanguage();
  const [isYearly, setIsYearly] = useState(false);
  const [currency, setCurrency] = useState<CurrencyRate>(defaultCurrency);
  const [showCalculator, setShowCalculator] = useState(false);
  const [isLoadingCurrency, setIsLoadingCurrency] = useState(true);
  const sectionRef = useRef<HTMLElement>(null);

  // Calculator state
  const [calcValues, setCalcValues] = useState({
    teamMembers: 1,
    contacts: 300,
    conversations: 400,
    aiResponses: 1000,
    aiTickets: 150,
    sitePages: 20,
    flowCreators: 20,
    mediaFiles: 20,
    knowledgeBases: 3,
    channels: 1,
    webChat: false,
    paymentLinks: false,
    bookingsTables: false,
  });

  // Detect country from IP using multiple fallback services
  useEffect(() => {
    const detectCountry = async () => {
      setIsLoadingCurrency(true);
      
      // List of IP geolocation services to try (all support CORS)
      const services = [
        {
          url: 'https://api.country.is/',
          getCountry: (data: { country: string }) => data.country
        },
        {
          url: 'https://ipwho.is/',
          getCountry: (data: { country_code: string }) => data.country_code
        },
        {
          url: 'https://freeipapi.com/api/json',
          getCountry: (data: { countryCode: string }) => data.countryCode
        }
      ];

      for (const service of services) {
        try {
          const controller = new AbortController();
          const timeoutId = setTimeout(() => controller.abort(), 3000);
          
          const response = await fetch(service.url, { 
            signal: controller.signal,
            mode: 'cors'
          });
          clearTimeout(timeoutId);
          
          if (response.ok) {
            const data = await response.json();
            const countryCode = service.getCountry(data);
            
            if (countryCode && currencyRates[countryCode]) {
              setCurrency(currencyRates[countryCode]);
              setIsLoadingCurrency(false);
              return;
            }
          }
        } catch (error) {
          // Try next service
          continue;
        }
      }
      
      // Default to USD if all services fail
      setCurrency(defaultCurrency);
      setIsLoadingCurrency(false);
    };
    
    detectCountry();
  }, []);

  // Calculate estimated price based on usage - realistic pricing model
  const calculateEstimatedPrice = () => {
    // Unit prices as specified
    const prices = {
      teamMembers: 4,        // $4 per team member
      contacts: 0.0015,      // $0.0015 per contact
      conversations: 0.0005, // $0.0005 per conversation
      aiResponses: 0.03,     // $0.03 per AI response
      aiTickets: 0.005,      // $0.005 per AI ticket
      sitePages: 0.01,       // $0.01 per scraped page
      flowCreators: 0.01,    // $0.01 per flow creator
      mediaFiles: 0.02,      // $0.02 per media file
      knowledgeBases: 0.5,   // $0.50 per knowledge base
      channels: 5,           // $5 per channel (max 4)
      webChat: 6,            // $6 flat fee if enabled
      paymentLinks: 8,       // $8 flat fee if enabled
      bookingsTables: 5,     // $5 flat fee if enabled
    };

    let total = 0;
    
    // Team members
    total += calcValues.teamMembers * prices.teamMembers;
    
    // Usage-based pricing
    total += calcValues.contacts * prices.contacts;
    total += calcValues.conversations * prices.conversations;
    total += calcValues.aiResponses * prices.aiResponses;
    total += calcValues.aiTickets * prices.aiTickets;
    total += calcValues.sitePages * prices.sitePages;
    total += calcValues.flowCreators * prices.flowCreators;
    total += calcValues.mediaFiles * prices.mediaFiles;
    
    // Knowledge bases (direct pricing)
    total += calcValues.knowledgeBases * prices.knowledgeBases;
    
    // Channels (max 4)
    total += Math.min(calcValues.channels, 4) * prices.channels;
    
    // Add-ons
    if (calcValues.webChat) total += prices.webChat;
    if (calcValues.paymentLinks) total += prices.paymentLinks;
    if (calcValues.bookingsTables) total += prices.bookingsTables;

    return Math.round(total);
  };

  const plans: Plan[] = [
    {
      id: "basic",
      name: t("pricing.basic.name"),
      monthlyPrice: 10,
      yearlyPrice: 100,
      description: t("pricing.basic.description"),
      features: [
        { name: t("pricing.feature.teamMembers"), included: true, value: "1", infoKey: "teamMembers" },
        { name: t("pricing.feature.connections"), included: true, value: "50", infoKey: "connections" },
        { name: t("pricing.feature.conversations"), included: true, value: "100", infoKey: "conversations" },
        { name: t("pricing.feature.aiResponses"), included: true, value: "200", infoKey: "aiResponses" },
        { name: t("pricing.feature.aiTickets"), included: true, value: "25", infoKey: "aiTickets" },
        { name: t("pricing.feature.sitePages"), included: true, value: "5", infoKey: "sitePages" },
        { name: t("pricing.feature.flowCreators"), included: true, value: "3", infoKey: "flowCreators" },
        { name: t("pricing.feature.mediaFiles"), included: true, value: "5", infoKey: "mediaFiles" },
        { name: t("pricing.feature.knowledgeBases"), included: true, value: "1", infoKey: "knowledgeBases" },
        { name: t("pricing.feature.channels"), included: true, value: "1", infoKey: "channels" },
        { name: t("pricing.feature.paymentLinks"), included: false, infoKey: "paymentLinks" },
        { name: t("pricing.feature.bookingsTables"), included: false, infoKey: "bookingsTables" },
        { name: t("pricing.feature.webChat"), included: false, infoKey: "webChat" },
        { name: t("pricing.feature.voiceMessages"), included: false, infoKey: "voiceMessages" },
      ],
    },
    {
      id: "starter",
      name: t("pricing.starter.name"),
      monthlyPrice: 49,
      yearlyPrice: 490,
      description: t("pricing.starter.description"),
      features: [
        { name: t("pricing.feature.teamMembers"), included: true, value: "1", infoKey: "teamMembers" },
        { name: t("pricing.feature.connections"), included: true, value: "300", infoKey: "connections" },
        { name: t("pricing.feature.conversations"), included: true, value: "400", infoKey: "conversations" },
        { name: t("pricing.feature.aiResponses"), included: true, value: "1,000", infoKey: "aiResponses" },
        { name: t("pricing.feature.aiTickets"), included: true, value: "150", infoKey: "aiTickets" },
        { name: t("pricing.feature.sitePages"), included: true, value: "20", infoKey: "sitePages" },
        { name: t("pricing.feature.flowCreators"), included: true, value: "20", infoKey: "flowCreators" },
        { name: t("pricing.feature.mediaFiles"), included: true, value: "20", infoKey: "mediaFiles" },
        { name: t("pricing.feature.knowledgeBases"), included: true, value: "3", infoKey: "knowledgeBases" },
        { name: t("pricing.feature.channels"), included: true, value: "1", infoKey: "channels" },
        { name: t("pricing.feature.paymentLinks"), included: false, infoKey: "paymentLinks" },
        { name: t("pricing.feature.bookingsTables"), included: false, infoKey: "bookingsTables" },
        { name: t("pricing.feature.webChat"), included: false, infoKey: "webChat" },
        { name: t("pricing.feature.voiceMessages"), included: true, infoKey: "voiceMessages" },
      ],
    },
    {
      id: "professional",
      name: t("pricing.professional.name"),
      monthlyPrice: 65,
      yearlyPrice: 650,
      description: t("pricing.professional.description"),
      popular: true,
      features: [
        { name: t("pricing.feature.teamMembers"), included: true, value: "2", infoKey: "teamMembers" },
        { name: t("pricing.feature.connections"), included: true, value: "700", infoKey: "connections" },
        { name: t("pricing.feature.conversations"), included: true, value: "900", infoKey: "conversations" },
        { name: t("pricing.feature.aiResponses"), included: true, value: "2,000", infoKey: "aiResponses" },
        { name: t("pricing.feature.aiTickets"), included: true, value: "350", infoKey: "aiTickets" },
        { name: t("pricing.feature.sitePages"), included: true, value: "40", infoKey: "sitePages" },
        { name: t("pricing.feature.flowCreators"), included: true, value: "40", infoKey: "flowCreators" },
        { name: t("pricing.feature.mediaFiles"), included: true, value: "50", infoKey: "mediaFiles" },
        { name: t("pricing.feature.knowledgeBases"), included: true, value: "8", infoKey: "knowledgeBases" },
        { name: t("pricing.feature.channels"), included: true, value: "2", infoKey: "channels" },
        { name: t("pricing.feature.paymentLinks"), included: true, infoKey: "paymentLinks" },
        { name: t("pricing.feature.bookingsTables"), included: false, infoKey: "bookingsTables" },
        { name: t("pricing.feature.webChat"), included: true, infoKey: "webChat" },
        { name: t("pricing.feature.voiceMessages"), included: true, infoKey: "voiceMessages" },
      ],
    },
    {
      id: "premium",
      name: t("pricing.premium.name"),
      monthlyPrice: 99,
      yearlyPrice: 990,
      description: t("pricing.premium.description"),
      features: [
        { name: t("pricing.feature.teamMembers"), included: true, value: "5", infoKey: "teamMembers" },
        { name: t("pricing.feature.connections"), included: true, value: "1,500", infoKey: "connections" },
        { name: t("pricing.feature.conversations"), included: true, value: "2,000", infoKey: "conversations" },
        { name: t("pricing.feature.aiResponses"), included: true, value: "3,500", infoKey: "aiResponses" },
        { name: t("pricing.feature.aiTickets"), included: true, value: "700", infoKey: "aiTickets" },
        { name: t("pricing.feature.sitePages"), included: true, value: "80", infoKey: "sitePages" },
        { name: t("pricing.feature.flowCreators"), included: true, value: "80", infoKey: "flowCreators" },
        { name: t("pricing.feature.mediaFiles"), included: true, value: "100", infoKey: "mediaFiles" },
        { name: t("pricing.feature.knowledgeBases"), included: true, value: "15", infoKey: "knowledgeBases" },
        { name: t("pricing.feature.channels"), included: true, value: "3", infoKey: "channels" },
        { name: t("pricing.feature.paymentLinks"), included: true, infoKey: "paymentLinks" },
        { name: t("pricing.feature.bookingsTables"), included: true, infoKey: "bookingsTables" },
        { name: t("pricing.feature.webChat"), included: true, infoKey: "webChat" },
        { name: t("pricing.feature.voiceMessages"), included: true, infoKey: "voiceMessages" },
      ],
    },
  ];

  const roundDzd = (price: number) => Math.round(price / 500) * 500;

  const convertPrice = (usdPrice: number) => {
    const raw = Math.round(usdPrice * currency.rate);
    if (currency.code === "DZD") return roundDzd(raw);
    return raw;
  };

  const formatPrice = (price: number) => {
    if (currency.code === "DZD") return price.toString();
    if (price >= 1000) {
      return price.toLocaleString();
    }
    return price.toString();
  };

  const getPrice = (plan: Plan) => {
    const basePrice = isYearly ? plan.yearlyPrice : plan.monthlyPrice;
    return formatPrice(convertPrice(basePrice));
  };

  const getSavings = (plan: Plan) => {
    const monthlyCost = plan.monthlyPrice * 12;
    const yearlyCost = plan.yearlyPrice;
    return formatPrice(convertPrice(monthlyCost - yearlyCost));
  };

  return (
    <section
      className="azzle-pricing-section"
      id="pricing"
      ref={sectionRef}
    >
      <style jsx>{`
        .azzle-pricing-section {
          padding: 100px 0;
          background: linear-gradient(180deg, #0a0f1c 0%, #111827 50%, #0a0f1c 100%);
          position: relative;
          overflow: hidden;
        }

        .azzle-pricing-section::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: 
            radial-gradient(ellipse 80% 50% at 50% 0%, rgba(50, 28, 164, 0.18) 0%, transparent 50%),
            radial-gradient(ellipse 60% 40% at 100% 100%, rgba(102, 16, 242, 0.12) 0%, transparent 50%),
            radial-gradient(ellipse 60% 40% at 0% 100%, rgba(16, 185, 129, 0.1) 0%, transparent 50%);
          pointer-events: none;
        }

        .pricing-header {
          text-align: center;
          margin-bottom: 40px;
          position: relative;
          z-index: 1;
        }

        .pricing-header h2 {
          font-size: 42px;
          font-weight: 700;
          color: #fff;
          margin-bottom: 16px;
          background: linear-gradient(135deg, #fff 0%, #a78bfa 100%);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
          background-clip: text;
        }

        .pricing-header p {
          font-size: 18px;
          color: #9ca3af;
          max-width: 600px;
          margin: 0 auto 30px;
        }

        .currency-badge {
          display: inline-flex;
          align-items: center;
          gap: 8px;
          background: rgba(102, 16, 242, 0.15);
          color: #a78bfa;
          padding: 8px 16px;
          border-radius: 20px;
          font-size: 13px;
          margin-bottom: 20px;
          border: 1px solid rgba(102, 16, 242, 0.3);
          min-height: 36px;
        }

        .currency-badge svg {
          width: 16px;
          height: 16px;
        }

        .currency-badge.loading {
          opacity: 0.7;
        }

        .pricing-toggle {
          display: inline-flex;
          align-items: center;
          gap: 16px;
          background: rgba(255, 255, 255, 0.05);
          padding: 8px;
          border-radius: 50px;
          border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .toggle-option {
          padding: 12px 28px;
          border-radius: 40px;
          font-size: 15px;
          font-weight: 500;
          cursor: pointer;
          transition: all 0.3s ease;
          color: #9ca3af;
          position: relative;
        }

        .toggle-option.active {
          background: linear-gradient(135deg, #321ca4 0%, #6610f2 100%);
          color: #fff;
          box-shadow: 0 4px 20px rgba(50, 28, 164, 0.4);
        }

        .toggle-option:not(.active):hover {
          color: #fff;
        }

        .save-badge {
          position: absolute;
          top: -28px;
          right: -10px;
          background: linear-gradient(135deg, #10b981 0%, #059669 100%);
          color: #fff;
          font-size: 11px;
          font-weight: 600;
          padding: 4px 10px;
          border-radius: 20px;
          white-space: nowrap;
        }

        .pricing-cards {
          display: flex;
          gap: 24px;
          position: relative;
          z-index: 1;
          max-width: 1400px;
          margin: 0 auto;
          justify-content: center;
        }

        .pricing-card {
          flex: 0 0 280px;
          min-width: 280px;
        }

        .pricing-card {
          background: rgba(255, 255, 255, 0.03);
          border: 1px solid rgba(255, 255, 255, 0.08);
          border-radius: 24px;
          padding: 36px 28px;
          position: relative;
          transition: all 0.4s ease;
          backdrop-filter: blur(10px);
          display: flex;
          flex-direction: column;
          flex: 0 0 280px;
          min-width: 280px;
        }

        .pricing-card:hover {
          transform: translateY(-8px);
          border-color: rgba(255, 255, 255, 0.15);
          box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
        }

        .pricing-card.popular {
          background: linear-gradient(135deg, rgba(50, 28, 164, 0.12) 0%, rgba(102, 16, 242, 0.12) 100%);
          border-color: rgba(102, 16, 242, 0.3);
          transform: scale(1.02);
        }

        .pricing-card.popular:hover {
          transform: scale(1.02) translateY(-8px);
        }

        .popular-badge {
          position: absolute;
          top: -14px;
          left: 50%;
          transform: translateX(-50%);
          background: linear-gradient(135deg, #6610f2 0%, #321ca4 100%);
          color: #fff;
          font-size: 12px;
          font-weight: 600;
          padding: 6px 20px;
          border-radius: 30px;
          box-shadow: 0 4px 20px rgba(102, 16, 242, 0.4);
          white-space: nowrap;
        }

        .plan-name {
          font-size: 22px;
          font-weight: 700;
          color: #fff;
          margin-bottom: 8px;
        }

        .plan-description {
          font-size: 13px;
          color: #9ca3af;
          margin-bottom: 20px;
          line-height: 1.5;
          min-height: 40px;
        }

        .plan-price {
          display: flex;
          align-items: baseline;
          gap: 4px;
          margin-bottom: 6px;
        }

        .price-currency {
          font-size: 20px;
          font-weight: 600;
          color: #fff;
        }

        .price-amount {
          font-size: 44px;
          font-weight: 800;
          color: #fff;
          line-height: 1;
        }

        .price-period {
          font-size: 14px;
          color: #9ca3af;
          margin-bottom: 20px;
        }

        .yearly-savings {
          display: inline-block;
          background: rgba(16, 185, 129, 0.15);
          color: #10b981;
          font-size: 12px;
          font-weight: 600;
          padding: 5px 12px;
          border-radius: 20px;
          margin-bottom: 20px;
        }

        .plan-cta {
          display: block;
          width: 100%;
          padding: 14px 20px;
          border-radius: 12px;
          font-size: 15px;
          font-weight: 600;
          text-align: center;
          text-decoration: none;
          transition: all 0.3s ease;
          margin-bottom: 28px;
        }

        .plan-cta.primary {
          background: linear-gradient(135deg, #321ca4 0%, #6610f2 100%);
          color: #fff;
          border: none;
          box-shadow: 0 4px 20px rgba(50, 28, 164, 0.3);
        }

        .plan-cta.primary:hover {
          transform: translateY(-2px);
          box-shadow: 0 8px 30px rgba(102, 16, 242, 0.4);
        }

        .plan-cta.secondary {
          background: transparent;
          color: #fff;
          border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .plan-cta.secondary:hover {
          background: rgba(255, 255, 255, 0.05);
          border-color: rgba(255, 255, 255, 0.3);
        }

        .features-title {
          font-size: 12px;
          font-weight: 600;
          color: #9ca3af;
          text-transform: uppercase;
          letter-spacing: 1px;
          margin-bottom: 16px;
        }

        .features-list {
          list-style: none;
          padding: 0;
          margin: 0;
          flex-grow: 1;
        }

        .feature-item {
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 8px 0;
          border-bottom: 1px solid rgba(255, 255, 255, 0.05);
          font-size: 13px;
          color: #d1d5db;
        }

        .feature-item:last-child {
          border-bottom: none;
        }

        .feature-icon {
          width: 18px;
          height: 18px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;
        }

        .feature-icon.included {
          background: rgba(16, 185, 129, 0.15);
          color: #10b981;
        }

        .feature-icon.excluded {
          background: rgba(107, 114, 128, 0.15);
          color: #6b7280;
        }

        .feature-name {
          flex: 1;
          display: flex;
          align-items: center;
          gap: 6px;
        }

        .tooltip-wrapper {
          position: relative;
          display: inline-flex;
        }

        .info-btn {
          width: 16px;
          height: 16px;
          border-radius: 50%;
          background: rgba(255, 255, 255, 0.1);
          border: none;
          color: #9ca3af;
          cursor: help;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          font-size: 10px;
          font-weight: 700;
          transition: all 0.2s ease;
          padding: 0;
          flex-shrink: 0;
          font-style: italic;
          line-height: 1;
        }

        .info-btn:hover {
          background: rgba(102, 16, 242, 0.4);
          color: #fff;
          transform: scale(1.1);
        }

        .tooltip {
          position: absolute;
          bottom: calc(100% + 10px);
          left: 50%;
          transform: translateX(-50%);
          background: #1e293b;
          color: #e2e8f0;
          padding: 12px 16px;
          border-radius: 10px;
          font-size: 12px;
          line-height: 1.5;
          width: 240px;
          box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
          border: 1px solid rgba(255, 255, 255, 0.15);
          z-index: 1000;
          text-align: center;
          font-style: normal;
          font-weight: 400;
          opacity: 0;
          visibility: hidden;
          transition: opacity 0.2s ease, visibility 0.2s ease, transform 0.2s ease;
          pointer-events: none;
        }

        .tooltip-wrapper:hover .tooltip,
        .info-btn:focus + .tooltip,
        .info-btn:focus-within + .tooltip {
          opacity: 1;
          visibility: visible;
          transform: translateX(-50%) translateY(0);
          pointer-events: auto;
        }

        .tooltip::after {
          content: '';
          position: absolute;
          top: 100%;
          left: 50%;
          transform: translateX(-50%);
          border: 8px solid transparent;
          border-top-color: #1e293b;
        }

        html[dir="rtl"] .tooltip {
          text-align: center;
        }

        .feature-value {
          margin-left: auto;
          font-weight: 600;
          color: #a78bfa;
          font-size: 12px;
        }

        html[dir="rtl"] .feature-value {
          margin-left: 0;
          margin-right: auto;
        }

        /* Calculator Section */
        .calculator-section {
          margin-top: 60px;
          position: relative;
          z-index: 1;
        }

        .calculator-toggle {
          display: flex;
          justify-content: center;
          margin-bottom: 30px;
        }

        .calculator-toggle-btn {
          display: inline-flex;
          align-items: center;
          gap: 12px;
          background: linear-gradient(135deg, #321ca4 0%, #6610f2 100%);
          border: none;
          color: #fff;
          padding: 16px 32px;
          border-radius: 50px;
          font-size: 16px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.3s ease;
          box-shadow: 0 4px 20px rgba(50, 28, 164, 0.4);
          animation: pulse-glow 2s ease-in-out infinite;
        }

        @keyframes pulse-glow {
          0%, 100% {
            box-shadow: 0 4px 20px rgba(50, 28, 164, 0.4);
            transform: scale(1);
          }
          50% {
            box-shadow: 0 6px 30px rgba(102, 16, 242, 0.6);
            transform: scale(1.02);
          }
        }

        @keyframes vibrate {
          0%, 100% { transform: translateX(0); }
          10%, 30%, 50%, 70%, 90% { transform: translateX(-2px); }
          20%, 40%, 60%, 80% { transform: translateX(2px); }
        }

        .calculator-toggle-btn:hover {
          background: linear-gradient(135deg, #4527c9 0%, #7c3aed 100%);
          box-shadow: 0 8px 30px rgba(102, 16, 242, 0.5);
          transform: translateY(-2px);
          animation: none;
        }

        .calculator-toggle-btn:active {
          transform: scale(0.98);
        }

        .calculator-toggle-btn svg {
          width: 22px;
          height: 22px;
          animation: vibrate 0.5s ease-in-out infinite;
        }

        .calculator-toggle-btn:hover svg {
          animation: none;
        }

        .calculator-container {
          background: rgba(255, 255, 255, 0.03);
          border: 1px solid rgba(255, 255, 255, 0.08);
          border-radius: 24px;
          padding: 40px;
          max-width: 900px;
          margin: 0 auto;
        }

        .calculator-title {
          text-align: center;
          font-size: 24px;
          font-weight: 700;
          color: #fff;
          margin-bottom: 30px;
        }

        .calculator-grid {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 20px;
          margin-bottom: 30px;
        }

        .calc-field {
          display: flex;
          flex-direction: column;
          gap: 8px;
        }

        .calc-field > label {
          font-size: 13px;
          color: #9ca3af;
          font-weight: 500;
        }

        .calc-field input[type="number"] {
          background: rgba(255, 255, 255, 0.05);
          border: 1px solid rgba(255, 255, 255, 0.1);
          border-radius: 10px;
          padding: 12px 16px;
          color: #fff;
          font-size: 15px;
          width: 100%;
          transition: all 0.2s ease;
        }

        .calc-field input[type="number"]:focus {
          outline: none;
          border-color: rgba(102, 16, 242, 0.5);
          background: rgba(102, 16, 242, 0.1);
        }

        .calc-checkbox {
          display: flex;
          align-items: center;
          gap: 10px;
          padding: 12px 16px;
          background: rgba(255, 255, 255, 0.05);
          border: 1px solid rgba(255, 255, 255, 0.1);
          border-radius: 10px;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .calc-checkbox:hover {
          border-color: rgba(102, 16, 242, 0.3);
        }

        .calc-checkbox input {
          width: 18px;
          height: 18px;
          accent-color: #6610f2;
          cursor: pointer;
        }

        .calc-checkbox span {
          font-size: 13px;
          color: #d1d5db;
        }

        .calc-result {
          text-align: center;
          padding: 30px;
          background: linear-gradient(135deg, rgba(50, 28, 164, 0.12) 0%, rgba(102, 16, 242, 0.12) 100%);
          border-radius: 16px;
          border: 1px solid rgba(102, 16, 242, 0.2);
        }

        .calc-result-label {
          font-size: 14px;
          color: #9ca3af;
          margin-bottom: 10px;
        }

        .calc-result-price {
          font-size: 48px;
          font-weight: 800;
          color: #fff;
          margin-bottom: 10px;
        }

        .calc-result-period {
          font-size: 14px;
          color: #9ca3af;
        }

        .estimation-note {
          text-align: center;
          margin-top: 20px;
          padding: 16px;
          background: rgba(251, 191, 36, 0.1);
          border: 1px solid rgba(251, 191, 36, 0.2);
          border-radius: 12px;
          color: #fbbf24;
          font-size: 13px;
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 10px;
        }

        .estimation-note svg {
          width: 18px;
          height: 18px;
          flex-shrink: 0;
        }

        @media (max-width: 1200px) {
          .pricing-cards {
            flex-wrap: wrap;
          }
          
          .pricing-card.popular {
            transform: scale(1);
          }
          
          .pricing-card.popular:hover {
            transform: translateY(-8px);
          }

          .calculator-grid {
            grid-template-columns: repeat(2, 1fr);
          }
        }

        @media (max-width: 768px) {
          .azzle-pricing-section {
            padding: 60px 0;
          }
          
          .pricing-header h2 {
            font-size: 32px;
          }
          
          .pricing-cards-wrapper {
            width: 100%;
            overflow-x: auto;
            overflow-y: hidden;
            -webkit-overflow-scrolling: touch;
            scrollbar-width: none;
            -ms-overflow-style: none;
            padding: 20px 0 30px;
            margin: -20px 0;
          }

          .pricing-cards-wrapper::-webkit-scrollbar {
            display: none;
          }
          
          .pricing-cards {
            display: flex;
            flex-wrap: nowrap;
            gap: 16px;
            padding: 0 20px;
            width: max-content;
            justify-content: flex-start;
          }
          
          .pricing-card {
            flex: 0 0 280px;
            min-width: 280px;
            padding: 28px 20px;
            scroll-snap-align: center;
          }

          .pricing-cards-wrapper {
            scroll-snap-type: x mandatory;
          }

          .scroll-indicator {
            display: flex;
            justify-content: center;
            gap: 8px;
            margin-top: 16px;
          }

          .scroll-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            transition: all 0.3s ease;
          }

          .scroll-dot.active {
            background: #6610f2;
            width: 24px;
            border-radius: 4px;
          }

          .swipe-hint {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            color: #9ca3af;
            font-size: 13px;
            margin-bottom: 16px;
            animation: swipe-bounce 2s ease-in-out infinite;
          }

          @keyframes swipe-bounce {
            0%, 100% { transform: translateX(0); }
            50% { transform: translateX(10px); }
          }

          .swipe-hint svg {
            width: 20px;
            height: 20px;
          }
          
          .price-amount {
            font-size: 40px;
          }

          .calculator-grid {
            grid-template-columns: 1fr;
          }

          .calculator-container {
            padding: 24px;
          }

          .calc-result-price {
            font-size: 36px;
          }

          .tooltip {
            width: 200px;
            font-size: 11px;
          }
        }

        @media (min-width: 769px) {
          .swipe-hint {
            display: none;
          }

          .scroll-indicator {
            display: none;
          }

          .pricing-cards-wrapper {
            overflow: visible;
          }
        }
      `}</style>

      <div className="container">
        <div className="pricing-header" data-aos="fade-up" data-aos-delay="200">
          <h2>{t("pricing.title")}</h2>
          <p>{t("pricing.subtitle")}</p>

          <div className={`currency-badge ${isLoadingCurrency ? 'loading' : ''}`}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <circle cx="12" cy="12" r="10"/>
              <path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
            </svg>
            {isLoadingCurrency 
              ? t("pricing.detectingLocation")
              : `${t("pricing.showingPricesIn")} ${currency.name} (${currency.symbol})`
            }
          </div>

          <div className="pricing-toggle">
            <span
              className={`toggle-option ${!isYearly ? "active" : ""}`}
              onClick={() => setIsYearly(false)}
            >
              {t("pricing.monthly")}
            </span>
            <span
              className={`toggle-option ${isYearly ? "active" : ""}`}
              onClick={() => setIsYearly(true)}
            >
              {t("pricing.yearly")}
              <span className="save-badge">{t("pricing.save")} 16%</span>
            </span>
          </div>
        </div>

        <div className="swipe-hint">
          <span>{language === "ar" ? "اسحب لرؤية المزيد" : "Swipe to see more"}</span>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <path d="M5 12h14M12 5l7 7-7 7"/>
          </svg>
        </div>

        <div className="pricing-cards-wrapper">
          <div className="pricing-cards">
            {plans.map((plan, index) => (
              <div
                key={plan.id}
                className={`pricing-card ${plan.popular ? "popular" : ""}`}
                data-aos="fade-up"
                data-aos-delay={300 + index * 100}
              >
                {plan.popular && (
                  <span className="popular-badge">{t("pricing.mostPopular")}</span>
                )}

                <h3 className="plan-name">{plan.name}</h3>
                <p className="plan-description">{plan.description}</p>

                <div className="plan-price">
                  <span className="price-currency">{currency.symbol}</span>
                  <span className="price-amount">{getPrice(plan)}</span>
                </div>
                <p className="price-period">
                  {isYearly ? t("pricing.perYear") : t("pricing.perMonth")}
                </p>

                {isYearly && (
                  <span className="yearly-savings">
                    {t("pricing.youSave")} {currency.symbol}{getSavings(plan)}
                  </span>
                )}

                <Link
                  href={`/${language}/contact-us`}
                  className={`plan-cta ${plan.popular ? "primary" : "secondary"}`}
                >
                  {t("pricing.getStarted")}
                </Link>

                <p className="features-title">{t("pricing.whatsIncluded")}</p>
                <ul className="features-list">
                  {plan.features.map((feature, idx) => (
                      <li key={idx} className="feature-item">
                        <span
                          className={`feature-icon ${
                            feature.included ? "included" : "excluded"
                          }`}
                        >
                          {feature.included ? (
                            <svg
                              width="10"
                              height="10"
                              viewBox="0 0 12 12"
                              fill="none"
                            >
                              <path
                                d="M10 3L4.5 8.5L2 6"
                                stroke="currentColor"
                                strokeWidth="2"
                                strokeLinecap="round"
                                strokeLinejoin="round"
                              />
                            </svg>
                          ) : (
                            <svg
                              width="8"
                              height="8"
                              viewBox="0 0 10 10"
                              fill="none"
                            >
                              <path
                                d="M8 2L2 8M2 2L8 8"
                                stroke="currentColor"
                                strokeWidth="1.5"
                                strokeLinecap="round"
                              />
                            </svg>
                          )}
                        </span>
                        <span className="feature-name">
                          {feature.name}
                          <div className="tooltip-wrapper">
                            <span
                              className="info-btn"
                              tabIndex={0}
                              role="button"
                              aria-label="More info"
                            >
                              i
                            </span>
                            <div className="tooltip">
                              {t(`pricing.info.${feature.infoKey}`)}
                            </div>
                          </div>
                        </span>
                        {feature.value && (
                          <span className="feature-value">{feature.value}</span>
                        )}
                      </li>
                    ))}
                </ul>
              </div>
            ))}
          </div>
        </div>

        <div className="scroll-indicator">
          {plans.map((plan, index) => (
            <span key={plan.id} className={`scroll-dot ${index === 0 ? 'active' : ''}`}></span>
          ))}
        </div>

        {/* Cost Calculator Section */}
        <div className="calculator-section" data-aos="fade-up" data-aos-delay="500">
          <div className="calculator-toggle">
            <button 
              type="button"
              className="calculator-toggle-btn"
              onClick={() => setShowCalculator(!showCalculator)}
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <rect x="4" y="2" width="16" height="20" rx="2"/>
                <line x1="8" y1="6" x2="16" y2="6"/>
                <line x1="8" y1="10" x2="10" y2="10"/>
                <line x1="12" y1="10" x2="14" y2="10"/>
                <line x1="8" y1="14" x2="10" y2="14"/>
                <line x1="12" y1="14" x2="14" y2="14"/>
                <line x1="8" y1="18" x2="10" y2="18"/>
                <line x1="12" y1="18" x2="16" y2="18"/>
              </svg>
              {showCalculator ? t("pricing.hideCalculator") : t("pricing.showCalculator")}
            </button>
          </div>

          {showCalculator && (
            <div className="calculator-container">
              <h3 className="calculator-title">{t("pricing.calculatorTitle")}</h3>
              
              <div className="calculator-grid">
                <div className="calc-field">
                  <label>{t("pricing.feature.teamMembers")}</label>
                  <input
                    type="number"
                    min="1"
                    value={calcValues.teamMembers}
                    onChange={(e) => setCalcValues({...calcValues, teamMembers: Math.max(1, parseInt(e.target.value) || 1)})}
                  />
                </div>
                <div className="calc-field">
                  <label>{t("pricing.feature.connections")}</label>
                  <input
                    type="number"
                    min="1"
                    value={calcValues.contacts}
                    onChange={(e) => setCalcValues({...calcValues, contacts: Math.max(1, parseInt(e.target.value) || 1)})}
                  />
                </div>
                <div className="calc-field">
                  <label>{t("pricing.feature.conversations")}</label>
                  <input
                    type="number"
                    min="1"
                    value={calcValues.conversations}
                    onChange={(e) => setCalcValues({...calcValues, conversations: Math.max(1, parseInt(e.target.value) || 1)})}
                  />
                </div>
                <div className="calc-field">
                  <label>{t("pricing.feature.aiResponses")}</label>
                  <input
                    type="number"
                    min="1"
                    value={calcValues.aiResponses}
                    onChange={(e) => setCalcValues({...calcValues, aiResponses: Math.max(1, parseInt(e.target.value) || 1)})}
                  />
                </div>
                <div className="calc-field">
                  <label>{t("pricing.feature.aiTickets")}</label>
                  <input
                    type="number"
                    min="0"
                    value={calcValues.aiTickets}
                    onChange={(e) => setCalcValues({...calcValues, aiTickets: Math.max(0, parseInt(e.target.value) || 0)})}
                  />
                </div>
                <div className="calc-field">
                  <label>{t("pricing.feature.sitePages")}</label>
                  <input
                    type="number"
                    min="0"
                    value={calcValues.sitePages}
                    onChange={(e) => setCalcValues({...calcValues, sitePages: Math.max(0, parseInt(e.target.value) || 0)})}
                  />
                </div>
                <div className="calc-field">
                  <label>{t("pricing.feature.flowCreators")}</label>
                  <input
                    type="number"
                    min="0"
                    value={calcValues.flowCreators}
                    onChange={(e) => setCalcValues({...calcValues, flowCreators: Math.max(0, parseInt(e.target.value) || 0)})}
                  />
                </div>
                <div className="calc-field">
                  <label>{t("pricing.feature.mediaFiles")}</label>
                  <input
                    type="number"
                    min="0"
                    value={calcValues.mediaFiles}
                    onChange={(e) => setCalcValues({...calcValues, mediaFiles: Math.max(0, parseInt(e.target.value) || 0)})}
                  />
                </div>
                <div className="calc-field">
                  <label>{t("pricing.feature.knowledgeBases")}</label>
                  <input
                    type="number"
                    min="1"
                    value={calcValues.knowledgeBases}
                    onChange={(e) => setCalcValues({...calcValues, knowledgeBases: Math.max(1, parseInt(e.target.value) || 1)})}
                  />
                </div>
                <div className="calc-field">
                  <label>{t("pricing.feature.channels")}</label>
                  <input
                    type="number"
                    min="1"
                    max="4"
                    value={calcValues.channels}
                    onChange={(e) => setCalcValues({...calcValues, channels: Math.min(4, Math.max(1, parseInt(e.target.value) || 1))})}
                  />
                </div>
                <div className="calc-field">
                  <label className="calc-checkbox">
                    <input
                      type="checkbox"
                      checked={calcValues.webChat}
                      onChange={(e) => setCalcValues({...calcValues, webChat: e.target.checked})}
                    />
                    <span>{t("pricing.feature.webChat")}</span>
                  </label>
                </div>
                <div className="calc-field">
                  <label className="calc-checkbox">
                    <input
                      type="checkbox"
                      checked={calcValues.paymentLinks}
                      onChange={(e) => setCalcValues({...calcValues, paymentLinks: e.target.checked})}
                    />
                    <span>{t("pricing.feature.paymentLinks")}</span>
                  </label>
                </div>
                <div className="calc-field">
                  <label className="calc-checkbox">
                    <input
                      type="checkbox"
                      checked={calcValues.bookingsTables}
                      onChange={(e) => setCalcValues({...calcValues, bookingsTables: e.target.checked})}
                    />
                    <span>{t("pricing.feature.bookingsTables")}</span>
                  </label>
                </div>
              </div>

              <div className="calc-result">
                <p className="calc-result-label">{t("pricing.estimatedPrice")}</p>
                <p className="calc-result-price">
                  {currency.symbol}{formatPrice(convertPrice(calculateEstimatedPrice()))}
                </p>
                <p className="calc-result-period">{t("pricing.perMonth")}</p>
              </div>

              <div className="estimation-note">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <circle cx="12" cy="12" r="10"/>
                  <line x1="12" y1="8" x2="12" y2="12"/>
                  <line x1="12" y1="16" x2="12.01" y2="16"/>
                </svg>
                {t("pricing.estimationDisclaimer")}
              </div>
            </div>
          )}
        </div>
      </div>
    </section>
  );
}
