'use client';

import { useEffect, useState } from 'react';
import { AUTH_REFRESH_KEY, AUTH_SESSION_KEY, AUTH_TOKEN_KEY } from '@/lib/api';
import { resolveMiniAppTargetOrigin } from '@/lib/mini-app-url';

export const EMBEDDED_AUTH_MESSAGE = 'lendry-id-embedded-auth';
export const EMBEDDED_AUTH_REQUEST = 'lendry-id-embedded-auth-request';

export interface EmbeddedAuthPayload {
  type: typeof EMBEDDED_AUTH_MESSAGE;
  token: string;
  refreshToken?: string;
  sessionId?: string;
}

function collectTrustedOrigins() {
  const origins = new Set<string>();
  if (typeof window === 'undefined') return origins;

  origins.add(window.location.origin);
  if (document.referrer) {
    try {
      origins.add(new URL(document.referrer).origin);
    } catch {
      // ignore malformed referrer
    }
  }
  return origins;
}

function resolveParentPostMessageTarget() {
  if (typeof window === 'undefined' || window.parent === window) {
    return window.location.origin;
  }

  if (document.referrer) {
    try {
      const referrerOrigin = new URL(document.referrer).origin;
      if (referrerOrigin !== window.location.origin) {
        return '*';
      }
      return referrerOrigin;
    } catch {
      return '*';
    }
  }

  return '*';
}

export function postEmbeddedAuthToIframe(
  iframe: HTMLIFrameElement,
  auth: { token: string; refreshToken?: string | null; sessionId?: string | null }
) {
  const target = iframe.contentWindow;
  if (!target || !auth.token) return;

  const payload: EmbeddedAuthPayload = {
    type: EMBEDDED_AUTH_MESSAGE,
    token: auth.token,
    refreshToken: auth.refreshToken ?? undefined,
    sessionId: auth.sessionId ?? undefined
  };

  const targetOrigin = resolveMiniAppTargetOrigin(iframe.getAttribute('src') || iframe.src, window.location.origin);
  target.postMessage(payload, targetOrigin);
}

export function useEmbeddedAuthFallback() {
  const [embeddedToken, setEmbeddedToken] = useState<string | null>(null);

  useEffect(() => {
    function handleMessage(event: MessageEvent) {
      if (!collectTrustedOrigins().has(event.origin)) return;
      const data = event.data as Partial<EmbeddedAuthPayload> | null;
      if (!data || data.type !== EMBEDDED_AUTH_MESSAGE || !data.token?.trim()) return;

      const token = data.token.trim();
      setEmbeddedToken(token);
      window.localStorage.setItem(AUTH_TOKEN_KEY, token);
      if (data.refreshToken) {
        window.localStorage.setItem(AUTH_REFRESH_KEY, data.refreshToken);
      }
      if (data.sessionId) {
        window.localStorage.setItem(AUTH_SESSION_KEY, data.sessionId);
      }
      window.dispatchEvent(new CustomEvent(EMBEDDED_AUTH_MESSAGE, { detail: data }));
    }

    window.addEventListener('message', handleMessage);
    if (window.parent !== window) {
      window.parent.postMessage({ type: EMBEDDED_AUTH_REQUEST }, resolveParentPostMessageTarget());
    }
    return () => window.removeEventListener('message', handleMessage);
  }, []);

  return embeddedToken;
}
