import { useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import type { Organization } from 'fhir/r4'; import { isWpAdminMount } from './mountContext'; // A founder signs up and signs in after the practice exists. Sign-up and sign-in drop any query and may // continue in another tab, so where they land is kept in localStorage for that practice. const KEY = 'akashic.founderLanding'; const MAX_AGE_MS = 24 * 60 * 60 * 1000; // The Administrator workspace's practice dashboard, where a new practice's setup guide is open. export const FOUNDER_LANDING = '/dashboard/organization'; export const rememberFounderLanding = (organizationId: string): void => { try { localStorage.setItem(KEY, JSON.stringify({ organizationId, at: Date.now() })); } catch { // storage unavailable: the founder lands on their workspace's own default instead } }; export const takeFounderLanding = (organizationId: string): boolean => { try { const raw = localStorage.getItem(KEY); if (!raw) return false; const landing = JSON.parse(raw) as { organizationId?: unknown; at?: unknown }; if (typeof landing.at !== 'number' || Date.now() - landing.at > MAX_AGE_MS) { localStorage.removeItem(KEY); return false; } if (landing.organizationId !== organizationId) return false; localStorage.removeItem(KEY); return true; } catch { return false; } }; // `onTaken` lets the dashboard stand down its own sign-in landing, which would otherwise race this. // Founding here happens only in WordPress admin; a hosted practice address keeps its own landing. export const useFounderLanding = (organization: Organization | null | undefined, onTaken?: () => void): void => { const navigate = useNavigate(); const organizationId = organization?.id; useEffect(() => { if (organizationId && isWpAdminMount() && takeFounderLanding(organizationId)) { onTaken?.(); navigate(FOUNDER_LANDING, { replace: true }); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [organizationId, navigate]); };