// src/cms/factory.ts
import { useEffect, useState } from "react";
import { gql } from "./hooks"; // твой fetch-GraphQL из cms/hooks.ts

type State<T> = { data: T | null; loading: boolean; error: Error | null };

/** Хук для single-type списков (HeroSection и т.п.) */
export function useSingleton<T = any>(listKey: string, selection: string): State<T> {
  const [st, setSt] = useState<State<T>>({ data: null, loading: true, error: null });

  useEffect(() => {
    let mounted = true;
    const q = `
      query Singleton_${listKey} {
        ${camel(listKey)}s {
          ${selection}
        }
      }`;
    gql<{ [k: string]: any[] }>(q)
      .then(json => {
        if (!mounted) return;
        const key = `${camel(listKey)}s`;
        setSt({ data: (json[key]?.[0] ?? null) as T, loading: false, error: null });
      })
      .catch(err => mounted && setSt({ data: null, loading: false, error: err }));
    return () => { mounted = false; };
  }, [listKey, selection]);

  return st;
}

/** Хук для обычных коллекций (массив элементов) */
export function useCollection<T = any>(listKey: string, selection: string): State<T[]> {
  const [st, setSt] = useState<State<T[]>>({ data: null, loading: true, error: null });

  useEffect(() => {
    let mounted = true;
    const q = `
      query Collection_${listKey} {
        ${camel(listKey)}s {
          ${selection}
        }
      }`;
    gql<{ [k: string]: any[] }>(q)
      .then(json => {
        if (!mounted) return;
        const key = `${camel(listKey)}s`;
        setSt({ data: (json[key] ?? []) as T[], loading: false, error: null });
      })
      .catch(err => mounted && setSt({ data: [], loading: false, error: err }));
    return () => { mounted = false; };
  }, [listKey, selection]);

  return st;
}

function camel(s: string) {
  return s.charAt(0).toLowerCase() + s.slice(1);
}
