🚀 Private Beta • Limited to 500 Developers

AI Generates Code. We Make It Production-Ready.

While ChatGPT and Claude generate raw code, our agentic framework transforms it into enterprise-grade React components through multi-iteration refinement, automated testing, and 20+ years of architectural patterns baked into every generation.

Enterprise patterns built-in
Multi-model intelligence
Production-ready output
247
Beta Developers
🚀
~3s
Avg Generation Time
99.7%
Valid TypeScript
🏗️
20+
Years Experience

Human Experience Meets AI Innovation

Same AI models (GPT-5, Claude Opus 4.1), different results. Our agentic framework applies multi-iteration refinement, automated testing guardrails, and enterprise architectural patterns to transform raw AI output into production-ready components every single time.

💬 Your prompt:
"Create a modern user profile card with avatar, name, role, and social links. Use our design system's color palette, match our existing card shadows, follow our naming conventions, ensure it works with our dark mode theme toggle, and include proper error boundaries and loading states."
👁️ Live Preview:
DN
Deepak Nanda
Enterprise Architect
💬 Your prompt:
"Build a clean login form with email/password fields, proper validation states, forgot password link, and responsive design. Follow our brand colors and typography, include focus states, loading animations, and ensure accessibility compliance."
👁️ Live Preview:
💬 Your prompt:
"Create a user registration form with full name, email, password fields. Include real-time validation, password strength indicator, terms acceptance checkbox, and smooth animations. Maintain design consistency with login form."
👁️ Live Preview:
💬 Your prompt:
"Create responsive pricing cards with three tiers (Starter, Pro, Enterprise). Include feature lists, pricing display, recommended badge, hover effects, accessibility support, loading states, and dark mode compatibility. Handle currency formatting, annual/monthly toggle, and click analytics."
👁️ Live Preview:
Starter
$29
per month
  • Up to 100 components/month
  • Basic AI models
  • Community support
  • × Priority generation
  • × Custom templates
Enterprise
Custom
tailored pricing
  • Everything in Pro
  • Custom AI training
  • Dedicated support
  • SLA guarantee
  • On-premise option
GPT-5 + Claude + 20yr Experience → Production Ready
import React, { useState } from 'react';

/**
 * ProfileCard - A production-ready user profile component
 * Features: Loading states, error handling, theme support, accessibility
 */
interface ProfileCardProps {
  user: {
    name: string;
    role: string;
    avatar: string;
    social: { platform: string; url: string }[];
  };
  theme?: 'light' | 'dark';
  loading?: boolean;
}

export const ProfileCard = ({ user, theme = 'light', loading = false }: ProfileCardProps) => {
  // State management for image loading and error handling
  const [imageError, setImageError] = useState(false);
  const [imageLoading, setImageLoading] = useState(true);

  // Loading state: Show skeleton UI while data is being fetched
  if (loading) {
    return (
      <div className={`p-6 rounded-xl max-w-sm mx-auto animate-pulse ${
        theme === 'dark' ? 'bg-slate-800' : 'bg-white'
      }`}>
        <div className="text-center">
          {/* Skeleton avatar */}
          <div className="w-20 h-20 bg-slate-300 rounded-full mx-auto mb-4"></div>
          {/* Skeleton name */}
          <div className="h-4 bg-slate-300 rounded w-3/4 mx-auto mb-2"></div>
          {/* Skeleton role */}
          <div className="h-3 bg-slate-300 rounded w-1/2 mx-auto mb-4"></div>
          {/* Skeleton social links */}
          <div className="flex justify-center gap-2">
            <div className="h-8 w-16 bg-slate-300 rounded"></div>
            <div className="h-8 w-16 bg-slate-300 rounded"></div>
            <div className="h-8 w-16 bg-slate-300 rounded"></div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={`p-6 rounded-xl shadow-lg max-w-sm mx-auto transition-all duration-300 hover:shadow-xl ${
      theme === 'dark' 
        ? 'bg-slate-800 text-white border border-slate-700' 
        : 'bg-white text-gray-900 border border-gray-200'
    }`}>
      <div className="text-center">
        {/* User Avatar with error handling */}
        <div className="relative inline-block mb-4">
          {!imageError ? (
            <img
              src={user.avatar}
              alt={`${user.name} avatar`}
              className="w-20 h-20 rounded-full mx-auto object-cover ring-4 ring-blue-500/20"
              onLoad={() => setImageLoading(false)}
              onError={() => setImageError(true)}
              style={{ display: imageLoading ? 'none' : 'block' }}
            />
          ) : (
            <div className="w-20 h-20 rounded-full mx-auto bg-gradient-to-r from-blue-500 to-purple-600 flex items-center justify-center text-white font-bold text-xl ring-4 ring-blue-500/20">
              {user.name.split(' ').map(n => n[0]).join('')}
            </div>
          )}
          {imageLoading && !imageError && (
            <div className="w-20 h-20 rounded-full mx-auto bg-gray-300 animate-pulse"></div>
          )}
        </div>

        {/* User Information */}
        <h3 className="text-xl font-bold mb-1">{user.name}</h3>
        <p className={`text-sm mb-4 ${theme === 'dark' ? 'text-slate-400' : 'text-gray-600'}`>
          {user.role}
        </p>

        {/* Social Links */}
        <div className="flex justify-center gap-2">
          {user.social.map((link, index) => (
            <a
              key={index}
              href={link.url}
              target="_blank"
              rel="noopener noreferrer"
              className={`px-3 py-1 rounded-full text-xs font-medium transition-all duration-200 hover:scale-105 focus:outline-none focus:ring-2 focus:ring-blue-500/50 ${
                theme === 'dark'
                  ? 'bg-slate-700 text-slate-300 hover:bg-slate-600'
                  : 'bg-gray-100 text-gray-700 hover:bg-gray-200'
              }`}
              aria-label={`Visit ${user.name}'s ${link.platform}`}
            >
              {link.platform}
            </a>
          ))}
        </div>
      </div>
    </div>
  );
};
GPT-5 + Claude + 20yr Experience → Production Ready
import React, { useState, useRef } from 'react';

/**
 * LoginForm - Production-ready authentication component
 * Features: Form validation, loading states, error handling, accessibility
 */
interface LoginFormProps {
  onSubmit: (credentials: { email: string; password: string }) => Promise<void>;
  theme?: 'light' | 'dark';
  loading?: boolean;
}

export const LoginForm = ({ onSubmit, theme = 'light', loading = false }: LoginFormProps) => {
  // Form state management
  const [formData, setFormData] = useState({ email: '', password: '' });
  const [errors, setErrors] = useState<{ [key: string]: string }>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const emailInputRef = useRef<HTMLInputElement>(null);

  // Form validation
  const validateForm = () => {
    const newErrors: { [key: string]: string } = {};
    
    if (!formData.email) {
      newErrors.email = 'Email is required';
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      newErrors.email = 'Please enter a valid email address';
    }
    
    if (!formData.password) {
      newErrors.password = 'Password is required';
    } else if (formData.password.length < 6) {
      newErrors.password = 'Password must be at least 6 characters';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      // Focus first error field
      if (errors.email && emailInputRef.current) {
        emailInputRef.current.focus();
      }
      return;
    }

    setIsSubmitting(true);
    try {
      await onSubmit(formData);
    } catch (error) {
      setErrors({ submit: 'Login failed. Please check your credentials.' });
    } finally {
      setIsSubmitting(false);
    }
  };

  // Handle input changes
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // Clear field error on input
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  return (
    <div className={`w-full max-w-md mx-auto p-8 rounded-2xl shadow-xl ${
      theme === 'dark' 
        ? 'bg-slate-800 border border-slate-700' 
        : 'bg-white border border-gray-200'
    }`}>
      <div className="text-center mb-8">
        <h2 className={`text-2xl font-bold ${
          theme === 'dark' ? 'text-white' : 'text-gray-900'
        }`}>
          Welcome Back
        </h2>
        <p className={`mt-2 text-sm ${
          theme === 'dark' ? 'text-slate-400' : 'text-gray-600'
        }`}>
          Sign in to your account
        </p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Email Field */}
        <div>
          <label 
            htmlFor="email" 
            className={`block text-sm font-medium mb-2 ${
              theme === 'dark' ? 'text-slate-300' : 'text-gray-700'
            }`}
          >
            Email Address
          </label>
          <input
            ref={emailInputRef}
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
            disabled={isSubmitting || loading}
            className={`w-full px-4 py-3 rounded-lg border transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500/50 disabled:opacity-50 disabled:cursor-not-allowed ${
              errors.email
                ? 'border-red-500 focus:border-red-500'
                : theme === 'dark'
                ? 'bg-slate-700 border-slate-600 text-white placeholder-slate-400 focus:border-blue-500'
                : 'bg-white border-gray-300 text-gray-900 placeholder-gray-500 focus:border-blue-500'
            }`}
            placeholder="Enter your email"
            aria-describedby={errors.email ? 'email-error' : undefined}
          />
          {errors.email && (
            <p id="email-error" className="mt-1 text-sm text-red-500" role="alert">
              {errors.email}
            </p>
          )}
        </div>

        {/* Password Field */}
        <div>
          <label 
            htmlFor="password" 
            className={`block text-sm font-medium mb-2 ${
              theme === 'dark' ? 'text-slate-300' : 'text-gray-700'
            }`}
          >
            Password
          </label>
          <input
            type="password"
            id="password"
            name="password"
            value={formData.password}
            onChange={handleChange}
            disabled={isSubmitting || loading}
            className={`w-full px-4 py-3 rounded-lg border transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500/50 disabled:opacity-50 disabled:cursor-not-allowed ${
              errors.password
                ? 'border-red-500 focus:border-red-500'
                : theme === 'dark'
                ? 'bg-slate-700 border-slate-600 text-white placeholder-slate-400 focus:border-blue-500'
                : 'bg-white border-gray-300 text-gray-900 placeholder-gray-500 focus:border-blue-500'
            }`}
            placeholder="Enter your password"
            aria-describedby={errors.password ? 'password-error' : undefined}
          />
          {errors.password && (
            <p id="password-error" className="mt-1 text-sm text-red-500" role="alert">
              {errors.password}
            </p>
          )}
        </div>

        {/* Submit Error */}
        {errors.submit && (
          <p className="text-sm text-red-500 text-center" role="alert">
            {errors.submit}
          </p>
        )}

        {/* Submit Button */}
        <button
          type="submit"
          disabled={isSubmitting || loading}
          className="w-full py-3 px-4 bg-gradient-to-r from-blue-600 to-purple-600 text-white font-medium rounded-lg transition-all duration-200 hover:from-blue-700 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-blue-500/50 disabled:opacity-50 disabled:cursor-not-allowed transform hover:scale-[1.02] active:scale-[0.98]"
        >
          {isSubmitting ? (
            <span className="flex items-center justify-center">
              <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              Signing in...
            </span>
          ) : (
            'Sign In'
          )}
        </button>

        {/* Forgot Password Link */}
        <div className="text-center">
          <a
            href="#"
            className={`text-sm font-medium transition-colors hover:underline focus:outline-none focus:underline ${
              theme === 'dark' ? 'text-blue-400 hover:text-blue-300' : 'text-blue-600 hover:text-blue-500'
            }`}
          >
            Forgot your password?
          </a>
        </div>
      </form>
    </div>
  );
};
GPT-5 + Claude + 20yr Experience → Production Ready
import React, { useState, useRef } from 'react';

/**
 * RegistrationForm - Production-ready user registration component
 * Features: Real-time validation, password strength, accessibility, loading states
 */
interface RegistrationFormProps {
  onSubmit: (userData: { name: string; email: string; password: string }) => Promise<void>;
  theme?: 'light' | 'dark';
  loading?: boolean;
}

export const RegistrationForm = ({ onSubmit, theme = 'light', loading = false }: RegistrationFormProps) => {
  // Form state management
  const [formData, setFormData] = useState({ name: '', email: '', password: '' });
  const [errors, setErrors] = useState<{ [key: string]: string }>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [passwordStrength, setPasswordStrength] = useState(0);
  const nameInputRef = useRef<HTMLInputElement>(null);

  // Password strength calculation
  const calculatePasswordStrength = (password: string) => {
    let strength = 0;
    if (password.length >= 8) strength += 25;
    if (/[a-z]/.test(password)) strength += 25;
    if (/[A-Z]/.test(password)) strength += 25;
    if (/[0-9]/.test(password)) strength += 25;
    return strength;
  };

  // Form validation
  const validateForm = () => {
    const newErrors: { [key: string]: string } = {};
    
    if (!formData.name.trim()) {
      newErrors.name = 'Full name is required';
    } else if (formData.name.trim().length < 2) {
      newErrors.name = 'Name must be at least 2 characters';
    }
    
    if (!formData.email) {
      newErrors.email = 'Email is required';
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      newErrors.email = 'Please enter a valid email address';
    }
    
    if (!formData.password) {
      newErrors.password = 'Password is required';
    } else if (formData.password.length < 8) {
      newErrors.password = 'Password must be at least 8 characters';
    } else if (passwordStrength < 75) {
      newErrors.password = 'Password must contain uppercase, lowercase, and numbers';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      // Focus first error field
      if (errors.name && nameInputRef.current) {
        nameInputRef.current.focus();
      }
      return;
    }

    setIsSubmitting(true);
    try {
      await onSubmit(formData);
    } catch (error) {
      setErrors({ submit: 'Registration failed. Please try again.' });
    } finally {
      setIsSubmitting(false);
    }
  };

  // Handle input changes
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    
    // Calculate password strength
    if (name === 'password') {
      setPasswordStrength(calculatePasswordStrength(value));
    }
    
    // Clear field error on input
    if (errors[name]) {
      setErrors(prev => ({ ...prev, [name]: '' }));
    }
  };

  // Password strength color and text
  const getPasswordStrengthInfo = (strength: number) => {
    if (strength < 25) return { color: 'bg-red-500', text: 'Very Weak' };
    if (strength < 50) return { color: 'bg-orange-500', text: 'Weak' };
    if (strength < 75) return { color: 'bg-yellow-500', text: 'Fair' };
    return { color: 'bg-green-500', text: 'Strong' };
  };

  const strengthInfo = getPasswordStrengthInfo(passwordStrength);

  return (
    <div className={`w-full max-w-md mx-auto p-8 rounded-2xl shadow-xl ${
      theme === 'dark' 
        ? 'bg-slate-800 border border-slate-700' 
        : 'bg-white border border-gray-200'
    }`}>
      <div className="text-center mb-8">
        <h2 className={`text-2xl font-bold ${
          theme === 'dark' ? 'text-white' : 'text-gray-900'
        }`}>
          Create Account
        </h2>
        <p className={`mt-2 text-sm ${
          theme === 'dark' ? 'text-slate-400' : 'text-gray-600'
        }`}>
          Join us today
        </p>
      </div>

      <form onSubmit={handleSubmit} className="space-y-6">
        {/* Name Field */}
        <div>
          <label 
            htmlFor="name" 
            className={`block text-sm font-medium mb-2 ${
              theme === 'dark' ? 'text-slate-300' : 'text-gray-700'
            }`}
          >
            Full Name
          </label>
          <input
            ref={nameInputRef}
            type="text"
            id="name"
            name="name"
            value={formData.name}
            onChange={handleChange}
            disabled={isSubmitting || loading}
            className={`w-full px-4 py-3 rounded-lg border transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500/50 disabled:opacity-50 disabled:cursor-not-allowed ${
              errors.name
                ? 'border-red-500 focus:border-red-500'
                : theme === 'dark'
                ? 'bg-slate-700 border-slate-600 text-white placeholder-slate-400 focus:border-blue-500'
                : 'bg-white border-gray-300 text-gray-900 placeholder-gray-500 focus:border-blue-500'
            }`}
            placeholder="Enter your full name"
            aria-describedby={errors.name ? 'name-error' : undefined}
          />
          {errors.name && (
            <p id="name-error" className="mt-1 text-sm text-red-500" role="alert">
              {errors.name}
            </p>
          )}
        </div>

        {/* Email Field */}
        <div>
          <label 
            htmlFor="email" 
            className={`block text-sm font-medium mb-2 ${
              theme === 'dark' ? 'text-slate-300' : 'text-gray-700'
            }`}
          >
            Email Address
          </label>
          <input
            type="email"
            id="email"
            name="email"
            value={formData.email}
            onChange={handleChange}
            disabled={isSubmitting || loading}
            className={`w-full px-4 py-3 rounded-lg border transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500/50 disabled:opacity-50 disabled:cursor-not-allowed ${
              errors.email
                ? 'border-red-500 focus:border-red-500'
                : theme === 'dark'
                ? 'bg-slate-700 border-slate-600 text-white placeholder-slate-400 focus:border-blue-500'
                : 'bg-white border-gray-300 text-gray-900 placeholder-gray-500 focus:border-blue-500'
            }`}
            placeholder="Enter your email"
            aria-describedby={errors.email ? 'email-error' : undefined}
          />
          {errors.email && (
            <p id="email-error" className="mt-1 text-sm text-red-500" role="alert">
              {errors.email}
            </p>
          )}
        </div>

        {/* Password Field */}
        <div>
          <label 
            htmlFor="password" 
            className={`block text-sm font-medium mb-2 ${
              theme === 'dark' ? 'text-slate-300' : 'text-gray-700'
            }`}
          >
            Password
          </label>
          <input
            type="password"
            id="password"
            name="password"
            value={formData.password}
            onChange={handleChange}
            disabled={isSubmitting || loading}
            className={`w-full px-4 py-3 rounded-lg border transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500/50 disabled:opacity-50 disabled:cursor-not-allowed ${
              errors.password
                ? 'border-red-500 focus:border-red-500'
                : theme === 'dark'
                ? 'bg-slate-700 border-slate-600 text-white placeholder-slate-400 focus:border-blue-500'
                : 'bg-white border-gray-300 text-gray-900 placeholder-gray-500 focus:border-blue-500'
            }`}
            placeholder="Create a password"
            aria-describedby={errors.password ? 'password-error' : 'password-strength'}
          />
          
          {/* Password Strength Indicator */}
          {formData.password && (
            <div className="mt-2">
              <div className="flex justify-between items-center mb-1">
                <span className={`text-xs ${
                  theme === 'dark' ? 'text-slate-400' : 'text-gray-600'
                }`}>
                  Password Strength
                </span>
                <span className={`text-xs font-medium ${
                  strengthInfo.color === 'bg-green-500' ? 'text-green-600' :
                  strengthInfo.color === 'bg-yellow-500' ? 'text-yellow-600' :
                  strengthInfo.color === 'bg-orange-500' ? 'text-orange-600' : 'text-red-600'
                }`}>
                  {strengthInfo.text}
                </span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-2">
                <div 
                  className={`h-2 rounded-full transition-all duration-300 ${strengthInfo.color}`}
                  style={{ width: `${passwordStrength}%` }}
                  role="progressbar"
                  aria-valuenow={passwordStrength}
                  aria-valuemin={0}
                  aria-valuemax={100}
                  aria-label="Password strength"
                ></div>
              </div>
            </div>
          )}
          
          {errors.password && (
            <p id="password-error" className="mt-1 text-sm text-red-500" role="alert">
              {errors.password}
            </p>
          )}
        </div>

        {/* Submit Error */}
        {errors.submit && (
          <p className="text-sm text-red-500 text-center" role="alert">
            {errors.submit}
          </p>
        )}

        {/* Submit Button */}
        <button
          type="submit"
          disabled={isSubmitting || loading}
          className="w-full py-3 px-4 bg-gradient-to-r from-blue-600 to-purple-600 text-white font-medium rounded-lg transition-all duration-200 hover:from-blue-700 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-blue-500/50 disabled:opacity-50 disabled:cursor-not-allowed transform hover:scale-[1.02] active:scale-[0.98]"
        >
          {isSubmitting ? (
            <span className="flex items-center justify-center">
              <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                <path className="opacity-75" fill="currentColor" d="m4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              Creating account...
            </span>
          ) : (
            'Create Account'
          )}
        </button>

        {/* Sign In Link */}
        <div className="text-center">
          <span className={`text-sm ${
            theme === 'dark' ? 'text-slate-400' : 'text-gray-600'
          }`}>
            Already have an account?{' '}
          </span>
          <a
            href="#"
            class="text-sm font-medium transition-colors hover:underline focus:outline-none focus:underline ${
              theme === 'dark' ? 'text-blue-400 hover:text-blue-300' : 'text-blue-600 hover:text-blue-500'
            }`}
          >
            Sign in
          </a>
        </div>
      </form>
    </div>
  );
};
GPT-5 + Claude + 20yr Experience → Production Ready
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { motion, AnimatePresence } from 'framer-motion';

/**
 * PricingCards - Production-ready pricing component with enterprise features
 * Features: Annual/monthly toggle, loading states, animations, analytics, accessibility
 */

// Comprehensive type definitions
interface PricingFeature {
  text: string;
  included: boolean;
  tooltip?: string;
}

interface PricingTier {
  id: string;
  name: string;
  description?: string;
  price: {
    monthly: number | 'custom';
    annual: number | 'custom';
  };
  currency: string;
  features: PricingFeature[];
  highlighted?: boolean;
  badge?: string;
  cta: {
    text: string;
    action: () => void;
    variant: 'primary' | 'secondary' | 'outline';
  };
}

interface PricingCardsProps {
  tiers: PricingTier[];
  billing?: 'monthly' | 'annual';
  onBillingChange?: (billing: 'monthly' | 'annual') => void;
  loading?: boolean;
  theme?: 'light' | 'dark';
  locale?: string;
  onTierSelect?: (tierId: string, billing: 'monthly' | 'annual') => void;
  showComparison?: boolean;
  analyticsEnabled?: boolean;
}

// Currency formatter with locale support
const formatCurrency = (
  amount: number | 'custom',
  currency: string,
  locale: string = 'en-US'
): string => {
  if (amount === 'custom') return 'Custom';
  
  try {
    return new Intl.NumberFormat(locale, {
      style: 'currency',
      currency,
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(amount);
  } catch (error) {
    console.error('Currency formatting error:', error);
    return `${currency} ${amount}`;
  }
};

// Analytics tracking hook
const useAnalytics = (enabled: boolean) => {
  const track = useCallback((event: string, properties?: Record) => {
    if (!enabled) return;
    
    // Integration with analytics services
    if (typeof window !== 'undefined' && (window as any).analytics) {
      (window as any).analytics.track(event, properties);
    }
    
    // Fallback to console in development
    if (process.env.NODE_ENV === 'development') {
      console.log('[Analytics]', event, properties);
    }
  }, [enabled]);
  
  return { track };
};

// Loading skeleton component
const PricingCardSkeleton: React.FC<{ theme?: 'light' | 'dark' }> = ({ theme = 'light' }) => (
  <div className={`pricing-card-skeleton ${theme}`}>
    <div className="skeleton-line h-4 w-20 mb-4" />
    <div className="skeleton-line h-12 w-32 mb-2" />
    <div className="skeleton-line h-3 w-24 mb-6" />
    {[...Array(5)].map((_, i) => (
      <div key={i} className="flex items-center gap-3 mb-3">
        <div className="skeleton-circle w-5 h-5" />
        <div className="skeleton-line h-3 flex-1" />
      </div>
    ))}
    <div className="skeleton-line h-12 w-full mt-8 rounded-lg" />
  </div>
);

// Main component
export const PricingCards: React.FC<PricingCardsProps> = ({
  tiers,
  billing = 'monthly',
  onBillingChange,
  loading = false,
  theme = 'light',
  locale = 'en-US',
  onTierSelect,
  showComparison = false,
  analyticsEnabled = true,
}) => {
  const [selectedBilling, setSelectedBilling] = useState<'monthly' | 'annual'>(billing);
  const [hoveredTier, setHoveredTier] = useState<string | null>(null);
  const { track } = useAnalytics(analyticsEnabled);

  // Handle billing period change
  const handleBillingChange = useCallback((newBilling: 'monthly' | 'annual') => {
    setSelectedBilling(newBilling);
    onBillingChange?.(newBilling);
    track('pricing_billing_changed', { billing: newBilling });
  }, [onBillingChange, track]);

  // Handle tier selection
  const handleTierSelect = useCallback((tier: PricingTier) => {
    onTierSelect?.(tier.id, selectedBilling);
    track('pricing_tier_selected', {
      tier: tier.name,
      billing: selectedBilling,
      price: tier.price[selectedBilling],
    });
    tier.cta.action();
  }, [selectedBilling, onTierSelect, track]);

  // Calculate savings for annual billing
  const calculateSavings = useMemo(() => {
    return tiers.map(tier => {
      if (tier.price.monthly === 'custom' || tier.price.annual === 'custom') {
        return null;
      }
      const monthlyCost = tier.price.monthly * 12;
      const annualCost = tier.price.annual;
      const savings = monthlyCost - annualCost;
      const savingsPercent = Math.round((savings / monthlyCost) * 100);
      return { savings, savingsPercent };
    });
  }, [tiers]);

  // Keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === 'Tab' && !e.shiftKey) {
        // Custom tab navigation logic for better accessibility
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);

  // Loading state
  if (loading) {
    return (
      <div className={`pricing-cards-container ${theme}`>
        <div className="pricing-cards-grid">
          {[...Array(3)].map((_, i) => (
            <PricingCardSkeleton key={i} theme={theme} />
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className={`pricing-cards-container ${theme}`>
      {/* Billing Toggle */}
      <div className="billing-toggle-container">
        <div className="billing-toggle" role="radiogroup" aria-label="Billing period">
          <button
            className={`toggle-option ${selectedBilling === 'monthly' ? 'active' : ''}`}
            onClick={() => handleBillingChange('monthly')}
            role="radio"
            aria-checked={selectedBilling === 'monthly'}
            aria-label="Monthly billing"
          >
            Monthly
          </button>
          <button
            className={`toggle-option ${selectedBilling === 'annual' ? 'active' : ''}`}
            onClick={() => handleBillingChange('annual')}
            role="radio"
            aria-checked={selectedBilling === 'annual'}
            aria-label="Annual billing"
          >
            Annual
            {calculateSavings.some(s => s && s.savingsPercent > 0) && (
              <span className="savings-badge">Save up to 20%</span>
            )}
          </button>
        </div>
      </div>

      {/* Pricing Cards */}
      <div className="pricing-cards-grid">
        <AnimatePresence>
          {tiers.map((tier, index) => (
            <motion.div
              key={tier.id}
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              transition={{ duration: 0.3, delay: index * 0.1 }}
              className={`pricing-card ${tier.highlighted ? 'highlighted' : ''} ${
                hoveredTier === tier.id ? 'hovered' : ''
              }`}
              onMouseEnter={() => setHoveredTier(tier.id)}
              onMouseLeave={() => setHoveredTier(null)}
              role="article"
              aria-label={`${tier.name} pricing plan`}
            >
              {/* Badge */}
              {tier.badge && (
                <div className="pricing-badge" aria-label="Recommended plan">
                  {tier.badge}
                </div>
              )}

              {/* Header */}
              <div className="pricing-header">
                <h3 className="pricing-tier-name">{tier.name}</h3>
                {tier.description && (
                  <p className="pricing-description">{tier.description}</p>
                )}
              </div>

              {/* Price */}
              <div className="pricing-price-container">
                <div className="pricing-price" aria-label={`Price: ${
                  tier.price[selectedBilling] === 'custom' 
                    ? 'Custom pricing' 
                    : formatCurrency(tier.price[selectedBilling] as number, tier.currency, locale)
                }`}>
                  {tier.price[selectedBilling] === 'custom' ? (
                    <span className="custom-pricing">Custom</span>
                  ) : (
                    <>
                      <span className="currency">{tier.currency === 'USD' ? '$' : tier.currency}</span>
                      <span className="amount">{tier.price[selectedBilling]}</span>
                    </>
                  )}
                </div>
                <div className="pricing-period">
                  {tier.price[selectedBilling] === 'custom' 
                    ? 'Contact for pricing' 
                    : selectedBilling === 'monthly' ? 'per month' : 'per year'}
                </div>
                
                {/* Annual savings */}
                {selectedBilling === 'annual' && calculateSavings[index] && (
                  <div className="annual-savings">
                    Save {formatCurrency(calculateSavings[index]!.savings, tier.currency, locale)}
                  </div>
                )}
              </div>

              {/* Features */}
              <ul className="pricing-features" role="list">
                {tier.features.map((feature, featureIndex) => (
                  <li
                    key={featureIndex}
                    className={`pricing-feature ${!feature.included ? 'not-included' : ''}`}
                    role="listitem"
                  >
                    <span 
                      className="feature-icon"
                      aria-hidden="true"
                    >
                      {feature.included ? '✓' : '×'}
                    </span>
                    <span className="feature-text">
                      {feature.text}
                      {feature.tooltip && (
                        <button
                          className="tooltip-trigger"
                          aria-label={`More info about ${feature.text}`}
                          onClick={(e) => {
                            e.stopPropagation();
                            // Show tooltip logic
                          }}
                        >
                          ⓘ
                        </button>
                      )}
                    </span>
                  </li>
                ))}
              </ul>

              {/* CTA Button */}
              <button
                className={`pricing-cta pricing-cta-${tier.cta.variant}`}
                onClick={() => handleTierSelect(tier)}
                aria-label={`Select ${tier.name} plan`}
              >
                {tier.cta.text}
              </button>
            </motion.div>
          ))}
        </AnimatePresence>
      </div>

      {/* Comparison Table (Optional) */}
      {showComparison && (
        <div className="comparison-table-container">
          <button 
            className="comparison-toggle"
            onClick={() => track('pricing_comparison_viewed')}
          >
            Compare all features
          </button>
        </div>
      )}
    </div>
  );
};

// Error Boundary for production safety
export class PricingCardsErrorBoundary extends React.Component<
  { children: React.ReactNode; fallback?: React.ReactNode },
  { hasError: boolean; error: Error | null }
> {
  constructor(props: any) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: Error) {
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('PricingCards error:', error, errorInfo);
    // Send to error tracking service
    if ((window as any).Sentry) {
      (window as any).Sentry.captureException(error);
    }
  }

  render() {
    if (this.state.hasError) {
      return (
        this.props.fallback || (
          <div className="pricing-error">
            <p>Unable to load pricing information.</p>
            <button onClick={() => window.location.reload()}>
              Refresh page
            </button>
          </div>
        )
      );
    }

    return this.props.children;
  }
}

// Export wrapped component with error boundary
export default function PricingCardsWithErrorBoundary(props: PricingCardsProps) {
  return (
    <PricingCardsErrorBoundary>
      <PricingCards {...props} />
    </PricingCardsErrorBoundary>
  );
}

Join the Developer Community

ServoUI is being built by developers, for developers. Your feedback shapes every feature, improvement, and integration we build. Get exclusive access to our developer community.

💬
Direct Slack Channel
🚀
Early Feature Access
📊
Product Roadmap Input
🎯
Custom Use Case Support
📚
Template Library Access
100s of Ready Components

Ready to Build the Future?

Be among the first developers to experience AI-powered component generation. Help us build something amazing together.