'use client';

import { useEffect, useState } from 'react';
import { useAuth } from '@/components/id/auth-provider';
import { useEmbeddedAuthFallback } from '@/lib/embedded-auth-bridge';

const EMBEDDED_AUTH_WAIT_MS = 4000;

export function useMiniAppAuth() {
  const { token, isPinLocked, isLoading } = useAuth();
  const embeddedToken = useEmbeddedAuthFallback();
  const isEmbedded = typeof window !== 'undefined' && window.parent !== window;
  const [bridgeTimedOut, setBridgeTimedOut] = useState(false);

  useEffect(() => {
    if (!isEmbedded) {
      setBridgeTimedOut(true);
      return;
    }
    const timer = window.setTimeout(() => setBridgeTimedOut(true), EMBEDDED_AUTH_WAIT_MS);
    return () => window.clearTimeout(timer);
  }, [isEmbedded]);

  const effectiveToken = token ?? embeddedToken;
  const waitingForBridge = isEmbedded && !effectiveToken && !bridgeTimedOut;
  const authReady = !isEmbedded || Boolean(effectiveToken) || bridgeTimedOut || !isLoading;
  const canUse = Boolean(effectiveToken && (!isPinLocked || Boolean(embeddedToken)));

  return {
    effectiveToken,
    canUse,
    authReady,
    waitingForBridge,
    isEmbedded,
    isLoading
  };
}
