'use client' import { useState, useEffect } from 'react' import { useTranslations } from 'next-intl' import { useAuthUser } from '@/hooks/useAuthUser' import { useRouter } from 'next/navigation' import { Header } from '@/components/layout/Header' import { Button } from '@/components/ui/button' import { LoadingSpinner } from '@/components/ui/loading-spinner' import { Crown, Star, CreditCard, AlertTriangle } from 'lucide-react' import { SubscriptionStatus } from '@/components/subscription/SubscriptionStatus' import { QuickUpgradeButton } from '@/components/subscription/SubscribeButton' interface SubscriptionData { plan: string status?: string subscriptions: Array<{ id: string status: string currentPeriodEnd: number cancelAtPeriodEnd: boolean }> } export default function SubscriptionPage() { const { user, userData, loading } = useAuthUser() const router = useRouter() const t = useTranslations('subscription') const [subscriptionData, setSubscriptionData] = useState(null) const [subscriptionLoading, setSubscriptionLoading] = useState(true) const [actionLoading, setActionLoading] = useState(false) useEffect(() => { if (!loading && !user) { router.push('/signin') return } const fetchSubscriptionData = async () => { if (!userData) return try { // 检查是否是从支付成功页面返回 const urlParams = new URLSearchParams(window.location.search) const isSuccess = urlParams.get('success') === 'true' if (isSuccess) { // 先同步订阅状态 try { const syncResponse = await fetch('/api/subscription/sync', { method: 'POST', headers: { 'Content-Type': 'application/json' } }) if (syncResponse.ok) { // 清除 URL 参数 window.history.replaceState({}, '', '/subscription') } } catch (syncError) { console.error('Failed to sync subscription:', syncError) } } const response = await fetch('/api/subscription/manage') if (response.ok) { const data = await response.json() setSubscriptionData(data) } } catch (error) { console.error('Failed to fetch subscription data:', error) } finally { setSubscriptionLoading(false) } } if (userData) { fetchSubscriptionData() } }, [user, userData, loading, router]) const handleCancelSubscription = async (subscriptionId: string) => { if (!confirm(t('confirmCancel'))) return setActionLoading(true) try { const response = await fetch('/api/subscription/manage', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ action: 'cancel', subscriptionId }), }) if (response.ok) { // 刷新订阅数据 window.location.reload() } else { throw new Error('Failed to cancel subscription') } } catch (error) { console.error('Cancel failed:', error) alert('Failed to cancel subscription. Please try again.') } finally { setActionLoading(false) } } const handleSyncSubscription = async () => { setActionLoading(true) try { const response = await fetch('/api/subscription/sync', { method: 'POST', headers: { 'Content-Type': 'application/json', }, }) if (response.ok) { const result = await response.json() console.log('Sync result:', result) // 刷新页面以显示最新状态 window.location.reload() } else { throw new Error('Failed to sync subscription') } } catch (error) { console.error('Sync failed:', error) alert('Failed to sync subscription. Please try again.') } finally { setActionLoading(false) } } const handleManageSubscription = async () => { setActionLoading(true) try { const response = await fetch('/api/subscription/portal', { method: 'POST', headers: { 'Content-Type': 'application/json', }, }) if (response.ok) { const result = await response.json() // 重定向到Stripe客户门户 window.location.href = result.url } else { const errorData = await response.json() throw new Error(errorData.error || 'Failed to create portal session') } } catch (error) { console.error('Portal creation failed:', error) const message = error.message.includes('development mode') ? 'Stripe billing portal is only available in production environment.' : 'Failed to access billing portal. Please try again.' alert(message) } finally { setActionLoading(false) } } if (loading || subscriptionLoading) { return (

{t('loading')}

) } if (!user) { return null } const currentPlan = subscriptionData?.plan || 'free' return (

{t('title')}

{t('subtitle')}

{/* Current Plan */} {/* Quick Actions */}

{t('quickActions')}

{/* Primary Actions */}
{currentPlan === 'free' ? ( {t('upgradePlan')} ) : ( <> {subscriptionData?.subscriptions && subscriptionData.subscriptions.length > 0 && ( )} )}
{/* Secondary Actions */}
) }