/**
 * Parse global values from GraphQL query data for use with GlobalContext
 */
export const parseGlobalsData = (data: any) => {
  const {
    settings,
    themeSettings: { globalSettings },
    socialLinks: { themeSettingsSocial: socialLinks },
    headerMenu,
    footerMenu,
    newsletterForm,
    preview,
    ...rest
  } = data

  return {
    globals: {
      settings,
      globalSettings,
      socialLinks,
      headerMenu: filterMenuItems(headerMenu),
      footerMenu: filterMenuItems(footerMenu),
      newsletterForm,
      preview,
    },
    ...rest,
  }
}

/**
 * Parse GraphQL menu data to remove child items
 */
const filterMenuItems = (menu: Record<string, any>) => {
  return menu.menuItems.nodes.filter((node: any) => node.parentId === null)
}

/**
 * Get the nodes from a GraphQL response
 */
export const nodesFromEdges = (edges: Record<'node', any>[]) => {
  return edges.map(({ node }) => node)
}

/**
 * Get the first term for a post
 */
export const getFirstTerm = (terms: any): { slug: string; name: string } | null => {
  return terms?.edges[0].node
}

/**
 * Transform URLs from our backend to a frontend URL
 */
export const transformHeadlessURLs = (content: string) => {
  return content
    .replaceAll(process.env.NEXT_PUBLIC_WORDPRESS_URL || '', process.env.NEXT_PUBLIC_SITE_URL || '')
    .replaceAll(`${process.env.NEXT_PUBLIC_SITE_URL}/wp-content/uploads` || '', '/uploads')
}

/**
 * Check if a URL is external or not
 */
export const isExternalURL = (url: string) => {
  const transformedUrl = transformHeadlessURLs(url)
  if (transformedUrl.startsWith('/')) return false
  return new URL(transformedUrl).host !== new URL(process.env.NEXT_PUBLIC_SITE_URL || '').host
}

/**
 * Scroll to a section on the page for FAQ and Glossary (requires data-scroll-to attribute on element scrolling to)
 */
export const handleScrollTo: React.MouseEventHandler<HTMLButtonElement> = elemntToScrollTo => {
  const sectionId = elemntToScrollTo.currentTarget.getAttribute('data-scroll-to')
  const section = document.getElementById(sectionId as string)
  section?.scrollIntoView({ behavior: 'smooth' })
}

/**
 * noop function
 */
export const noop = () => {}

/**
 * Check if is browser (or server)
 */
export const isBrowser = typeof window !== 'undefined'

/**
 * Calculate swipe power for Framer Motion drag events
 */
export const getSwipePower = (offset: number, velocity: number) => {
  return Math.abs(offset) * velocity
}

/**
 * Detect if user is using a touch device
 */
export const isTouchDevice = () => {
  return isBrowser && ('ontouchstart' in window || navigator.maxTouchPoints > 0)
}
