"use client"; import React, { createContext, useContext, useState } from "react"; interface TrialVariantSelectionContextValue { selectedVariantId: string | null; setSelectedVariantId: (variantId: string | null) => void; } const TrialVariantSelectionContext = createContext(null); const STORAGE_KEY = 'trial_variant_selection'; export function TrialVariantSelectionProvider({ children, }: { children: React.ReactNode; }) { // Initialize from sessionStorage if available const [selectedVariantId, setSelectedVariantId] = useState(() => { if (typeof window === 'undefined') return null; const stored = sessionStorage.getItem(STORAGE_KEY); return stored || null; }); const wrappedSetSelectedVariantId = (id: string | null) => { setSelectedVariantId(id); // Persist to sessionStorage if (typeof window !== 'undefined') { if (id) { sessionStorage.setItem(STORAGE_KEY, id); } else { sessionStorage.removeItem(STORAGE_KEY); } } }; return ( {children} ); } export function useTrialVariantSelection() { const context = useContext(TrialVariantSelectionContext); if (!context) { throw new Error( "useTrialVariantSelection must be used within TrialVariantSelectionProvider" ); } return context; }