import { apiClient } from './api-client'

const WP_URL = import.meta.env.VITE_WP_API_URL || 'https://panel.profbody.uz/wp-json/wp/v2'
const WP_API_URL = 'https://panel.profbody.uz/wp-json'

export interface WpMenuItem {
  ID: number
  title: string
  url: string
  slug?: string
  children?: WpMenuItem[]
  menu_item_parent?: string
  order?: number
}

export interface WpMenu {
  ID: number
  name: string
  slug: string
  items: WpMenuItem[]
}

export const wordpressMenuService = {

  async getMenus(): Promise<any[]> {
    try {
      return apiClient.fetch<any[]>(`${WP_API_URL}/wp-api-menus/v2/menus`)
    } catch (error) {
      console.error('Error fetching menus:', error)
      return []
    }
  },

  async getMenu(menuId: string | number): Promise<any | null> {
    try {
      return apiClient.fetch<any>(
        `${WP_API_URL}/wp-api-menus/v2/menus/${menuId}`
      )
    } catch (error) {
      console.error(`Error fetching menu ${menuId}:`, error)
      return null
    }
  },


  async getMenuItems(menuId: string | number): Promise<WpMenuItem[]> {
    try {
      const menuData = await apiClient.fetch<any>(
        `${WP_API_URL}/wp-api-menus/v2/menus/${menuId}`
      )

      return menuData.items || []
    } catch (error) {
      console.error(`Error fetching menu items for ${menuId}:`, error)
      return []
    }
  },


  convertToRouterLink(wpUrl: string): string {
    if (!wpUrl) return '/'

    try {
      const urlObj = new URL(wpUrl)
      const path = urlObj.pathname

      const baseUrl = 'https://panel.profbody.uz'
      if (path.includes(baseUrl)) {
        return path.replace(baseUrl, '') || '/'
      }

      if (path === '/' || path === '') {
        return '/'
      }

      let cleanPath = path

      const prefixes = ['/wordpress', '/wp', '/blog']
      for (const prefix of prefixes) {
        if (cleanPath.startsWith(prefix)) {
          cleanPath = cleanPath.replace(prefix, '')
          break
        }
      }

      if (!cleanPath || cleanPath === '') {
        return '/'
      }

      return cleanPath
    } catch {
      if (wpUrl.startsWith('/')) {
        return wpUrl
      }
      return wpUrl
    }
  }
}
