import { lazy, Suspense, useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import { qk } from "../lib/queryKeys";
import { useQuery } from "@tanstack/react-query";
import { api } from "../lib/api";
import { shouldAutoOpenOnboarding } from "../lib/onboarding";
import { WizardActionsContext, type WizardActions } from "./wizardContext";
const OnboardingWizard = lazy(() => import("./OnboardingWizard"));
// Owns the onboarding wizard's open state (and the wizard render itself), lifted out of App so any
// module can trigger "connect YouTube" via a hook instead of an onOpenWizard prop threaded through
// the tree. Mirrors the other split-context providers; composed in main.tsx around .
//
// The wizard auto-opens on first login for accounts that still need to connect YouTube (derived from
// granted scopes + storage flags, so it's stable across the OAuth round-trip) and is reopenable from
// Settings / the notify "reconnect" action. It reads `me` as a passive qk.me() observer (BootGate owns
// the fetching query), so it re-runs the auto-open check when the account's grants change.
//
// The actions context + hook live in wizardContext.ts.
export function WizardProvider({ children }: { children: ReactNode }) {
const [open, setOpen] = useState(false);
// Passive observer of the account BootGate fetches (enabled:false → reads cache, re-renders on update).
const { data: me } = useQuery({ queryKey: qk.me(), queryFn: api.me, enabled: false });
const openWizard = useCallback(() => setOpen(true), []);
const closeWizard = useCallback(() => setOpen(false), []);
// First-login onboarding: prompt the user to connect YouTube (and resume the flow after each
// consent redirect). Re-checked when the account or its grants change.
// Keyed on the fields that matter, NOT the `me` object: the 60 s refetch hands out a new object,
// and re-running on that would reopen a wizard the user just closed. `can_write` is read by nothing
// here but is a trigger: a completed write grant resumes the flow.
const meId = me?.id;
const canRead = me?.can_read;
const canWrite = me?.can_write;
const isDemo = me?.is_demo;
const googleEnabled = me?.google_enabled;
useEffect(() => {
if (meId == null || canRead == null) return;
const account = { can_read: canRead, is_demo: isDemo, google_enabled: googleEnabled };
// eslint-disable-next-line react-hooks/set-state-in-effect -- opening is a one-way decision taken from SERVER data as it arrives, not a value derivable in render — deriving `open` from the grants would re-open a wizard the user had just closed, which is exactly what the narrowed dep list above exists to prevent.
if (shouldAutoOpenOnboarding(account)) setOpen(true);
}, [meId, canRead, canWrite, isDemo, googleEnabled]);
const actions = useMemo(
() => ({ openWizard, closeWizard }),
[openWizard, closeWizard],
);
return (
{children}
{/* The wizard is a full-screen overlay; the demo account can't connect YouTube, so it never
opens there. Lazy — its chunk loads only when first opened. */}
{open && me && !me.is_demo && }
);
}