'use client';

import { useEffect, useState } from 'react';
import { Auth0Provider } from '@auth0/auth0-react';
import { ThemeProvider } from '@tidbcloud/uikit/theme';
import { LocaleProvider } from '@/lib/i18n';

interface RuntimeConfig {
  auth0Domain: string;
  auth0ClientId: string;
}

/**
 * Fetch Auth0 runtime config from the server-side API route.
 * This avoids the NEXT_PUBLIC_* build-time limitation so the same Docker
 * image works across environments (dev / staging / prod) by reading env
 * vars injected by Kubernetes at container startup.
 */
const API_BASE = process.env.NEXT_PUBLIC_API_URL ?? '';

async function fetchRuntimeConfig(): Promise<RuntimeConfig> {
  try {
    const res = await fetch(`${API_BASE}/api/config`);
    if (res.ok) return res.json();
  } catch {
    // ignore — falls back to empty config (email-only login)
  }
  return { auth0Domain: '', auth0ClientId: '' };
}

export function Providers({ children }: { children: React.ReactNode }) {
  const [config, setConfig] = useState<RuntimeConfig | null>(null);

  useEffect(() => {
    fetchRuntimeConfig().then(setConfig);
  }, []);

  const inner = (
    <ThemeProvider colorScheme="light">
      <LocaleProvider>{children}</LocaleProvider>
    </ThemeProvider>
  );

  // Wait until config is loaded; then conditionally enable Auth0Provider.
  if (!config) return inner;

  const auth0Enabled = Boolean(config.auth0Domain && config.auth0ClientId);

  // Check if running on secure origin (https or localhost)
  const isSecureOrigin = typeof window !== 'undefined' &&
    (window.location.protocol === 'https:' ||
     window.location.hostname === 'localhost' ||
     window.location.hostname === '127.0.0.1');

  // Only enable Auth0 if both config exists AND running on secure origin
  if (!auth0Enabled || !isSecureOrigin) return inner;

  return (
    <Auth0Provider
      domain={config.auth0Domain}
      clientId={config.auth0ClientId}
      authorizationParams={{
        redirect_uri: typeof window !== 'undefined' ? `${window.location.origin}/auth/callback` : '',
        connection: 'google-oauth2',
      }}
    >
      {inner}
    </Auth0Provider>
  );
}
