const SANITY_PROJECT_ID = "vfu6rlfk";
const SANITY_DATASET = "production";
const SANITY_API_VERSION = "2024-01-01";

const GROQ = encodeURIComponent(`*[_type == "landingPage"][0]`);
const SANITY_URL = `https://${SANITY_PROJECT_ID}.apicdn.sanity.io/v${SANITY_API_VERSION}/data/query/${SANITY_DATASET}?query=${GROQ}`;

const SanityContext = React.createContext(null);

function SanityProvider({ children }) {
  const [data, setData] = React.useState(null);

  React.useEffect(() => {
    fetch(SANITY_URL)
      .then((r) => r.json())
      .then((json) => setData(json.result))
      .catch((e) => console.warn("Sanity fetch failed, using fallback content.", e));
  }, []);

  return React.createElement(SanityContext.Provider, { value: data }, children);
}

function useSanityLP() {
  return React.useContext(SanityContext);
}

function sanityImgUrl(asset, width) {
  const ref = asset?._ref || asset;
  if (!ref || typeof ref !== 'string') return null;
  const m = ref.match(/^image-([a-f0-9]+)-(\d+x\d+)-(\w+)$/i);
  if (!m) return null;
  const url = `https://cdn.sanity.io/images/vfu6rlfk/production/${m[1]}-${m[2]}.${m[3]}`;
  return width ? url + `?w=${width}&auto=format` : url;
}
