'use client';

import { useEffect, useMemo, useState } from 'react';
import { fetchPublicSettingsClient } from '@/lib/api';
import { buildOneTapUrls, type OneTapUrls } from '@/lib/one-tap-examples';
import { resolveFrontendBase, resolveOAuthApiBase } from '@/lib/oauth-url';

export function useOneTapUrls() {
  const [urls, setUrls] = useState<OneTapUrls | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

    void fetchPublicSettingsClient()
      .then((settings) => {
        if (cancelled) return;

        const apiBase = resolveOAuthApiBase(settings, '');
        const frontendBase = resolveFrontendBase(settings, '');

        if (!apiBase || !frontendBase) {
          setError('Укажите PUBLIC_API_URL и PUBLIC_FRONTEND_URL в настройках IdP — примеры подставят актуальные URL автоматически.');
          setUrls(null);
          return;
        }

        setUrls(buildOneTapUrls(apiBase, frontendBase, settings.PROJECT_NAME?.trim() || 'MVK ID'));
        setError(null);
      })
      .catch(() => {
        if (cancelled) return;
        setError('Не удалось загрузить публичные настройки IdP.');
        setUrls(null);
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

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

  return useMemo(
    () => ({
      urls,
      loading,
      error,
      apiBase: urls?.apiBase ?? '',
      frontendBase: urls?.frontendBase ?? '',
      projectName: urls?.projectName ?? 'MVK ID'
    }),
    [error, loading, urls]
  );
}
