'use client';

import { useEffect } from 'react';
import { syncFedcmSession } from '@/lib/api';
import { DEFAULT_PUBLIC_API_URL } from '@/lib/project-domains';

/** Синхронизирует FedCM cookie и Login Status API на origin API-домена (login_url). */
export function FedcmApiLoginStatusBridge({
  active,
  accessToken,
  publicApiUrl = DEFAULT_PUBLIC_API_URL
}: {
  active: boolean;
  accessToken?: string | null;
  publicApiUrl?: string;
}) {
  useEffect(() => {
    if (!active || !accessToken) return;
    void syncFedcmSession(accessToken);
  }, [accessToken, active]);

  useEffect(() => {
    if (!active) return;
    const apiBase = publicApiUrl.replace(/\/+$/, '');
    if (!apiBase) return;

    const iframe = document.createElement('iframe');
    iframe.hidden = true;
    iframe.title = 'FedCM login status';
    iframe.src = `${apiBase}/fedcm/login-status`;
    document.body.appendChild(iframe);

    return () => {
      iframe.remove();
    };
  }, [active, publicApiUrl]);

  return null;
}
