import React, { createContext, useContext } from 'react'

// Default texture source: zardoy/mc-assets gh-pages
export const MC_ASSETS_BASE =
  'https://raw.githubusercontent.com/zardoy/mc-assets/refs/heads/gh-pages'
export const MC_ITEMS_BASE =
  `${MC_ASSETS_BASE}/1.21.11/textures`
export const MC_GUI_BASE = MC_ASSETS_BASE

export interface TextureConfig {
  baseUrl: string
  /**
   * Resolve item texture URL.
   * When `item.textureKey` is set it is used as the path relative to the items texture root
   * (e.g. `"item/dye_black"` → `<base>/item/dye_black.png`).
   * Otherwise falls back to `name` then `type`.
   */
  getItemTextureUrl(item: { type: number; name?: string; textureKey?: string }): string
  getBlockTextureUrl(item: { type: number; name?: string }): string
  /** Supports full mc-assets paths (e.g. "1.21.11/textures/gui/container/anvil.png") */
  getGuiTextureUrl(path: string, version?: string): string
}

function buildDefault(base: string): TextureConfig {
  const isRemote = base.startsWith('http')
  // For remote default: use standardized versioned paths from mc-assets.
  const guiBase = isRemote ? MC_GUI_BASE : base

  return {
    baseUrl: base,

    getItemTextureUrl({ type, name, textureKey }) {
      const root = isRemote ? MC_ITEMS_BASE : base
      if (textureKey) return `${root}/${textureKey}.png`
      if (name) return `${root}/item/${name}.png`
      return `${root}/item/${type}.png`
    },

    getBlockTextureUrl({ type, name }) {
      const root = isRemote ? MC_ITEMS_BASE : base
      if (name) return `${root}/block/${name}.png`
      return `${root}/block/${type}.png`
    },

    getGuiTextureUrl(path: string, version = '1.16.4') {
      if (isRemote) {
        // New format: "1.21.11/textures/gui/container/anvil.png"
        if (path.endsWith('.png') && path.includes('/textures/')) {
          return `${guiBase}/${path}`
        }
        // Backward compatibility with legacy "gui/container/anvil" + version fields.
        return `${guiBase}/${version}/textures/${path}.png`
      }
      return `${base}/textures/${path}.png`
    },
  }
}

const defaultTextureConfig = buildDefault(MC_ITEMS_BASE)

const TextureContext = createContext<TextureConfig>(defaultTextureConfig)

export function useTextures(): TextureConfig {
  return useContext(TextureContext)
}

interface TextureProviderProps {
  config?: Partial<TextureConfig>
  baseUrl?: string
  children: React.ReactNode
}

export function TextureProvider({ config, baseUrl, children }: TextureProviderProps) {
  const base = baseUrl ?? config?.baseUrl ?? MC_ITEMS_BASE
  const merged: TextureConfig = {
    ...buildDefault(base),
    ...config,
  }

  return <TextureContext.Provider value={merged}>{children}</TextureContext.Provider>
}

export { defaultTextureConfig }
