'use client'

// AUTO-GENERATED by mizan — do not edit

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

import { fetchGlobalContext, type GlobalContextData, type GlobalContextParams, fetchLocalContext, type LocalContextData, type LocalContextParams, callEcho, callAdd, callWhoami, callHttpOnlyEcho, callStaffOnly, callSuperuserOnly, callVerifiedOnly, callMultiply, callNotImplementedFn, callBuggyFn, callPermissionCheckFn, callWsWhoami, callJwtObtain, callJwtRefresh } from '../index'

// Subscribe to kernel state via useSyncExternalStore
function useContextState<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

    // Fetch on mount if no data
    useEffect(() => {
        if (handle.getState().status === 'idle') handle.refetch()
        return () => handle.unregister()
    }, [handle])

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

// Mutation hook with loading/error state
function useMutation<TArgs, TResult>(
    callFn: (args: TArgs) => Promise<TResult>,
): { mutate: (args: TArgs) => Promise<TResult>; isPending: boolean; error: Error | null } {
    const [isPending, setIsPending] = useState(false)
    const [error, setError] = useState<Error | null>(null)

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

    return { mutate, isPending, error }
}

// ── Global Context ──

export function useGlobalContext(): ContextState<GlobalContextData> {
    const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : null
    return useContextState('global', {}, () => fetchGlobalContext({} as any), ssrData)
}

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

// ── Local Context ──

export function useLocalContext(params: LocalContextParams): ContextState<LocalContextData> {
    const ssrData = typeof window !== 'undefined' ? (window as any).__MIZAN_SSR_DATA__ : null
    return useContextState('local', params, () => fetchLocalContext(params), ssrData)
}

export function useGreet(params: LocalContextParams): greetOutput | null {
    const state = useLocalContext(params)
    return state.data?.greet ?? 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 useWhoami() {
    return useMutation<void, Awaited<ReturnType<typeof callWhoami>>>(() => callWhoami() as any)
}

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

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 useMultiply() {
    return useMutation<Parameters<typeof callMultiply>[0], Awaited<ReturnType<typeof callMultiply>>>(callMultiply)
}

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 useWsWhoami() {
    return useMutation<void, Awaited<ReturnType<typeof callWsWhoami>>>(() => callWsWhoami() as any)
}

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

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

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