/**
 * Unified Signup Form with Integrated Pricing Selection
 * Combines free and paid signup flows in one modern interface
 */

import { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Link, useNavigate } from 'react-router-dom';
import { ChevronLeftIcon, EyeCloseIcon, EyeIcon } from '../../icons';
import { CreditCard, Building2, Wallet, Check, Loader2, CheckCircle } from 'lucide-react';
import Label from '../form/Label';
import Input from '../form/input/InputField';
import Checkbox from '../form/input/Checkbox';
import Button from '../ui/button/Button';
import SelectDropdown from '../form/SelectDropdown';
import { useAuthStore } from '../../store/authStore';

interface Plan {
  id: number;
  name: string;
  slug: string;
  price: string | number;
  billing_cycle: string;
  is_active: boolean;
  max_users: number;
  max_sites: number;
  max_keywords: number;
  monthly_word_count_limit: number;
  included_credits: number;
  features: string[];
}

interface PaymentMethodConfig {
  id: number;
  payment_method: string;
  display_name: string;
  instructions: string | null;
  country_code: string;
  is_enabled: boolean;
}

interface SignUpFormUnifiedProps {
  plans: Plan[];
  selectedPlan: Plan | null;
  onPlanSelect: (plan: Plan) => void;
  plansLoading: boolean;
}

export default function SignUpFormUnified({
  plans,
  selectedPlan,
  onPlanSelect,
  plansLoading,
}: SignUpFormUnifiedProps) {
  const [showPassword, setShowPassword] = useState(false);
  const [isChecked, setIsChecked] = useState(false);
  const [billingPeriod, setBillingPeriod] = useState<'monthly' | 'annually'>('monthly');

  const [formData, setFormData] = useState({
    firstName: '',
    lastName: '',
    email: '',
    password: '',
    accountName: '',
    billingCountry: 'US',
  });

  const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<string>('');
  const [paymentMethods, setPaymentMethods] = useState<PaymentMethodConfig[]>([]);
  const [paymentMethodsLoading, setPaymentMethodsLoading] = useState(false);
  const [error, setError] = useState('');

  const navigate = useNavigate();
  const { register, loading } = useAuthStore();

  const isPaidPlan = selectedPlan && parseFloat(String(selectedPlan.price || 0)) > 0;

  // Update URL when plan changes
  useEffect(() => {
    if (selectedPlan) {
      const url = new URL(window.location.href);
      url.searchParams.set('plan', selectedPlan.slug);
      window.history.replaceState({}, '', url.toString());
    }
  }, [selectedPlan]);

  // Load payment methods for paid plans
  useEffect(() => {
    if (!isPaidPlan) {
      setPaymentMethods([]);
      return;
    }

    const loadPaymentMethods = async () => {
      setPaymentMethodsLoading(true);
      try {
        const API_BASE_URL = import.meta.env.VITE_BACKEND_URL || 'https://api.igny8.com/api';
        const country = formData.billingCountry || 'US';
        const response = await fetch(`${API_BASE_URL}/v1/billing/payment-configs/payment-methods/?country=${country}`);

        if (!response.ok) {
          throw new Error('Failed to load payment methods');
        }

        const data = await response.json();

        let methodsList: PaymentMethodConfig[] = [];
        if (Array.isArray(data)) {
          methodsList = data;
        } else if (data.success && data.data) {
          methodsList = Array.isArray(data.data) ? data.data : data.data.results || [];
        } else if (data.results) {
          methodsList = data.results;
        }

        const enabledMethods = methodsList.filter((m: PaymentMethodConfig) => m.is_enabled);
        setPaymentMethods(enabledMethods);

        if (enabledMethods.length > 0 && !selectedPaymentMethod) {
          setSelectedPaymentMethod(enabledMethods[0].payment_method);
        }
      } catch (err: any) {
        console.error('Failed to load payment methods:', err);
        // Don't set error for free plans or if payment methods fail to load
        // Just log it and continue
      } finally {
        setPaymentMethodsLoading(false);
      }
    };

    loadPaymentMethods();
  }, [isPaidPlan, formData.billingCountry]);

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');

    if (!formData.email || !formData.password || !formData.firstName || !formData.lastName) {
      setError('Please fill in all required fields');
      return;
    }

    if (!isChecked) {
      setError('Please agree to the Terms and Conditions');
      return;
    }

    if (!selectedPlan) {
      setError('Please select a plan');
      return;
    }

    if (isPaidPlan && !selectedPaymentMethod) {
      setError('Please select a payment method');
      return;
    }

    try {
      const username = formData.email.split('@')[0];

      const registerPayload: any = {
        email: formData.email,
        password: formData.password,
        username: username,
        first_name: formData.firstName,
        last_name: formData.lastName,
        account_name: formData.accountName,
        plan_slug: selectedPlan.slug,
      };

      if (isPaidPlan) {
        registerPayload.payment_method = selectedPaymentMethod;
        registerPayload.billing_email = formData.email;
        registerPayload.billing_country = formData.billingCountry;
      }

      const user = (await register(registerPayload)) as any;

      // CRITICAL: Verify auth state is actually set in Zustand store
      // The register function should have already set isAuthenticated=true
      const currentAuthState = useAuthStore.getState();
      
      console.log('Post-registration auth state check:', {
        isAuthenticated: currentAuthState.isAuthenticated,
        hasUser: !!currentAuthState.user,
        hasToken: !!currentAuthState.token,
        userData: user
      });

      // If for some reason state wasn't set, force set it again
      if (!currentAuthState.isAuthenticated || !currentAuthState.user || !currentAuthState.token) {
        console.error('Auth state not properly set after registration, forcing update...');
        
        // Extract tokens from user data if available
        const tokenData = user?.tokens || {};
        const accessToken = user?.access || tokenData.access || localStorage.getItem('access_token');
        const refreshToken = user?.refresh || tokenData.refresh || localStorage.getItem('refresh_token');
        
        // Force set the state
        useAuthStore.setState({
          user: user,
          token: accessToken,
          refreshToken: refreshToken,
          isAuthenticated: true,
          loading: false
        });
        
        // Wait a bit for state to propagate
        await new Promise((resolve) => setTimeout(resolve, 500));
      }

      // Final verification before navigation
      const finalState = useAuthStore.getState();
      if (!finalState.isAuthenticated) {
        throw new Error('Failed to authenticate after registration. Please try logging in manually.');
      }

      const status = user?.account?.status;
      if (status === 'pending_payment') {
        navigate('/account/plans', { replace: true });
      } else {
        navigate('/sites', { replace: true });
      }
    } catch (err: any) {
      setError(err.message || 'Registration failed. Please try again.');
    }
  };

  const getPaymentIcon = (method: string) => {
    switch (method) {
      case 'stripe':
        return <CreditCard className="w-5 h-5" />;
      case 'bank_transfer':
        return <Building2 className="w-5 h-5" />;
      case 'local_wallet':
        return <Wallet className="w-5 h-5" />;
      default:
        return <CreditCard className="w-5 h-5" />;
    }
  };

  const formatNumber = (num: number): string => {
    if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`;
    if (num >= 1000) return `${(num / 1000).toFixed(0)}K`;
    return num.toString();
  };

  const extractFeatures = (plan: Plan): string[] => {
    // Use features from plan's JSON field if available, otherwise build from limits
    if (plan.features && plan.features.length > 0) {
      return plan.features;
    }
    
    // Fallback to building from plan limits
    const features: string[] = [];
    features.push(`${plan.max_sites} ${plan.max_sites === 1 ? 'Site' : 'Sites'}`);
    features.push(`${plan.max_users} ${plan.max_users === 1 ? 'User' : 'Users'}`);
    features.push(`${formatNumber(plan.max_keywords || 0)} Keywords`);
    features.push(`${formatNumber(plan.monthly_word_count_limit || 0)} Words/Month`);
    features.push(`${formatNumber(plan.included_credits || 0)} AI Credits`);
    return features;
  };

  const getDisplayPrice = (plan: Plan): number => {
    const monthlyPrice = typeof plan.price === 'number' ? plan.price : parseFloat(String(plan.price || 0));
    if (billingPeriod === 'annually') {
      return monthlyPrice * 12 * 0.85; // 15% discount
    }
    return monthlyPrice;
  };

  return (
    <div className="flex flex-col lg:w-1/2 w-full">
      {/* Mobile Pricing Toggle */}
      <div className="lg:hidden bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-700 p-4">
        <div className="flex flex-col items-center gap-3">
          <div className="relative inline-flex p-1 bg-gray-100 dark:bg-gray-800 rounded-lg shadow-sm">
            <span
              className={`absolute top-1/2 left-1 flex h-9 w-28 -translate-y-1/2 rounded-md bg-gradient-to-br from-brand-500 to-brand-600 shadow-md transition-all duration-300 ease-out ${
                billingPeriod === 'monthly' ? 'translate-x-0' : 'translate-x-28'
              }`}
            ></span>
            <button
              type="button"
              onClick={() => setBillingPeriod('monthly')}
              className={`relative flex h-9 w-28 items-center justify-center text-sm font-semibold transition-all duration-200 rounded-md ${
                billingPeriod === 'monthly' ? 'text-white' : 'text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200'
              }`}
            >
              Monthly
            </button>
            <button
              type="button"
              onClick={() => setBillingPeriod('annually')}
              className={`relative flex h-9 w-28 items-center justify-center text-sm font-semibold transition-all duration-200 rounded-md ${
                billingPeriod === 'annually' ? 'text-white' : 'text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200'
              }`}
            >
              Annually
            </button>
          </div>
          <div className="h-6 flex items-center justify-center">
            <span className={`inline-flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400 font-semibold bg-green-50 dark:bg-green-900/20 px-2 py-1 rounded-full transition-opacity duration-200 ${
              billingPeriod === 'annually' ? 'opacity-100' : 'opacity-0'
            }`}>
              <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              Save 15%
            </span>
          </div>
        </div>
      </div>

      <div className="flex-1 overflow-y-auto no-scrollbar flex items-center">
        <div className={`w-full mx-auto p-6 sm:p-8 ${
          isPaidPlan ? 'max-w-2xl' : 'max-w-md'
        }`}>
          <Link
            to="/"
            className="inline-flex items-center text-sm text-gray-500 transition-colors hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-300 mb-6"
          >
            <ChevronLeftIcon className="size-5" />
            Back to dashboard
          </Link>

          <div className="mb-6">
            <h1 className="mb-2 font-semibold text-gray-800 dark:text-white text-2xl">Sign Up for {selectedPlan?.name || 'IGNY8'}</h1>
            <p className="text-sm text-gray-500 dark:text-gray-400">
              Complete your registration and select a payment method.
            </p>
          </div>

          {/* Plan Selection - Mobile */}
          <div className="lg:hidden mb-6">
            <Label>Select Plan</Label>
            <div className="grid grid-cols-2 gap-2 mt-2">
              {plans.map((plan) => {
                const displayPrice = getDisplayPrice(plan);
                const isSelected = selectedPlan?.id === plan.id;
                const isFree = parseFloat(String(plan.price || 0)) === 0;

                return (
                  <button
                    key={plan.id}
                    onClick={() => onPlanSelect(plan)}
                    className={`p-3 rounded-lg border-2 text-left transition-all ${
                      isSelected
                        ? 'border-brand-500 bg-brand-50 dark:bg-brand-900/20'
                        : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
                    }`}
                  >
                    <div className="flex items-center justify-between mb-1">
                      <span className={`font-semibold text-sm ${isSelected ? 'text-brand-600 dark:text-brand-400' : 'text-gray-900 dark:text-white'}`}>
                        {plan.name}
                      </span>
                      {isSelected && <CheckCircle className="w-4 h-4 text-brand-500" />}
                    </div>
                    <div className="text-lg font-bold text-gray-900 dark:text-white">
                      {isFree ? 'Free' : `$${displayPrice.toFixed(2)}`}
                    </div>
                    <div className="text-xs text-gray-500 dark:text-gray-400">
                      {billingPeriod === 'annually' && !isFree ? '/year' : '/month'}
                    </div>
                  </button>
                );
              })}
            </div>
          </div>

          {error && (
            <div className="mb-4 p-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded-lg dark:bg-red-900/20 dark:text-red-400 dark:border-red-800">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
              <div>
                <Label>
                  First Name<span className="text-error-500">*</span>
                </Label>
                <Input type="text" name="firstName" value={formData.firstName} onChange={handleChange} placeholder="Enter your first name" />
              </div>
              <div>
                <Label>
                  Last Name<span className="text-error-500">*</span>
                </Label>
                <Input type="text" name="lastName" value={formData.lastName} onChange={handleChange} placeholder="Enter your last name" />
              </div>
            </div>

            <div>
              <Label>
                Email<span className="text-error-500">*</span>
              </Label>
              <Input type="email" name="email" value={formData.email} onChange={handleChange} placeholder="Enter your email" />
            </div>

            <div>
              <Label>Account Name (optional)</Label>
              <Input type="text" name="accountName" value={formData.accountName} onChange={handleChange} placeholder="Workspace / Company name" />
            </div>

            <div>
              <Label>
                Password<span className="text-error-500">*</span>
              </Label>
              <div className="relative">
                <Input placeholder="Enter your password" type={showPassword ? 'text' : 'password'} name="password" value={formData.password} onChange={handleChange} />
                <span onClick={() => setShowPassword(!showPassword)} className="absolute z-30 -translate-y-1/2 cursor-pointer right-4 top-1/2">
                  {showPassword ? <EyeIcon className="fill-gray-500 dark:fill-gray-400 size-5" /> : <EyeCloseIcon className="fill-gray-500 dark:fill-gray-400 size-5" />}
                </span>
              </div>
            </div>

            {isPaidPlan && (
              <div className="pt-4 border-t border-gray-200 dark:border-gray-700 space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div>
                    <Label>
                      Country<span className="text-error-500">*</span>
                    </Label>
                    <SelectDropdown
                      options={[
                        { value: 'US', label: '🇺🇸 United States' },
                        { value: 'GB', label: '🇬🇧 United Kingdom' },
                        { value: 'IN', label: '🇮🇳 India' },
                        { value: 'PK', label: '🇵🇰 Pakistan' },
                        { value: 'CA', label: '🇨🇦 Canada' },
                        { value: 'AU', label: '🇦🇺 Australia' },
                        { value: 'DE', label: '🇩🇪 Germany' },
                        { value: 'FR', label: '🇫🇷 France' },
                      ]}
                      value={formData.billingCountry}
                      onChange={(value) => setFormData((prev) => ({ ...prev, billingCountry: value }))}
                      className="text-base"
                    />
                    <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">Payment methods filtered by country</p>
                  </div>

                  <div>
                    <Label>
                      Payment Method<span className="text-error-500">*</span>
                    </Label>
                    {paymentMethodsLoading ? (
                      <div className="flex items-center justify-center p-4 bg-gray-50 dark:bg-gray-800 rounded-lg h-[52px]">
                        <Loader2 className="w-4 h-4 animate-spin text-brand-500" />
                      </div>
                    ) : paymentMethods.length === 0 ? (
                      <div className="p-3 bg-amber-50 border border-amber-200 rounded-lg text-amber-800 dark:bg-amber-900/20 dark:border-amber-800 dark:text-amber-200">
                        <p className="text-xs">No payment methods available</p>
                      </div>
                    ) : (
                      <SelectDropdown
                        options={paymentMethods.map(m => ({
                          value: m.payment_method,
                          label: m.display_name
                        }))}
                        value={selectedPaymentMethod}
                        onChange={(value) => setSelectedPaymentMethod(value)}
                        className="text-base"
                      />
                    )}
                    <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">How you'd like to pay</p>
                  </div>
                </div>

                {/* Payment Method Details - Full Width Below */}
                {selectedPaymentMethod && paymentMethods.length > 0 && (
                  <div className="space-y-2">
                    {paymentMethods.filter(m => m.payment_method === selectedPaymentMethod).map((method) => (
                      method.instructions && (
                        <div
                          key={method.id}
                          className="p-4 rounded-lg border border-gray-200 bg-gray-50 dark:border-gray-700 dark:bg-gray-800/50"
                        >
                          <div className="flex items-start gap-3">
                            <div className="flex items-center justify-center w-10 h-10 rounded-lg bg-brand-500 text-white flex-shrink-0">
                              {getPaymentIcon(method.payment_method)}
                            </div>
                            <div className="flex-1">
                              <h4 className="font-semibold text-gray-900 dark:text-white text-sm mb-1">{method.display_name}</h4>
                              <p className="text-xs text-gray-600 dark:text-gray-400 whitespace-pre-line">{method.instructions}</p>
                            </div>
                          </div>
                        </div>
                      )
                    ))}
                  </div>
                )}
              </div>
            )}

            <div className="flex items-start gap-3 pt-2">
              <Checkbox className="w-5 h-5 mt-0.5" checked={isChecked} onChange={setIsChecked} />
              <p className="text-sm text-gray-500 dark:text-gray-400">
                By creating an account means you agree to the <span className="text-gray-800 dark:text-white/90">Terms and Conditions</span>, and our{' '}
                <span className="text-gray-800 dark:text-white">Privacy Policy</span>
              </p>
            </div>

            <Button type="submit" variant="primary" disabled={loading} className="w-full">
              {loading ? (
                <span className="flex items-center justify-center">
                  <Loader2 className="w-4 h-4 animate-spin mr-2" />
                  Creating your account...
                </span>
              ) : isPaidPlan ? (
                'Create Account & Continue to Payment'
              ) : (
                'Start Free Trial'
              )}
            </Button>
          </form>

          <div className="mt-5 text-center">
            <p className="text-sm text-gray-700 dark:text-gray-400">
              Already have an account?{' '}
              <Link to="/signin" className="text-brand-500 hover:text-brand-600 dark:text-brand-400 font-medium">
                Sign In
              </Link>
            </p>
          </div>
        </div>
      </div>

      {/* Desktop Pricing Panel - Renders in right side */}
      <div className="hidden lg:block">
        {/* This will be portaled to the right side */}
        {typeof document !== 'undefined' &&
          document.getElementById('signup-pricing-plans') &&
          ReactDOM.createPortal(
            <div className="space-y-8">
              {/* Billing Toggle - Improved UI */}
              <div className="text-center space-y-3">
                <div className="relative inline-flex p-1 bg-gray-100 dark:bg-gray-800 rounded-xl shadow-sm">
                  <span
                    className={`absolute top-1/2 left-1 flex h-11 w-32 -translate-y-1/2 rounded-lg bg-gradient-to-br from-brand-500 to-brand-600 shadow-md transition-all duration-300 ease-out ${
                      billingPeriod === 'monthly' ? 'translate-x-0' : 'translate-x-32'
                    }`}
                  ></span>
                  <button
                    type="button"
                    onClick={() => setBillingPeriod('monthly')}
                    className={`relative flex h-11 w-32 items-center justify-center text-base font-semibold transition-all duration-200 rounded-lg ${
                      billingPeriod === 'monthly' ? 'text-white' : 'text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200'
                    }`}
                  >
                    Monthly
                  </button>
                  <button
                    type="button"
                    onClick={() => setBillingPeriod('annually')}
                    className={`relative flex h-11 w-32 items-center justify-center text-base font-semibold transition-all duration-200 rounded-lg ${
                      billingPeriod === 'annually' ? 'text-white' : 'text-gray-600 dark:text-gray-400 hover:text-gray-800 dark:hover:text-gray-200'
                    }`}
                  >
                    Annually
                  </button>
                </div>
                <div className="h-7 flex items-center justify-center">
                  <p className={`inline-flex items-center gap-1.5 text-green-600 dark:text-green-400 text-sm font-semibold bg-green-50 dark:bg-green-900/20 px-3 py-1.5 rounded-full transition-opacity duration-200 ${
                    billingPeriod === 'annually' ? 'opacity-100' : 'opacity-0'
                  }`}>
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    Save 15% with annual billing
                  </p>
                </div>
              </div>

              {/* Plan Cards - 2 columns, wider cards, no buttons */}
              <div className="grid gap-5 grid-cols-1 xl:grid-cols-2">
                {plans.map((plan) => {
                  const displayPrice = getDisplayPrice(plan);
                  const features = extractFeatures(plan);
                  const isSelected = selectedPlan?.id === plan.id;
                  const isFree = parseFloat(String(plan.price || 0)) === 0;
                  const isPopular = plan.slug.toLowerCase().includes('growth');

                  return (
                    <div
                      key={plan.id}
                      onClick={() => onPlanSelect(plan)}
                      className={`relative rounded-2xl p-6 cursor-pointer transition-all duration-300 border-2 ${
                        isSelected
                          ? 'border-brand-500 bg-white dark:bg-gray-800 shadow-2xl ring-4 ring-brand-500/20'
                          : isPopular
                          ? 'border-brand-200 dark:border-brand-800 bg-white dark:bg-gray-800/50 hover:shadow-xl'
                          : 'border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800/50 hover:shadow-lg'
                      }`}
                    >
                      {isPopular && !isSelected && (
                        <div className="absolute -top-3 left-1/2 -translate-x-1/2">
                          <span className="bg-gradient-to-r from-green-500 to-emerald-500 text-white text-xs font-bold px-3 py-1 rounded-full shadow-lg">
                            ⭐ POPULAR
                          </span>
                        </div>
                      )}
                      {isSelected && (
                        <div className="absolute -top-4 -right-4">
                          <div className="bg-brand-500 rounded-full p-2 shadow-lg">
                            <CheckCircle className="w-8 h-8 text-white" />
                          </div>
                        </div>
                      )}
                      <div className="mb-5">
                        <h3 className="text-xl font-bold text-gray-900 dark:text-white mb-2">{plan.name}</h3>
                        <div className="flex items-baseline gap-1">
                          <span className="text-4xl font-bold text-gray-900 dark:text-white">
                            {isFree ? 'Free' : `$${displayPrice.toFixed(2)}`}
                          </span>
                          <div className="h-5 flex items-center">
                            {!isFree && (
                              <span className="text-gray-500 dark:text-gray-400 text-sm">
                                {billingPeriod === 'annually' ? '/year' : '/month'}
                              </span>
                            )}
                          </div>
                        </div>
                        <div className="h-5">
                          {billingPeriod === 'annually' && !isFree && (
                            <p className="text-gray-500 dark:text-gray-400 text-xs">
                              ${(displayPrice / 12).toFixed(2)}/month billed annually
                            </p>
                          )}
                        </div>
                      </div>
                      
                      {/* Features - All features in 2 columns */}
                      <div className="grid grid-cols-2 gap-x-3 gap-y-2.5">
                        {features.map((feature, idx) => (
                          <div key={idx} className="flex items-start gap-2">
                            <CheckCircle className="w-4 h-4 text-green-500 dark:text-green-400 flex-shrink-0 mt-0.5" />
                            <span className="text-sm text-gray-700 dark:text-gray-300 leading-tight">{feature}</span>
                          </div>
                        ))}
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>,
            document.getElementById('signup-pricing-plans')!
          )}
      </div>
    </div>
  );
}
