import React, { useState, useEffect } from 'react';
import { CONFIGURED_BACKEND_HOST, API_CONFIG } from '../../infrastructure/config/environment';
import { STORAGE_KEYS as GLOBAL_STORAGE_KEYS } from '../../infrastructure/storage/storageKeys';
import {
  getHostExternalIdentityProvider,
  HOST_AUTH_PROVIDER_IDS,
  isHostReservedAuthProviderId,
  type HostLoginPresentationProps,
  type HostExternalIdentityProvider,
  type HostPublicLoginProvider,
} from '@nexuscrm/host-sdk';

// Storage keys — CONNECTION_MODE uses centralized key, others are login-screen-local
const STORAGE_KEYS = {
  CONNECTION_MODE: GLOBAL_STORAGE_KEYS.CONNECTION_MODE,
} as const;

const BACKEND_CONNECTION_MODE = HOST_AUTH_PROVIDER_IDS.BACKEND;
const CUSTOM_ENVIRONMENT_ID = 'custom';

type ConnectionMode = typeof BACKEND_CONNECTION_MODE | string;

const LOGIN_PROVIDER_IDS = {
  BACKEND: HOST_AUTH_PROVIDER_IDS.BACKEND,
  GOOGLE: HOST_AUTH_PROVIDER_IDS.GOOGLE,
  TOKEN: HOST_AUTH_PROVIDER_IDS.TOKEN,
} as const;

function providerStoragePrefix(provider: HostExternalIdentityProvider): string {
  return provider.storageKeyPrefix ?? provider.id;
}

function providerClientIdStorageKey(provider: HostExternalIdentityProvider): string {
  return `${providerStoragePrefix(provider)}_client_id`;
}

function providerClientSecretStorageKey(provider: HostExternalIdentityProvider): string {
  return `${providerStoragePrefix(provider)}_client_secret`;
}

function providerEnvironmentStorageKey(provider: HostExternalIdentityProvider): string {
  return `${providerStoragePrefix(provider)}_environment`;
}

function readLocalStorageWithFallback(primaryKey: string, fallbackKeys: readonly string[] = []): string | null {
  const primaryValue = localStorage.getItem(primaryKey);
  if (primaryValue) {
    return primaryValue;
  }
  for (const fallbackKey of fallbackKeys) {
    const fallbackValue = localStorage.getItem(fallbackKey);
    if (fallbackValue) {
      localStorage.setItem(primaryKey, fallbackValue);
      return fallbackValue;
    }
  }
  return null;
}

function readSessionStorageWithFallback(primaryKey: string, fallbackKeys: readonly string[] = []): string | null {
  const primaryValue = sessionStorage.getItem(primaryKey);
  if (primaryValue) {
    return primaryValue;
  }
  for (const fallbackKey of fallbackKeys) {
    const fallbackValue = sessionStorage.getItem(fallbackKey);
    if (fallbackValue) {
      sessionStorage.setItem(primaryKey, fallbackValue);
      return fallbackValue;
    }
  }
  return null;
}

function selectProviderEnvironment(provider: HostExternalIdentityProvider, environmentId: string) {
  return provider.environments.find((environment) => environment.id === environmentId)
    ?? provider.environments.find((environment) => environment.id === provider.defaultEnvironmentId)
    ?? provider.environments[0];
}

function environmentBadgeClasses(tone: HostExternalIdentityProvider['environments'][number]['badgeTone']) {
  switch (tone) {
    case 'warning':
      return {
        container: 'bg-amber-500/20 text-amber-300 border-amber-500/30',
        dot: 'bg-amber-400',
      };
    case 'success':
      return {
        container: 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30',
        dot: 'bg-emerald-400',
      };
    default:
      return {
        container: 'bg-blue-500/20 text-blue-200 border-blue-500/30',
        dot: 'bg-blue-300',
      };
  }
}

function displayEnvironmentLabel(label: string): string {
  return label || 'Environment';
}

export function LoginScreen({ onLogin, onLoginWithToken, loginError, authorizeContinue, actions }: HostLoginPresentationProps) {
  const backendEmailInputId = 'backend-login-email';
  const backendPasswordInputId = 'backend-login-password';
  const externalClientIdInputId = 'external-identity-client-id';
  const externalClientSecretInputId = 'external-identity-client-secret';
  const tokenInputId = 'token-login-token';
  const tokenInstanceUrlInputId = 'token-login-instance-url';
  // UI State
  const [isLoading, setIsLoading] = useState(false);
  const [isProviderConfigLoading, setIsProviderConfigLoading] = useState(true);
  const [isProviderConfigError, setIsProviderConfigError] = useState(false);
  const [oauthInitializationError, setOAuthInitializationError] = useState<string | null>(null);
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [showForgotPassword, setShowForgotPassword] = useState(false);
  const [forgotEmail, setForgotEmail] = useState('');
  const [forgotSent, setForgotSent] = useState(false);
  const [publicLoginProviders, setPublicLoginProviders] = useState<HostPublicLoginProvider[]>([]);

  // Connection Mode
  const [connectionMode, setConnectionMode] = useState<ConnectionMode>(() => {
    const storedMode = localStorage.getItem(STORAGE_KEYS.CONNECTION_MODE)?.trim();
    if (!storedMode || storedMode === BACKEND_CONNECTION_MODE) {
      return BACKEND_CONNECTION_MODE;
    }
    return getHostExternalIdentityProvider(storedMode) ? storedMode : BACKEND_CONNECTION_MODE;
  });

  // Backend Mode State
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  // External identity mode state. Provider-specific defaults and storage keys
  // come from the app-owned HostExternalIdentityProvider definition.
  const [clientId, setClientId] = useState('');
  const [clientSecret, setClientSecret] = useState('');
  const [environment, setEnvironment] = useState('');
  const [customDomain, setCustomDomain] = useState('');

  // Token Login (Advanced)
  const [token, setToken] = useState('');
  const [tokenInstanceUrl, setTokenInstanceUrl] = useState('https://your-org.example.com');

  useEffect(() => {
    let cancelled = false;

    const loadPublicLoginProviders = async () => {
      try {
        const response = await actions.getPublicLoginOptions();
        if (!cancelled) {
          setIsProviderConfigError(false);
          setPublicLoginProviders(response.providers);
        }
      } catch {
        if (!cancelled) {
          setIsProviderConfigError(true);
          setPublicLoginProviders([]);
        }
      } finally {
        if (!cancelled) {
          setIsProviderConfigLoading(false);
        }
      }
    };

    void loadPublicLoginProviders();

    return () => {
      cancelled = true;
    };
  }, [actions]);

  const googleProvider = publicLoginProviders.find((provider) => provider.id === LOGIN_PROVIDER_IDS.GOOGLE);
  const unresolvedExternalLoginProviders = publicLoginProviders.filter((provider) => (
    !isHostReservedAuthProviderId(provider.id) && !getHostExternalIdentityProvider(provider.id)
  ));
  const externalIdentityProviders = publicLoginProviders
    .map((loginProvider) => ({
      loginProvider,
      identityProvider: getHostExternalIdentityProvider(loginProvider.id),
    }))
    .filter((entry): entry is { loginProvider: HostPublicLoginProvider; identityProvider: HostExternalIdentityProvider } => (
      !!entry.identityProvider
    ));
  const googleEnabled = !!googleProvider?.clientId;
  const backendEnabled = publicLoginProviders.some((provider) => provider.id === LOGIN_PROVIDER_IDS.BACKEND);
  const tokenEnabled = !!onLoginWithToken && publicLoginProviders.some((provider) => provider.id === LOGIN_PROVIDER_IDS.TOKEN);
  const providerConfigurationError = unresolvedExternalLoginProviders.length > 0
    ? `Sign-in provider is not available: ${unresolvedExternalLoginProviders.map((provider) => provider.label || provider.id).join(', ')}. Ask your administrator to update the frontend app pack.`
    : null;
  const availableConnectionModes = [
    backendEnabled ? BACKEND_CONNECTION_MODE : null,
    ...externalIdentityProviders.map(({ identityProvider }) => identityProvider.id),
  ].filter((mode): mode is ConnectionMode => mode !== null);
  const activeConnectionMode = availableConnectionModes.includes(connectionMode)
    ? connectionMode
    : availableConnectionModes[0] ?? null;
  const activeExternalIdentityEntry = activeConnectionMode && activeConnectionMode !== BACKEND_CONNECTION_MODE
    ? externalIdentityProviders.find(({ identityProvider }) => identityProvider.id === activeConnectionMode)
    : undefined;
  const activeExternalIdentityProvider = activeExternalIdentityEntry?.identityProvider;
  const activeExternalLoginProvider = activeExternalIdentityEntry?.loginProvider;
  const hasConnectionModes = availableConnectionModes.length > 0;
  const hasMultipleConnectionModes = availableConnectionModes.length > 1;
  const hasAdvancedProviders = hasConnectionModes || tokenEnabled;
  const hasActionableProviders = googleEnabled || hasAdvancedProviders;
  const advancedPanelVisible = !googleEnabled || showAdvanced;
  // Provider-driven label for the affordance that reveals the demoted sign-in
  // methods. Never hardcodes a single provider: it reflects whatever remains
  // behind Google SSO (backend password, external identity, or token).
  const advancedToggleLabel = backendEnabled
    ? 'Administrator sign-in'
    : externalIdentityProviders.length > 0
      ? 'Sign in another way'
      : 'Other sign-in options';
  const footerText = activeExternalIdentityProvider
    ? 'Secure OAuth 2.0 with PKCE'
    : tokenEnabled && !hasConnectionModes && !googleEnabled
      ? 'Secure token-based access'
      : googleEnabled && !hasAdvancedProviders
        ? 'Secure sign-in with Google'
        : 'Secure connection to NexusCRM backend';

  useEffect(() => {
    if (activeConnectionMode && activeConnectionMode !== connectionMode) {
      setConnectionMode(activeConnectionMode);
    }
  }, [activeConnectionMode, connectionMode]);

  useEffect(() => {
    if (!activeExternalIdentityProvider) {
      return;
    }

    const defaultEnvironment = activeExternalLoginProvider?.defaultEnvironment
      ?? activeExternalIdentityProvider.defaultEnvironmentId
      ?? activeExternalIdentityProvider.environments[0]?.id
      ?? '';
    const savedEnvironment = readLocalStorageWithFallback(
      providerEnvironmentStorageKey(activeExternalIdentityProvider),
      activeExternalIdentityProvider.legacyStorageKeys?.environment,
    )
      || defaultEnvironment;
    const savedClientId = readLocalStorageWithFallback(
      providerClientIdStorageKey(activeExternalIdentityProvider),
      activeExternalIdentityProvider.legacyStorageKeys?.clientId,
    )
      || activeExternalLoginProvider?.clientId
      || '';
    const savedClientSecret = readSessionStorageWithFallback(
      providerClientSecretStorageKey(activeExternalIdentityProvider),
      activeExternalIdentityProvider.legacyStorageKeys?.clientSecret,
    ) || '';

    setEnvironment(savedEnvironment);
    setClientId(savedClientId);
    setClientSecret(savedClientSecret);

    if (activeExternalIdentityProvider.defaultTokenInstanceUrl) {
      setTokenInstanceUrl((current) => (
        !current.trim() || current === 'https://your-org.example.com'
          ? activeExternalIdentityProvider.defaultTokenInstanceUrl || current
          : current
      ));
    }
  }, [
    activeExternalIdentityProvider,
    activeExternalLoginProvider?.clientId,
    activeExternalLoginProvider?.defaultEnvironment,
  ]);

  // Persist config changes
  useEffect(() => {
    localStorage.setItem(STORAGE_KEYS.CONNECTION_MODE, connectionMode);
    if (!activeExternalIdentityProvider) {
      return;
    }

    const clientIdKey = providerClientIdStorageKey(activeExternalIdentityProvider);
    const clientSecretKey = providerClientSecretStorageKey(activeExternalIdentityProvider);
    const environmentKey = providerEnvironmentStorageKey(activeExternalIdentityProvider);

    if (clientId.trim()) {
      localStorage.setItem(clientIdKey, clientId.trim());
    } else {
      localStorage.removeItem(clientIdKey);
    }

    if (clientSecret.trim()) {
      sessionStorage.setItem(clientSecretKey, clientSecret.trim());
    } else {
      sessionStorage.removeItem(clientSecretKey);
    }

    if (environment) {
      localStorage.setItem(environmentKey, environment);
    }
  }, [connectionMode, activeExternalIdentityProvider, clientId, clientSecret, environment]);

  const selectedExternalEnvironment = activeExternalIdentityProvider
    ? selectProviderEnvironment(activeExternalIdentityProvider, environment)
    : undefined;
  const externalCustomDomain = activeExternalIdentityProvider?.customDomain;
  const isCustomExternalEnvironment = !!externalCustomDomain && environment === CUSTOM_ENVIRONMENT_ID;
  const instanceUrl = activeExternalIdentityProvider
    ? isCustomExternalEnvironment
      ? externalCustomDomain.buildAuthorizationBaseUrl(customDomain.trim())
      : selectedExternalEnvironment?.authorizationBaseUrl ?? ''
    : '';
  const externalBadge = environmentBadgeClasses(selectedExternalEnvironment?.badgeTone ?? 'neutral');
  const backendDisplayUrl = API_CONFIG.BACKEND_URL || CONFIGURED_BACKEND_HOST;

  // Forgot password handler
  const handleForgotPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!forgotEmail.trim()) return;
    setIsLoading(true);
    try {
      await actions.forgotPassword(forgotEmail.trim());
      setForgotSent(true);
    } catch {
      setForgotSent(true);
    } finally {
      setIsLoading(false);
    }
  };

  // Google SSO handler
  const handleGoogleLogin = async () => {
    if (!googleProvider?.clientId) return;
    setIsLoading(true);
    setOAuthInitializationError(null);
    try {
      await actions.initializeOAuth({
        providerId: LOGIN_PROVIDER_IDS.GOOGLE,
        clientId: googleProvider.clientId,
        authorizeContinue,
      });
    } catch {
      setOAuthInitializationError('Unable to start Google sign-in. Please try again.');
      setIsLoading(false);
    }
  };

  // Backend login handler
  const handleBackendLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!email.trim() || !password) return;

    setIsLoading(true);
    try {
      await onLogin(email.trim(), password);
    } finally {
      setIsLoading(false);
    }
  };

  // External identity OAuth handler
  const handleExternalIdentityLogin = async () => {
    if (!activeExternalIdentityProvider || !clientId.trim() || !instanceUrl) return;

    setIsLoading(true);
    try {
      await actions.initializeOAuth({
        providerId: activeExternalIdentityProvider.id,
        clientId: clientId.trim(),
        authorizationBaseUrl: instanceUrl,
        environmentId: environment,
        clientSecret: clientSecret.trim() || undefined,
      });
    } catch {
      setIsLoading(false);
    }
  };

  // Token login handler
  const handleTokenLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!onLoginWithToken || !token.trim()) return;

    setIsLoading(true);
    try {
      if (!activeExternalIdentityProvider) {
        localStorage.setItem(STORAGE_KEYS.CONNECTION_MODE, BACKEND_CONNECTION_MODE);
        setConnectionMode(BACKEND_CONNECTION_MODE);
      }
      await onLoginWithToken(token.trim(), tokenInstanceUrl);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-blue-900 to-indigo-900 relative overflow-hidden">
      {/* Animated Background Orbs */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute -top-40 -right-40 w-80 h-80 bg-blue-500/30 rounded-full blur-3xl animate-pulse" />
        <div className="absolute -bottom-40 -left-40 w-96 h-96 bg-indigo-500/20 rounded-full blur-3xl animate-pulse" style={{ animationDelay: '1s' }} />
        <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[600px] h-[600px] bg-cyan-500/10 rounded-full blur-3xl" />
      </div>

      {/* Login Card */}
      <div className="relative w-full max-w-md mx-4">
        {/* Glass Card */}
        <div className="backdrop-blur-xl bg-white/10 border border-white/20 rounded-3xl shadow-2xl p-8 space-y-6">

          {/* Logo & Brand */}
          <div className="flex flex-col items-center space-y-2">
            <div className="w-16 h-16 bg-gradient-to-br from-cyan-400 to-blue-600 rounded-2xl flex items-center justify-center shadow-lg shadow-blue-500/30 transform hover:scale-105 transition-transform">
              <svg className="w-9 h-9 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
              </svg>
            </div>
            <h1 className="text-3xl font-bold text-white tracking-tight">NexusCRM</h1>
            <p className="text-sm text-blue-200/70">Sign in to your workspace</p>
          </div>

          {isProviderConfigLoading ? (
            <div className="py-8 flex flex-col items-center gap-3 text-blue-100/80">
              <svg className="animate-spin h-6 w-6" viewBox="0 0 24 24">
                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
              </svg>
              <p className="text-sm">Loading sign-in options...</p>
            </div>
          ) : isProviderConfigError ? (
            <div className="p-4 bg-red-500/20 border border-red-500/30 rounded-xl text-red-100 text-sm space-y-3">
              <p>Unable to load sign-in options.</p>
              <button
                type="button"
                onClick={() => window.location.reload()}
                className="w-full py-2.5 bg-white/10 border border-white/20 text-white font-medium rounded-xl hover:bg-white/20 transition-all"
              >
                Retry
              </button>
            </div>
          ) : !hasActionableProviders && providerConfigurationError ? (
            <div className="p-4 bg-red-500/20 border border-red-500/30 rounded-xl text-red-100 text-sm">
              {providerConfigurationError}
            </div>
          ) : publicLoginProviders.length === 0 ? (
            <div className="p-4 bg-amber-500/20 border border-amber-500/30 rounded-xl text-amber-100 text-sm">
              No sign-in methods are currently configured. Ask your administrator.
            </div>
          ) : (
            <>
              {providerConfigurationError && (
                <div className="p-4 bg-red-500/20 border border-red-500/30 rounded-xl text-red-100 text-sm">
                  {providerConfigurationError}
                </div>
              )}

              {oauthInitializationError && (
                <div role="alert" className="p-4 bg-red-500/20 border border-red-500/30 rounded-xl text-red-100 text-sm">
                  {oauthInitializationError}
                </div>
              )}

              {/* Google SSO Button — Primary CTA when the runtime config exposes it */}
              {googleEnabled && (
                <>
                  <button
                    type="button"
                    onClick={handleGoogleLogin}
                    disabled={isLoading}
                    className="w-full py-4 bg-white text-gray-700 font-semibold rounded-xl hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-all transform hover:scale-[1.02] active:scale-[0.98] shadow-lg shadow-black/10 flex items-center justify-center gap-3 border border-gray-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-cyan-400/70 focus-visible:ring-offset-2 focus-visible:ring-offset-transparent"
                  >
                    {isLoading ? (
                      <>
                        <svg className="animate-spin h-5 w-5 text-gray-500" viewBox="0 0 24 24">
                          <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                          <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                        </svg>
                        Redirecting...
                      </>
                    ) : (
                      <>
                        <svg className="w-5 h-5" viewBox="0 0 24 24">
                          <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4" />
                          <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853" />
                          <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05" />
                          <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335" />
                        </svg>
                        Sign in with Google
                      </>
                    )}
                  </button>

                  {!hasAdvancedProviders && (
                    <p className="text-center text-xs text-blue-200/50">
                      Use your organization Google account to continue
                    </p>
                  )}

                  {advancedPanelVisible && hasAdvancedProviders && (
                    <div className="relative flex items-center">
                      <div className="flex-grow border-t border-white/10" />
                      <span className="flex-shrink mx-3 text-xs text-blue-300/50 uppercase tracking-wider">or</span>
                      <div className="flex-grow border-t border-white/10" />
                    </div>
                  )}
                </>
              )}

              {advancedPanelVisible && hasAdvancedProviders && (
                <>
                  {hasMultipleConnectionModes && (
                    <div className="flex bg-white/5 rounded-xl p-1 border border-white/10">
                      {backendEnabled && (
                        <button
                          type="button"
                          onClick={() => setConnectionMode(BACKEND_CONNECTION_MODE)}
                          className={`flex-1 py-2.5 px-4 rounded-lg text-sm font-medium transition-all flex items-center justify-center gap-2 ${activeConnectionMode === BACKEND_CONNECTION_MODE
                            ? 'bg-gradient-to-r from-cyan-500 to-blue-600 text-white shadow-lg'
                            : 'text-blue-200/70 hover:text-white hover:bg-white/5'
                            }`}
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2" />
                          </svg>
                          Backend
                        </button>
                      )}
                      {externalIdentityProviders.map(({ identityProvider }) => (
                        <button
                          key={identityProvider.id}
                          type="button"
                          onClick={() => setConnectionMode(identityProvider.id)}
                          className={`flex-1 py-2.5 px-4 rounded-lg text-sm font-medium transition-all flex items-center justify-center gap-2 ${activeConnectionMode === identityProvider.id
                            ? 'bg-gradient-to-r from-cyan-500 to-blue-600 text-white shadow-lg'
                            : 'text-blue-200/70 hover:text-white hover:bg-white/5'
                            }`}
                        >
                          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 11c0-1.1.9-2 2-2h4a2 2 0 012 2v7a2 2 0 01-2 2h-4a2 2 0 01-2-2v-1M7 7a4 4 0 118 0v4H7V7z" />
                          </svg>
                          {identityProvider.label}
                        </button>
                      ))}
                    </div>
                  )}

                  {activeConnectionMode && (
                    <p className="text-center text-blue-200/50 text-xs">
                      {activeConnectionMode === BACKEND_CONNECTION_MODE
                        ? `Requires NexusCRM backend server on ${backendDisplayUrl}`
                        : activeExternalIdentityProvider?.description ?? `Connect through ${activeExternalIdentityProvider?.label ?? 'external identity'}`}
                    </p>
                  )}

                  {loginError && (
                    <div className="p-4 bg-red-500/20 border border-red-500/30 rounded-xl text-red-200 text-sm backdrop-blur-sm">
                      {loginError}
                    </div>
                  )}

                  {activeConnectionMode === BACKEND_CONNECTION_MODE && (
                    <>
                      <p className="text-sm text-blue-200/60 text-center">
                        Sign in with email and password
                      </p>
                      <form onSubmit={handleBackendLogin} className="space-y-4">
                        <div className="space-y-2">
                          <label htmlFor={backendEmailInputId} className="block text-sm font-medium text-blue-100">Email</label>
                          <input
                            id={backendEmailInputId}
                            name="email"
                            type="email"
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                            data-testid="email-input"
                            className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/30 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500/50 transition-all"
                            placeholder="your@email.com"
                            required
                            autoComplete="email"
                          />
                        </div>

                        <div className="space-y-2">
                          <label htmlFor={backendPasswordInputId} className="block text-sm font-medium text-blue-100">Password</label>
                          <input
                            id={backendPasswordInputId}
                            name="password"
                            type="password"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                            data-testid="password-input"
                            className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/30 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500/50 transition-all"
                            placeholder="••••••••"
                            required
                            autoComplete="current-password"
                          />
                        </div>

                        <button
                          type="submit"
                          disabled={isLoading || !email.trim() || !password}
                          data-testid="login-button"
                          className="w-full py-4 bg-gradient-to-r from-cyan-500 to-blue-600 text-white font-semibold rounded-xl hover:from-cyan-400 hover:to-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all transform hover:scale-[1.02] active:scale-[0.98] shadow-lg shadow-blue-500/30 flex items-center justify-center gap-3"
                        >
                          {isLoading ? (
                            <>
                              <svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
                                <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                                <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                              </svg>
                              Signing in...
                            </>
                          ) : (
                            'Sign In'
                          )}
                        </button>
                      </form>

                      {!showForgotPassword ? (
                        <button
                          type="button"
                          onClick={() => setShowForgotPassword(true)}
                          className="w-full text-center text-sm text-blue-300/60 hover:text-blue-200 transition-colors mt-3"
                        >
                          Forgot Password?
                        </button>
                      ) : (
                        <div className="mt-4 pt-4 border-t border-white/10 space-y-3">
                          {forgotSent ? (
                            <div className="p-3 bg-green-500/20 border border-green-500/30 rounded-xl text-green-200 text-sm">
                              If an admin account exists with that email, a reset link has been sent. Check your inbox.
                            </div>
                          ) : (
                            <>
                              <p className="text-sm text-blue-200/60 text-center">
                                Enter your admin email to receive a reset link
                              </p>
                              <form onSubmit={handleForgotPassword} className="space-y-3">
                                <input
                                  type="email"
                                  value={forgotEmail}
                                  onChange={(e) => setForgotEmail(e.target.value)}
                                  className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/30 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500/50 transition-all"
                                  placeholder="admin@example.com"
                                  required
                                  autoFocus
                                />
                                <button
                                  type="submit"
                                  disabled={isLoading || !forgotEmail.trim()}
                                  className="w-full py-3 bg-white/10 border border-white/20 text-white font-medium rounded-xl hover:bg-white/20 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                                >
                                  {isLoading ? 'Sending...' : 'Send Reset Link'}
                                </button>
                              </form>
                            </>
                          )}
                          <button
                            type="button"
                            onClick={() => { setShowForgotPassword(false); setForgotSent(false); setForgotEmail(''); }}
                            className="w-full text-center text-sm text-blue-300/40 hover:text-blue-200 transition-colors"
                          >
                            Back to Sign In
                          </button>
                        </div>
                      )}
                    </>
                  )}

                  {activeExternalIdentityProvider && (
                    <div className="space-y-4">
                      <div className="flex justify-center">
                        <div className={`inline-flex items-center px-3 py-1 rounded-full text-xs font-medium border ${externalBadge.container}`}>
                          <span className={`w-1.5 h-1.5 mr-2 rounded-full ${externalBadge.dot}`} />
                          {displayEnvironmentLabel(selectedExternalEnvironment?.label ?? environment).toUpperCase()}
                        </div>
                      </div>

                      <div className="space-y-2">
                        <label htmlFor={externalClientIdInputId} className="block text-sm font-medium text-blue-100">
                          {activeExternalIdentityProvider.label} Client ID
                        </label>
                        <input
                          id={externalClientIdInputId}
                          type="text"
                          value={clientId}
                          onChange={(e) => setClientId(e.target.value)}
                          className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/30 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500/50 transition-all font-mono text-sm"
                          placeholder="client-id"
                          required
                        />
                      </div>

                      <div className="space-y-2">
                        <label htmlFor={externalClientSecretInputId} className="block text-sm font-medium text-blue-100">
                          Client Secret
                          <span className="ml-2 text-blue-300/40 font-normal">(optional)</span>
                        </label>
                        <input
                          id={externalClientSecretInputId}
                          type="password"
                          value={clientSecret}
                          onChange={(e) => setClientSecret(e.target.value)}
                          className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/30 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500/50 transition-all font-mono text-sm"
                          placeholder="Leave empty for Public Client apps"
                          autoComplete="off"
                        />
                        <p className="text-xs text-blue-300/50">
                          Required for confidential OAuth clients
                        </p>
                      </div>

                      <div className="space-y-2">
                        <label className="block text-sm font-medium text-blue-100">
                          {activeExternalIdentityProvider.label} Environment
                        </label>
                        <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
                          {activeExternalIdentityProvider.environments.map((env) => (
                            <button
                              key={env.id}
                              type="button"
                              onClick={() => setEnvironment(env.id)}
                              className={`px-3 py-2.5 rounded-lg text-sm font-medium transition-all ${environment === env.id
                                ? 'bg-gradient-to-r from-cyan-500 to-blue-600 text-white shadow-lg shadow-cyan-500/25'
                                : 'bg-white/5 text-blue-200/70 hover:bg-white/10 border border-white/10'
                                }`}
                            >
                              {env.label}
                            </button>
                          ))}
                          {activeExternalIdentityProvider.customDomain && (
                            <button
                              type="button"
                              onClick={() => setEnvironment(CUSTOM_ENVIRONMENT_ID)}
                              className={`px-3 py-2.5 rounded-lg text-sm font-medium transition-all ${environment === CUSTOM_ENVIRONMENT_ID
                                ? 'bg-gradient-to-r from-cyan-500 to-blue-600 text-white shadow-lg shadow-cyan-500/25'
                                : 'bg-white/5 text-blue-200/70 hover:bg-white/10 border border-white/10'
                                }`}
                            >
                              {activeExternalIdentityProvider.customDomain.label}
                            </button>
                          )}
                        </div>
                        {isCustomExternalEnvironment && (
                          <div className="mt-2 flex items-center gap-2 px-3 py-3 bg-white/5 border border-white/10 rounded-xl focus-within:ring-2 focus-within:ring-cyan-500/50 focus-within:border-cyan-500/50 transition-all">
                            {externalCustomDomain.inputPrefix && (
                              <span className="text-blue-300/50 text-xs shrink-0">{externalCustomDomain.inputPrefix}</span>
                            )}
                            <input
                              type="text"
                              value={customDomain}
                              onChange={(e) => setCustomDomain(e.target.value)}
                              className="min-w-0 flex-1 bg-transparent text-white placeholder-white/30 focus:outline-none font-mono text-sm"
                              placeholder={externalCustomDomain.placeholder}
                              required
                            />
                            {externalCustomDomain.inputSuffix && (
                              <span className="text-blue-300/50 text-xs shrink-0">{externalCustomDomain.inputSuffix}</span>
                            )}
                          </div>
                        )}
                      </div>

                      <button
                        type="button"
                        onClick={handleExternalIdentityLogin}
                        disabled={isLoading || !clientId.trim() || (isCustomExternalEnvironment && !customDomain.trim())}
                        className="w-full py-4 bg-gradient-to-r from-cyan-500 to-blue-600 text-white font-semibold rounded-xl hover:from-cyan-400 hover:to-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-all transform hover:scale-[1.02] active:scale-[0.98] shadow-lg shadow-blue-500/30 flex items-center justify-center gap-3"
                      >
                        {isLoading ? (
                          <>
                            <svg className="animate-spin h-5 w-5" viewBox="0 0 24 24">
                              <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                              <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                            </svg>
                            Connecting...
                          </>
                        ) : (
                          <>
                            <svg className="w-5 h-5" viewBox="0 0 24 24" fill="currentColor">
                              <path d="M16.1 11.4c1.1 0 2.1-.4 2.9-1.2.8-.8 1.2-1.7 1.2-2.9 0-1.1-.4-2.1-1.2-2.9-.8-.8-1.7-1.2-2.9-1.2-1.1 0-2.1.4-2.9 1.2-.8.8-1.2 1.7-1.2 2.9 0 1.2.4 2.1 1.2 2.9.8.8 1.7 1.2 2.9 1.2z" />
                            </svg>
                            Log in with {activeExternalIdentityProvider.buttonLabel ?? activeExternalIdentityProvider.label}
                          </>
                        )}
                      </button>
                    </div>
                  )}

                  {tokenEnabled && (
                    <div className="border-t border-white/10 pt-6 space-y-4">
                      <p className="text-sm text-blue-200/60 text-center">
                        Connect with an existing Session ID or Access Token
                      </p>

                      <form onSubmit={handleTokenLogin} className="space-y-4">
                        <div className="space-y-2">
                          <label htmlFor={tokenInputId} className="block text-sm font-medium text-blue-100">
                            Session ID / Access Token
                          </label>
                          <textarea
                            id={tokenInputId}
                            value={token}
                            onChange={(e) => setToken(e.target.value)}
                            className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/30 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500/50 transition-all font-mono text-xs resize-none"
                            placeholder="access-token"
                            rows={3}
                            required
                          />
                        </div>

                        <div className="space-y-2">
                          <label htmlFor={tokenInstanceUrlInputId} className="block text-sm font-medium text-blue-100">
                            Instance URL
                          </label>
                          <input
                            id={tokenInstanceUrlInputId}
                            type="url"
                            value={tokenInstanceUrl}
                            onChange={(e) => setTokenInstanceUrl(e.target.value)}
                            className="w-full px-4 py-3 bg-white/5 border border-white/10 rounded-xl text-white placeholder-white/30 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500/50 transition-all"
                            placeholder={activeExternalIdentityProvider?.tokenInstanceUrlPlaceholder ?? 'https://instance.example.com'}
                            required
                          />
                        </div>

                        <button
                          type="submit"
                          disabled={isLoading || !token.trim()}
                          className="w-full py-3 bg-white/10 border border-white/20 text-white font-medium rounded-xl hover:bg-white/20 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                        >
                          Connect with Token
                        </button>
                      </form>
                    </div>
                  )}
                </>
              )}

              {googleEnabled && hasAdvancedProviders && (
                <div className="pt-2 mt-2 border-t border-white/10">
                  <button
                    type="button"
                    onClick={() => setShowAdvanced(!showAdvanced)}
                    aria-expanded={showAdvanced}
                    className="w-full flex items-center justify-center gap-2 py-1.5 rounded-lg text-blue-300/60 hover:text-blue-200 text-sm transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-cyan-400/50"
                  >
                    <span>{showAdvanced ? 'Hide additional options' : advancedToggleLabel}</span>
                    <svg
                      className={`w-4 h-4 transition-transform ${showAdvanced ? 'rotate-180' : ''}`}
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </button>
                </div>
              )}
            </>
          )}
        </div>

        {/* Footer */}
        <p className="mt-6 text-center text-blue-300/40 text-xs">
          {footerText}
        </p>
      </div>
    </div>
  );
}
