import { useEffect } from 'react';
import { Spinner } from '@cameleer/design-system';
import { useMe } from '../api/hooks';
import { useOrgStore } from './useOrganization';

/**
 * Fetches /api/me and populates the org store with platform admin status
 * and tenant-to-org mapping. Renders children once resolved.
 */
export function OrgResolver({ children }: { children: React.ReactNode }) {
  const { data: me, isLoading, isError } = useMe();
  const { setIsPlatformAdmin, setOrganizations, setCurrentOrg, currentOrgId } = useOrgStore();

  useEffect(() => {
    if (!me) return;

    setIsPlatformAdmin(me.isPlatformAdmin);

    // Map tenants: logtoOrgId is the org ID for token scoping, id is the DB UUID
    const orgEntries = me.tenants.map((t) => ({
      id: t.logtoOrgId,
      name: t.name,
      slug: t.slug,
      tenantId: t.id,
    }));
    setOrganizations(orgEntries);

    // Auto-select if single tenant and no org selected yet
    if (orgEntries.length === 1 && !currentOrgId) {
      setCurrentOrg(orgEntries[0].id);
    }
  }, [me]);

  if (isLoading) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: '100vh' }}>
        <Spinner />
      </div>
    );
  }

  if (isError) {
    return null;
  }

  return <>{children}</>;
}
