import { useEffect, useState } from "react";
import { getMediaUrl, getSections } from "../lib/strapiClient";
import { DEFAULT_LOCALE, type SupportedLocale } from "../lib/locale";

interface Section {
  id: number;
  title?: string;
  subtitle?: string;
  buttonLabel?: string;
  order?: number;
  type?: string | null;
  action?: string | null;
  video?: any;
  image?: any;
  videoSrc?: string;
  logoSrc?: string;
}

export function useSections(locale: SupportedLocale = DEFAULT_LOCALE) {
  const [data, setData] = useState<Section[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<null | string>(null);

  useEffect(() => {
    let cancelled = false;

    setLoading(true);
    setError(null);

    getSections(locale)
      .then((sections) => {
        if (cancelled) return;

        const formatted = sections.map((item: any) => ({
          ...item,
          videoSrc: getMediaUrl(item.video),
          logoSrc: getMediaUrl(item.image),
        }));

        setData(
          formatted.sort((a: any, b: any) => Number(a.order) - Number(b.order))
        );
      })
      .catch((e) => {
        if (!cancelled) setError(e.message);
      })
      .finally(() => {
        if (!cancelled) setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [locale]);

  return { data, loading, error };
}
