"use client";

import {
  createContext,
  useContext,
  useEffect,
  useMemo,
  useState,
  type ReactNode,
} from "react";
import {
  defaultContactSettings,
  fetchPublicContact,
  type ContactSettings,
} from "@/lib/contact-api";

type ContactContextValue = {
  contact: ContactSettings;
  loading: boolean;
};

const ContactContext = createContext<ContactContextValue>({
  contact: defaultContactSettings,
  loading: true,
});

export function ContactProvider({ children }: { children: ReactNode }) {
  const [contact, setContact] = useState<ContactSettings>(defaultContactSettings);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const res = await fetchPublicContact();
        if (!active) return;
        setContact(res.contact);
      } catch {
        if (!active) return;
        setContact(defaultContactSettings);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => {
      active = false;
    };
  }, []);

  const value = useMemo(() => ({ contact, loading }), [contact, loading]);

  return <ContactContext.Provider value={value}>{children}</ContactContext.Provider>;
}

export function useContactSettings() {
  return useContext(ContactContext);
}
