'use client';
import React, { useEffect, useRef } from 'react';
import { useLoaderData } from 'react-router';
import { createRoleProtectedLoader } from "@/lib/features/protectedFetcher";
import { FEATURE_SLUGS } from "@/lib/role-helpers";
import { getKcgmSsoToken } from "@/lib/features/kcgm/query";

export const loader = createRoleProtectedLoader(
  FEATURE_SLUGS.kcgm,
  "read",
  async ({ request }) => {
    const response = await getKcgmSsoToken({
      Cookie: request.headers.get("Cookie") ?? "",
    });
    return { ssoToken: response.success ? response.data.token : null };
  },
);

export default function KCGMDashboard() {
  const { ssoToken } = useLoaderData<typeof loader>();
  const iframeRef = useRef<HTMLIFrameElement>(null);

  // The iframe src goes through the admin console's own domain (/kcgm-app)
  // which proxies app.html from the local KCGM Next.js server (port 3010).
  // This avoids "localhost refused to connect" on deployed servers.
  const selfOrigin = typeof window !== 'undefined' ? window.location.origin : '';
  const frontendUrl = import.meta.env.VITE_KCGM_FRONTEND_URL || `${selfOrigin}/kcgm-app`;
  // API calls go through the core server proxy — no separate domain needed.
  const coreUrl = import.meta.env.VITE_CORE_URL || "https://core2.karmagroup.com";
  const apiUrl = import.meta.env.VITE_KCGM_API_URL || `${coreUrl}/v1/admin-console/kcgm-proxy`;
  const iframeSrc = `${frontendUrl}?api=${encodeURIComponent(apiUrl)}`;

  // The KCGM app (running inside the iframe) asks us for a sign-in hand-off
  // token instead of showing its own login form — this replies with the
  // short-lived token core minted for the currently logged-in console user.
  // frontendUrl is same-origin with the console (served via /kcgm-app), so the
  // reply's targetOrigin is locked to our own origin, not "*".
  useEffect(() => {
    if (!ssoToken || !selfOrigin) return;
    function handleMessage(event: MessageEvent) {
      if (event.source !== iframeRef.current?.contentWindow) return;
      if (event.data?.type !== 'kcgm-sso-request') return;
      (event.source as Window).postMessage({ type: 'kcgm-sso', token: ssoToken }, selfOrigin);
    }
    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [ssoToken, selfOrigin]);

  return (
    <div style={{ width: '100%', height: 'calc(100vh - 64px)', display: 'flex', flex: 1, backgroundColor: '#fbf9f3' }}>
      <iframe
        ref={iframeRef}
        src={iframeSrc}
        style={{ width: '100%', height: '100%', border: 'none', flex: 1 }}
        title="KCGM Dashboard"
        allow="clipboard-write"
      />
    </div>
  );
}
