import { useEffect, useState } from "react";
import { getEnv } from "./env";

// ====== универсальный fetch GraphQL ======
export async function gql<T>(query: string, variables?: Record<string, any>): Promise<T> {
  const res = await fetch("/api/graphql", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    credentials: "include",
    body: JSON.stringify({ query, variables }),
  });
  const json = await res.json();
  if (!res.ok || json.errors) {
    const msg = json?.errors?.map((e: any) => e.message).join("\n") || res.statusText;
    throw new Error(msg);
  }
  return json.data as T;
}

// ====== конфиг для префикса медиа ======
const API_ORIGIN =
  getEnv("VITE_API_ORIGIN") ||
  getEnv("REACT_APP_API_ORIGIN") ||
  ""; // пусто = используем относительный путь (через proxy)

function normalizeMediaUrl(u?: string | null): string | undefined {
  if (!u) return undefined;
  if ((u.startsWith("/images") || u.startsWith("/files")) && API_ORIGIN) {
    return `${API_ORIGIN}${u}`;
  }
  return u;
}

// ====== типы и query ======
export type HeroSection = {
  id: string;
  title?: string | null;
  description?: string | null;
  buttonText?: string | null;
  buttonLink?: string | null;
  backgroundImage?: { url?: string | null } | null;
};

const HERO_SECTION = /* GraphQL */ `
  query HeroSection {
    heroSections {
      id
      title
      description
      buttonText
      buttonLink
      backgroundImage { url }
    }
  }
`;

// ====== универсальный хук useGQL ======
export function useGQL<T>(query: string, variables?: Record<string, any>) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    let mounted = true;
    setLoading(true);
    gql<T>(query, variables)
      .then((d) => { if (mounted) { setData(d); setError(null); } })
      .catch((e) => { if (mounted) setError(e as Error); })
      .finally(() => { if (mounted) setLoading(false); });
    return () => { mounted = false; };
  }, [query, JSON.stringify(variables)]);

  return { data, loading, error };
}

// ====== хук для HeroSection (ИМЕННО ИМЕНОВАННЫЙ экспорт) ======
export function useHeroSection() {
  const { data, loading, error } = useGQL<{ heroSections: HeroSection[] }>(HERO_SECTION);
  const hero = (data?.heroSections?.[0] ?? null) as HeroSection | null;
  const bgUrl = normalizeMediaUrl(hero?.backgroundImage?.url);
  return { hero, bgUrl, loading, error };
}
