/**
 * Official Shopify App Bridge v4 helpers.
 * Fully compliant with Built for Shopify requirements.
 */

export function showToast(message: string, isError: boolean = false): void {
  if (typeof window !== 'undefined') {
    const shopifyObj = (window as any).shopify;
    if (shopifyObj?.toast?.show) {
      shopifyObj.toast.show(message, { isError });
      return;
    }
  }
}

export function showModal(modalId: string): void {
  if (typeof window !== 'undefined') {
    const shopifyObj = (window as any).shopify;
    if (shopifyObj?.modal?.show) {
      shopifyObj.modal.show(modalId);
      return;
    }
    const modalEl = document.getElementById(modalId);
    if (modalEl && typeof (modalEl as any).show === 'function') {
      (modalEl as any).show();
    }
  }
}

export function hideModal(modalId: string): void {
  if (typeof window !== 'undefined') {
    const shopifyObj = (window as any).shopify;
    if (shopifyObj?.modal?.hide) {
      shopifyObj.modal.hide(modalId);
      return;
    }
    const modalEl = document.getElementById(modalId);
    if (modalEl && typeof (modalEl as any).hide === 'function') {
      (modalEl as any).hide();
    }
  }
}

export function showSaveBar(id?: string): void {
  if (typeof window !== 'undefined') {
    const shopifyObj = (window as any).shopify;
    if (shopifyObj?.saveBar?.show) {
      shopifyObj.saveBar.show(id);
    }
  }
}

export function hideSaveBar(id?: string): void {
  if (typeof window !== 'undefined') {
    const shopifyObj = (window as any).shopify;
    if (shopifyObj?.saveBar?.hide) {
      shopifyObj.saveBar.hide(id);
    }
  }
}

export async function getSessionToken(): Promise<string | null> {
  if (typeof window !== 'undefined') {
    const shopifyObj = (window as any).shopify;
    if (shopifyObj?.idToken) {
      try {
        const token = await shopifyObj.idToken();
        return token || null;
      } catch (err) {
        console.warn('[AppBridge] Failed to retrieve session token', err);
      }
    }
  }
  return null;
}
