import React, { useState, useEffect } from 'react'; import { Box, Container, Typography, Card, CardContent, CardActions, Button, Grid, Chip, List, ListItem, ListItemIcon, ListItemText, Switch, FormControlLabel, Divider, Alert, CircularProgress, useTheme, IconButton, Tooltip, Dialog, DialogTitle, DialogContent, DialogActions, Modal, Fade, Backdrop, Snackbar, } from '@mui/material'; import { Check as CheckIcon, Close as CloseIcon, Star as StarIcon, WorkspacePremium as PremiumIcon, Info as InfoIcon, Warning, Psychology, Search, FactCheck, Edit, Assistant, Verified, Timeline, Analytics, Support, Business, Group, } from '@mui/icons-material'; import { useNavigate } from 'react-router-dom'; import { apiClient } from '../../api/client'; interface SubscriptionPlan { id: number; name: string; tier: string; price_monthly: number; price_yearly: number; description: string; features: string[]; limits: { gemini_calls: number; openai_calls: number; anthropic_calls: number; mistral_calls: number; tavily_calls: number; serper_calls: number; metaphor_calls: number; firecrawl_calls: number; stability_calls: number; monthly_cost: number; }; } const PricingPage: React.FC = () => { const theme = useTheme(); const navigate = useNavigate(); const [plans, setPlans] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [yearlyBilling, setYearlyBilling] = useState(false); const [selectedPlan, setSelectedPlan] = useState(null); const [subscribing, setSubscribing] = useState(false); const [paymentModalOpen, setPaymentModalOpen] = useState(false); const [showSignInPrompt, setShowSignInPrompt] = useState(false); const [successSnackbar, setSuccessSnackbar] = useState({ open: false, message: '', countdown: 3 }); const [knowMoreModal, setKnowMoreModal] = useState<{ open: boolean; title: string; content: React.ReactNode }>({ open: false, title: '', content: null }); useEffect(() => { fetchPlans(); }, []); const fetchPlans = async () => { try { setLoading(true); const response = await apiClient.get('/api/subscription/plans'); // Filter out any alpha plans and ensure we only show the 4 main tiers const filteredPlans = response.data.data.plans.filter( (plan: SubscriptionPlan) => !plan.name.toLowerCase().includes('alpha') ); setPlans(filteredPlans); } catch (err) { console.error('Error fetching plans:', err); setError('Failed to load subscription plans'); } finally { setLoading(false); } }; const handleSubscribe = async (planId: number) => { const plan = plans.find(p => p.id === planId); if (!plan) return; // Get user_id from localStorage (set by Clerk auth) const userId = localStorage.getItem('user_id'); // Check if user is signed in if (!userId || userId === 'anonymous' || userId === '') { // User not signed in, show sign-in prompt console.warn('PricingPage: User not signed in, showing prompt'); setShowSignInPrompt(true); return; } // For alpha testing, only allow Free and Basic plans (Pro features not ready) if (plan.tier !== 'free' && plan.tier !== 'basic') { setError('This plan is not available for alpha testing'); return; } if (plan.tier === 'free') { // For free plan, just create subscription try { setSubscribing(true); const userId = localStorage.getItem('user_id') || 'anonymous'; await apiClient.post(`/api/subscription/subscribe/${userId}`, { plan_id: planId, billing_cycle: yearlyBilling ? 'yearly' : 'monthly' }); // Refresh subscription status window.dispatchEvent(new CustomEvent('subscription-updated')); // After subscription, check if onboarding is complete // If not complete, redirect to onboarding; otherwise to dashboard const onboardingComplete = localStorage.getItem('onboarding_complete') === 'true'; if (onboardingComplete) { navigate('/dashboard'); } else { navigate('/onboarding'); } } catch (err) { console.error('Error subscribing:', err); setError('Failed to process subscription'); } finally { setSubscribing(false); } } else { // For Basic plan, show payment modal setPaymentModalOpen(true); } }; const handlePaymentConfirm = async () => { if (!selectedPlan) return; try { setSubscribing(true); const userId = localStorage.getItem('user_id') || 'anonymous'; const response = await apiClient.post(`/api/subscription/subscribe/${userId}`, { plan_id: selectedPlan, billing_cycle: yearlyBilling ? 'yearly' : 'monthly' }); console.log('Subscription renewed successfully:', response.data); // Refresh subscription status immediately window.dispatchEvent(new CustomEvent('subscription-updated')); // Also trigger user authenticated event to refresh subscription context window.dispatchEvent(new CustomEvent('user-authenticated')); setPaymentModalOpen(false); // Get plan name for success message const planName = plans.find(p => p.id === selectedPlan)?.name || 'subscription'; // Show success message with countdown setSuccessSnackbar({ open: true, message: `🎉 ${planName} plan activated! Your usage limits have been reset. Returning to your work in 3 seconds...`, countdown: 3 }); // Countdown timer let countdown = 3; const countdownInterval = setInterval(() => { countdown -= 1; if (countdown > 0) { setSuccessSnackbar(prev => ({ ...prev, message: `🎉 ${planName} plan activated! Your usage limits have been reset. Returning to your work in ${countdown} second${countdown !== 1 ? 's' : ''}...`, countdown })); } else { clearInterval(countdownInterval); } }, 1000); // Auto-redirect after 3 seconds setTimeout(() => { clearInterval(countdownInterval); // After subscription, check if onboarding is complete // If not complete, redirect to onboarding; otherwise to dashboard const onboardingComplete = localStorage.getItem('onboarding_complete') === 'true'; if (onboardingComplete) { // Try to go back to where the user was (e.g., blog writer) // If no history, go to dashboard const referrer = sessionStorage.getItem('subscription_referrer'); if (referrer && referrer !== '/pricing') { navigate(referrer); } else { navigate('/dashboard'); } } else { navigate('/onboarding'); } }, 3000); } catch (err) { console.error('Error subscribing:', err); setError('Failed to process subscription'); setSuccessSnackbar({ open: false, message: '', countdown: 0 }); } finally { setSubscribing(false); } }; const openKnowMoreModal = (title: string, content: React.ReactNode) => { setKnowMoreModal({ open: true, title, content }); }; const getPlanIcon = (tier: string) => { switch (tier) { case 'free': return ; case 'basic': return ; case 'pro': return ; case 'enterprise': return ; default: return ; } }; const getPlanColor = (tier: string) => { switch (tier) { case 'free': return 'success' as const; case 'basic': return 'primary' as const; case 'pro': return 'secondary' as const; case 'enterprise': return 'warning' as const; default: return undefined; } }; if (loading) { return ( Loading subscription plans... ); } if (error) { return ( {error} ); } return ( Choose Your Plan Select the perfect plan for your AI content creation needs {/* Billing Toggle */} setYearlyBilling(e.target.checked)} color="primary" /> } label={yearlyBilling ? "Yearly Billing (Save 20%)" : "Monthly Billing"} sx={{ mb: 2 }} /> {plans.map((plan) => ( {/* Plan Badge */} {plan.tier === 'pro' && ( )} {getPlanIcon(plan.tier)} {plan.name} {plan.description} {/* Pricing */} ${yearlyBilling ? plan.price_yearly : plan.price_monthly} /{yearlyBilling ? 'year' : 'month'} {yearlyBilling && ( Save ${(plan.price_monthly * 12 - plan.price_yearly).toFixed(0)} yearly )} {/* Features */} {/* Platform Access - Free & Basic */} {(plan.tier === 'free' || plan.tier === 'basic') && ( <> Platform Access: openKnowMoreModal('Blog Writer', ( Blog Writer Create engaging blog posts with AI assistance. Includes SEO optimization, keyword research, and content structure suggestions. Features: • SEO-optimized content generation • Keyword research integration • Content structure suggestions • Publishing assistance ))} > openKnowMoreModal('LinkedIn Writer', ( LinkedIn Writer Create professional LinkedIn posts, articles, and carousels that engage your network and showcase your expertise. Features: • Professional post generation • Article writing assistance • Carousel creation • Network engagement optimization ))} > openKnowMoreModal('Facebook Writer', ( Facebook Writer Create engaging Facebook posts, stories, and reels that drive engagement and grow your community. Features: • Post and story creation • Reel script generation • Community management • Engagement optimization ))} > )} {/* Platform Integrations - Pro & Free */} {(plan.tier === 'free' || plan.tier === 'pro' || plan.tier === 'enterprise') && ( <> Platform Integrations: openKnowMoreModal('Wix Integration', ( Wix Integration Seamlessly publish your content directly to Wix websites. No manual copying required. Features: • Direct blog post publishing • SEO metadata sync • Image optimization • Publishing queue management ))} > openKnowMoreModal('WordPress Integration', ( WordPress Integration Connect directly to WordPress sites for seamless content publishing. Features: • REST API integration • Draft and publish modes • Category and tag management • Featured image handling ))} > openKnowMoreModal('Google Search Console', ( Google Search Console Monitor your website's SEO performance and get actionable insights for content optimization. Features: • Search performance tracking • Keyword ranking insights • Technical SEO monitoring • Content optimization suggestions ))} > )} {/* Social Media & Website Management - Pro & Enterprise */} {(plan.tier === 'pro' || plan.tier === 'enterprise') && ( <> Social Media & Website Management: openKnowMoreModal('6 Major Social Platforms', ( 6 Major Social Platforms Comprehensive social media management across all major platforms with AI-powered content optimization. Platforms: • LinkedIn (Professional networking) • Facebook (Community building) • Instagram (Visual storytelling) • Twitter (Real-time engagement) • TikTok (Short-form video) • YouTube (Long-form video content) ))} > )} {/* AI Content Creation Capabilities */} AI Content Creation: openKnowMoreModal('Text Generation', ( AI Text Generation Generate high-quality text content with AI assistance. From blog posts to social media updates, create engaging content effortlessly. Capabilities: • Blog posts and articles • Social media content • Email newsletters • Marketing copy {plan.tier === 'pro' || plan.tier === 'enterprise' && ( <> • Audio transcription • Video script writing )} ))} > openKnowMoreModal('Image Generation', ( AI Image Generation Create stunning visuals with AI-powered image generation. Perfect for social media, blog posts, and marketing materials. Capabilities: • Social media graphics • Blog featured images • Marketing visuals • Custom illustrations {plan.tier === 'pro' || plan.tier === 'enterprise' && ( <> • Video thumbnail generation • Animated graphics )} ))} > {/* Audio/Video for Pro & Enterprise */} {(plan.tier === 'pro' || plan.tier === 'enterprise') && ( <> )} {/* Advanced Features for Higher Tiers */} {plan.tier !== 'free' && ( <> Support & Analytics: {plan.tier === 'pro' && ( )} {plan.tier === 'enterprise' && ( <> )} )} {/* API Limits */} Monthly Limits: {/* For alpha testing: Only Free and Basic are selectable, Pro/Enterprise disabled */} {plan.tier === 'pro' ? ( ) : plan.tier === 'enterprise' ? ( ) : ( <> {selectedPlan === plan.id && ( )} )} ))} All plans include our core AI content creation features.
Need a custom plan?
{/* Payment Modal */} setPaymentModalOpen(false)} closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500, }} > Alpha Testing Subscription {/* Alpha Testing Notice */} ⚠️ Alpha Testing Mode - No Payment Required Payment integration is coming soon. For now, subscriptions are activated without charge. Thank you for participating in our alpha testing! We're crediting the Basic plan ($29 value) to your account. {/* TODO: Payment Integration Notice */} Coming in Production: • Secure Stripe/PayPal payment processing
• Automatic renewal management
• Payment verification & receipts
• Upgrade/downgrade options
{/* Note: Current behavior allows renewal without payment verification */} {/* This is intentional for alpha testing but will be secured in production */}
{/* Know More Modal */} setKnowMoreModal({ open: false, title: '', content: null })} maxWidth="md" fullWidth > {knowMoreModal.title} {knowMoreModal.content} {/* Sign In Prompt Modal */} setShowSignInPrompt(false)} maxWidth="sm" fullWidth > Sign In Required Please sign in to subscribe to a plan and start using ALwrity. If you don't have an account, signing in will automatically create one for you. {/* Success Snackbar */} setSuccessSnackbar({ open: false, message: '', countdown: 0 })} anchorOrigin={{ vertical: 'top', horizontal: 'center' }} sx={{ top: { xs: 16, sm: 24 }, '& .MuiSnackbarContent-root': { minWidth: { xs: '90vw', sm: '500px' } } }} > setSuccessSnackbar({ open: false, message: '', countdown: 0 })} sx={{ width: '100%', fontSize: '1rem', alignItems: 'center', boxShadow: '0 8px 24px rgba(76, 175, 80, 0.4)', '& .MuiAlert-icon': { fontSize: '2rem' } }} > {successSnackbar.message}
); }; export default PricingPage;