"use client";

import { useEffect, useState } from "react";
import { getStoredLocale, getStoredLocaleRaw } from "@/i18n/localeSwitcher";
import FooterContent from "./FooterContent";

export default function Footer({ showCallToAction = true }: { showCallToAction?: boolean }) {
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchFooter() {
      try {
        const baseUrl = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
        if (!baseUrl) {
          setData(null);
          return;
        }
        const res = await fetch(
          `${baseUrl}/store/pages/footer`,
          {
            method: "GET",
            headers: {
              "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
              "x-medusa-locale": (getStoredLocaleRaw() ?? getStoredLocale()).trim(),
            },
            cache: "no-store"
          }
        );

        if (!res.ok) {
          setData(null);
          return;
        }

        const json = await res.json();
        setData(json ?? null);
      } catch {
        setData(null);
      } finally {
        setLoading(false);
      }
    }

    fetchFooter();
  }, []);

  if (loading) {
    return <div className="min-h-[200px]" />;
  }

  if (!data) {
    return null;
  }

  return <FooterContent showCallToAction={showCallToAction} data={data} />;
}