'use client'

// AUTO-GENERATED by mizan — do not edit

import {
    createContext,
    useCallback,
    useContext,
    useEffect,
    useRef,
    useState,
    useSyncExternalStore,
    type ReactNode,
} from 'react'
import {
    configure,
    initSession,
    mizanCall,
    mizanFetch,
    MizanError,
    registerContext,
    type ContextState,
} from '@mizan/base'

import { fetchGlobalContext, type GlobalContextData, type GlobalContextParams, fetchMorphsContext, type MorphsContextData, type MorphsContextParams, callEcho, callAdd, callMultiply, callWhoami, callStaffOnly, callSuperuserOnly, callVerifiedOnly, callNotImplementedFn, callBuggyFn, callPermissionCheckFn, callSetMorphValue, type currentUserOutput, type morphGroupsOutput, type morphLayersOutput } from './index'

// Internal — runs inside a Provider, registers with the kernel exactly once.
function useContextSubscription<T>(
    name: string,
    params: Record<string, any>,
    fetchFn: () => Promise<T>,
    initialData?: T,
): ContextState<T> {
    const ref = useRef<ReturnType<typeof registerContext> | null>(null)
    if (!ref.current) {
        ref.current = registerContext(name, params, fetchFn, initialData)
    }
    const handle = ref.current

    useEffect(() => {
        if (handle.getState().status === 'idle') handle.refetch()
        return () => handle.unregister()
    }, [handle])

    return useSyncExternalStore(handle.subscribe, handle.getState, handle.getState)
}

// Internal — wraps an imperative call() with isPending / error state.
interface MutationHook<TArgs, TResult> {
    mutate: (args: TArgs) => Promise<TResult>
    isPending: boolean
    error: Error | null
}

function useMutation<TArgs, TResult>(
    callFn: (args: TArgs) => Promise<TResult>,
): MutationHook<TArgs, TResult> {
    const [isPending, setIsPending] = useState(false)
    const [error, setError] = useState<Error | null>(null)

    const mutate = useCallback(async (args: TArgs) => {
        setIsPending(true)
        setError(null)
        try {
            return await callFn(args)
        } catch (e) {
            setError(e as Error)
            throw e
        } finally {
            setIsPending(false)
        }
    }, [callFn])

    return { mutate, isPending, error }
}

// ── Global Context ──

const GlobalCtx = createContext<ContextState<GlobalContextData> | null>(null)

export function GlobalContextProvider({ children }: { children: ReactNode }) {
    const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : undefined
    const state = useContextSubscription('global', {}, () => fetchGlobalContext({} as any), ssrData)
    return <GlobalCtx.Provider value={state}>{children}</GlobalCtx.Provider>
}

export function useGlobalContext(): ContextState<GlobalContextData> {
    const ctx = useContext(GlobalCtx)
    if (!ctx) throw new Error('useGlobalContext requires <MizanContext> or <GlobalContextProvider>')
    return ctx
}

export function useCurrentUser(): currentUserOutput | null {
    return useGlobalContext().data?.current_user ?? null
}

// ── Morphs Context ──

const MorphsCtx = createContext<ContextState<MorphsContextData> | null>(null)

export function MorphsContext({ children }: { children: ReactNode }) {
    const state = useContextSubscription('morphs', {}, () => fetchMorphsContext({} as any))
    return <MorphsCtx.Provider value={state}>{children}</MorphsCtx.Provider>
}

export function useMorphsContext(): ContextState<MorphsContextData> {
    const ctx = useContext(MorphsCtx)
    if (!ctx) throw new Error('useMorphsContext requires <MorphsContext>')
    return ctx
}

export function useMorphGroups(): morphGroupsOutput | null {
    return useMorphsContext().data?.morph_groups ?? null
}

export function useMorphLayers(): morphLayersOutput | null {
    return useMorphsContext().data?.morph_layers ?? null
}

export function useEcho() {
    return useMutation<Parameters<typeof callEcho>[0], Awaited<ReturnType<typeof callEcho>>>(callEcho)
}

export function useAdd() {
    return useMutation<Parameters<typeof callAdd>[0], Awaited<ReturnType<typeof callAdd>>>(callAdd)
}

export function useMultiply() {
    return useMutation<Parameters<typeof callMultiply>[0], Awaited<ReturnType<typeof callMultiply>>>(callMultiply)
}

export function useWhoami() {
    return useMutation<void, Awaited<ReturnType<typeof callWhoami>>>(() => callWhoami() as any)
}

export function useStaffOnly() {
    return useMutation<void, Awaited<ReturnType<typeof callStaffOnly>>>(() => callStaffOnly() as any)
}

export function useSuperuserOnly() {
    return useMutation<void, Awaited<ReturnType<typeof callSuperuserOnly>>>(() => callSuperuserOnly() as any)
}

export function useVerifiedOnly() {
    return useMutation<void, Awaited<ReturnType<typeof callVerifiedOnly>>>(() => callVerifiedOnly() as any)
}

export function useNotImplementedFn() {
    return useMutation<void, Awaited<ReturnType<typeof callNotImplementedFn>>>(() => callNotImplementedFn() as any)
}

export function useBuggyFn() {
    return useMutation<void, Awaited<ReturnType<typeof callBuggyFn>>>(() => callBuggyFn() as any)
}

export function usePermissionCheckFn() {
    return useMutation<Parameters<typeof callPermissionCheckFn>[0], Awaited<ReturnType<typeof callPermissionCheckFn>>>(callPermissionCheckFn)
}

export function useSetMorphValue() {
    return useMutation<Parameters<typeof callSetMorphValue>[0], Awaited<ReturnType<typeof callSetMorphValue>>>(callSetMorphValue)
}

// ── MizanContext root provider ──

export interface MizanContextProps {
    /** Base URL for protocol endpoints. Defaults to "/api/mizan". */
    baseUrl?: string
    /** Set to `false` for backends without a `/session/` endpoint (e.g. FastAPI). */
    session?: boolean
    children: ReactNode
}

/**
 * Root provider — calls configure() once and mounts the global context (if defined).
 * Must wrap any component using Mizan-generated hooks.
 */
export function MizanContext({ baseUrl, session, children }: MizanContextProps) {
    const configured = useRef(false)
    if (!configured.current) {
        const opts: Parameters<typeof configure>[0] = {}
        if (baseUrl !== undefined) opts.baseUrl = baseUrl
        if (session !== undefined) opts.session = session
        if (Object.keys(opts).length > 0) configure(opts)
        configured.current = true
    }
    return <GlobalContextProvider>{children}</GlobalContextProvider>
}

// ── Imperative escape hatch ──

/**
 * Returns the imperative kernel API. For test harnesses or rare cases where
 * a typed generated hook does not fit. Most app code should use the typed hooks.
 */
export function useMizan() {
    return { call: mizanCall, fetch: mizanFetch }
}

export type { ContextState } from '@mizan/base'
export { configure, initSession, MizanError } from '@mizan/base'
