// App Bridge — the CDN build (https://cdn.shopify.com/shopifycloud/app-bridge.js),
// loaded from the root layout on embedded loads. It self-initialises from the
// `shopify-api-key` meta tag and the `host` URL param, and exposes a global
// `window.shopify` with `idToken()` for session-token auth. This is the form
// Shopify's App Store review requires; no npm SDK / manual createApp needed.

type ShopifyGlobal = { idToken?: () => Promise<string> };

function shopify(): ShopifyGlobal | null {
  if (typeof window === "undefined") return null;
  return (window as unknown as { shopify?: ShopifyGlobal }).shopify ?? null;
}

/** No-op: the CDN App Bridge script boots itself. Kept for call-site compatibility. */
export function initAppBridge(): void {
  /* CDN App Bridge self-initialises from the meta tag + host param. */
}

/** A fresh Shopify session token, or null if not embedded / not ready. */
export async function appSessionToken(): Promise<string | null> {
  const s = shopify();
  if (!s?.idToken) return null;
  try {
    return await s.idToken();
  } catch {
    return null;
  }
}
