'use client';
import { useQuery } from '@tanstack/react-query';
import { api } from './api';
import { useAuth } from './auth-context';

const API = process.env.NEXT_PUBLIC_API_URL ?? '';

export interface Brand {
  id: number | null;
  name: string;
  app_name: string;
  has_logo: boolean;
}

export function logoUrl(id: number | null): string | null {
  return id ? `${API}/api/v1/branding/logo/${id}` : null;
}

/** Signed-in organisation brand (logo + white-label app name), super-admin aware. */
export function useOrgBrand() {
  const { user, loading } = useAuth();
  const q = useQuery({
    queryKey: ['org-brand'],
    queryFn: () => api.get('/api/v1/organisation'),
    enabled: !!user && !loading,
    staleTime: 5 * 60 * 1000,
    retry: false,
  });
  const brand: Brand = q.data ?? { id: null, name: 'Qtrial', app_name: 'Qtrial', has_logo: false };
  return { brand, logo: logoUrl(brand.id != null && brand.has_logo ? brand.id : null) };
}

/** Logo image with the default Qtrial logo fallback. */
export function BrandMark({ brand, logo, size = 32 }: { brand: Brand; logo: string | null; size?: number }) {
  if (logo) {
    return <img src={logo} alt={`${brand.app_name} logo`} style={{ height: size }} className="max-w-[140px] object-contain rounded" />;
  }
  return (
    <span className="inline-flex items-center gap-2">
      <img src="/logo.svg" alt="Qtrial logo" style={{ height: size }} className="object-contain rounded" />
      <span className="font-bold tracking-tight" style={{ fontSize: size * 0.55 }}>{brand.app_name || 'Qtrial'}</span>
    </span>
  );
}
