/opt/canhelp/apps/web/src/components
Edit: /opt/canhelp/apps/web/src/components/AdminRolePreview.tsx (4928B)
'use client'
import { useSession } from '@/lib/auth'
import { useRouter } from 'next/navigation'
import { useEffect, useState, useRef } from 'react'
import { getPlans, updateAdminUser, type Plan } from '@/lib/api'
const ORIG_PLAN_KEY = 'canhelp_admin_orig_plan'
function getPreviewRole(): null {
return null
}
const TIER_COLORS: Record
= {
free: 'bg-slate-100 text-slate-600',
pro: 'bg-green-100 text-green-700',
ultimate: 'bg-amber-100 text-amber-700',
}
export function AdminRolePreview() {
const { data: session } = useSession()
const router = useRouter()
const isAdmin = (session?.user as any)?.role === 'admin'
const userId = (session?.user as any)?.id as string | undefined
const [mounted, setMounted] = useState(false)
const [plans, setPlans] = useState([])
const [activePlanId, setActivePlanId] = useState(null)
const [loading, setLoading] = useState(false)
const [expanded, setExpanded] = useState(false)
const origPlanRef = useRef(null)
useEffect(() => setMounted(true), [])
useEffect(() => {
if (typeof window !== 'undefined') {
origPlanRef.current = localStorage.getItem(ORIG_PLAN_KEY)
}
}, [])
useEffect(() => {
if (!isAdmin) return
getPlans().then(setPlans).catch(() => {})
}, [isAdmin])
useEffect(() => {
// Sync active plan from session
const currentPlanId = (session?.user as any)?.planId ?? null
setActivePlanId(currentPlanId)
}, [session])
if (!mounted || !isAdmin) return null
const setPlan = async (planId: string | null) => {
if (!userId) return
setLoading(true)
try {
// Save original plan on first change
if (!origPlanRef.current && activePlanId) {
localStorage.setItem(ORIG_PLAN_KEY, activePlanId)
origPlanRef.current = activePlanId
}
await updateAdminUser(userId, { planId })
setActivePlanId(planId)
window.dispatchEvent(new CustomEvent('canhelp:plan-changed', { detail: { planId } }))
router.refresh()
} catch {}
setLoading(false)
}
const restorePlan = async () => {
const orig = origPlanRef.current
localStorage.removeItem(ORIG_PLAN_KEY)
origPlanRef.current = null
await setPlan(orig ?? null)
}
const visiblePlans = plans
const hasOrigPlan = !!origPlanRef.current
return (
{/* Header — always visible, click to expand */}
{expanded && (
{/* Plan selector */}
{visiblePlans.length > 0 && (
<>
Plan
{visiblePlans.map((plan) => (
))}
{activePlanId && (
)}
{hasOrigPlan && (
)}
>
)}
)}
)
}