"use client"; import React, { useState } from "react"; import { ApiBaseUrl, ApiServerBaseUrl } from "@/utils/baseurl.utils"; interface Plan { name: string; desc: string; amountMonthly: number; amountYearly: number; features: string[]; planIdMonthly: string; planIdYearly: string; popular?: boolean; } const ComponentsPricingTableToggle = () => { const [billingCycle, setBillingCycle] = useState<"monthly" | "yearly">("monthly"); const [loadingPlan, setLoadingPlan] = useState(null); // Trial State const [trialStatus, setTrialStatus] = useState<{ hasUsedTrial: boolean; isTrialActive: boolean; trialEndsAt: string | null; stripeSessionId: string | null; } | null>(null); const [timeLeft, setTimeLeft] = useState(""); // Fetch subscription status on mount React.useEffect(() => { const fetchStatus = async () => { const userId = localStorage.getItem("userId"); if (!userId) return; try { const res = await fetch(`${ApiServerBaseUrl}/payment/status?userId=${userId}`); const data = await res.json(); setTrialStatus(data); } catch (err) { console.error("Failed to fetch sub status", err); } }; fetchStatus(); }, []); // Timer Effect React.useEffect(() => { if (!trialStatus?.isTrialActive || !trialStatus.trialEndsAt) return; const interval = setInterval(() => { const now = new Date().getTime(); const end = new Date(trialStatus.trialEndsAt!).getTime(); const diff = end - now; if (diff <= 0) { clearInterval(interval); setTimeLeft("Trial Expired"); // Refresh status to ensure strict consistency window.location.reload(); } else { const days = Math.floor(diff / (1000 * 60 * 60 * 24)); const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)); setTimeLeft(`${days}d ${hours}h ${minutes}m left`); } }, 1000); return () => clearInterval(interval); }, [trialStatus]); const handleCancelTrial = async () => { if (!confirm("Are you sure you want to cancel your free trial? You will lose access immediately.")) return; setLoadingPlan("cancel_trial"); try { const res = await fetch(`${ApiServerBaseUrl}/payment/cancel`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ session_id: trialStatus?.stripeSessionId }) }); const data = await res.json(); localStorage.removeItem('payment_session'); localStorage.removeItem('paymentDetails'); alert(data.message); window.location.reload(); } catch (err) { alert("Failed to cancel trial"); } setLoadingPlan(null); }; const plans: Plan[] = [ { name: "Basic Buddy", desc: "Perfect for individual creators.", amountMonthly: 10, amountYearly: 100, features: [ "1 Social Profiles", "Basic Analytics", "Content Scheduling", "Standard Support", ], planIdMonthly: "basic_monthly", planIdYearly: "basic_yearly", }, { name: "Standard Buddy", desc: "For growing businesses and influencers.", amountMonthly: 50, amountYearly: 500, features: [ "10 Social Profiles", "Advanced Analytics", "AI Content Generation", "Priority Support", "Team Collaboration (up to 3)", ], popular: true, planIdMonthly: "standard_monthly", planIdYearly: "standard_yearly", }, { name: "Premium Buddy", desc: "Ultimate solution for agencies.", amountMonthly: 150, amountYearly: 1500, features: [ "25 Social Profiles", "White Label Reports", "Dedicated Account Manager", "API Access", "Unlimited Team Members", ], planIdMonthly: "premium_monthly", planIdYearly: "premium_yearly", }, ]; const freeTrialPlan: Plan = { name: "7-Day Free Trial", desc: "Experience SocialBuddy with no commitment. Full access to all features.", amountMonthly: 0, amountYearly: 0, features: [ "Full Platform Access", "All Premium Features", "No Credit Card Required", "Cancel Anytime", ], planIdMonthly: "free_trial", planIdYearly: "free_trial", }; const handleSubscribe = async (plan: Plan) => { const selectedPriceId = billingCycle === "monthly" ? plan.planIdMonthly : plan.planIdYearly; setLoadingPlan(plan.name); try { const email = localStorage.getItem("user_email"); const userId: any = localStorage.getItem("userId"); if (plan.planIdMonthly === "free_trial") { // --- FREE TRIAL FLOW --- const res = await fetch(`${ApiServerBaseUrl}/payment/activate-trial`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, userId }), }); const data = await res.json(); if (data.success) { if (data.payment && data.payment.sessionId) { localStorage.setItem('payment_session', data.payment.sessionId); localStorage.setItem('paymentDetails', JSON.stringify(data.payment)); } alert(data.message); window.location.reload(); } else { alert(data.error || "Failed to activate trial"); } } else { // --- STRIPE FLOW --- const res = await fetch( `${ApiServerBaseUrl}/payment/create-checkout-session`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email, userId, planId: selectedPriceId, }), } ); const data = await res.json(); if (data.url) { window.location.href = data.url; } else { alert("Stripe session creation failed."); } } } catch (error) { alert("Payment error — check console."); console.error(error); } setLoadingPlan(null); }; return (
{/* Billing Toggle */}
{/* Free Trial Banner */}
Limited Offer {!(trialStatus?.hasUsedTrial && !trialStatus?.isTrialActive) && ( ⭐ Recommended )}

{trialStatus?.isTrialActive ? "Your Free Trial is Active!" : trialStatus?.hasUsedTrial ? "Free Trial Ended" : freeTrialPlan.name}

{trialStatus?.isTrialActive ? "Enjoy full access to all premium features. Check your dashboard for insights." : trialStatus?.hasUsedTrial ? "You have already used your free trial. Please select a plan to continue." : freeTrialPlan.desc}

{/* Show features list only if not used or active */} {!trialStatus?.isTrialActive && !trialStatus?.hasUsedTrial && (
{freeTrialPlan.features.map((f, i) => (
{f}
))}
)}
{trialStatus?.isTrialActive ? ( // --- ACTIVE TRIAL STATE ---

Time Remaining

{timeLeft || "Calculating..."}

Cancelling will end your access immediately.

) : trialStatus?.hasUsedTrial ? ( // --- USED / EXPIRED STATE ---
Used

One-time offer only.

) : ( // --- SUBSCRIBE STATE --- <>
$0 / 7 days

No commitment, cancel anytime.

)}
{/* Pricing Plans */}
{plans.map((plan) => (
{plan.popular && (
MOST POPULAR
)}

{plan.name}

{plan.desc}

{/* Price */}
$ {billingCycle === "monthly" ? plan.amountMonthly : plan.amountYearly} /{billingCycle === "monthly" ? "mo" : "yr"}
{/* Features */}
    {plan.features.map((f, i) => (
  • {f}
  • ))}
{/* FIXED BUTTON */}
))}
); }; export default ComponentsPricingTableToggle;