import React from 'react'
import { useInventoryContext } from '../../context/InventoryContext'
import { useScale } from '../../context/ScaleContext'
import { useTextures } from '../../context/TextureContext'
import { Slot } from '../Slot'
import type { ItemStack } from '../../types'

interface HotbarExtrasProps {
  showOffhand: boolean
  container: boolean
  offhandItem: ItemStack | null
}

/** Renders a sprite from the widgets.png using the same inner-div+transform approach as InventoryBackground */
function WidgetSprite({
  url,
  srcX,
  srcY,
  srcW,
  srcH,
  scale,
  style,
}: {
  url: string
  srcX: number
  srcY: number
  srcW: number
  srcH: number
  scale: number
  style?: React.CSSProperties
}) {
  return (
    <div
      style={{
        position: 'absolute',
        width: srcW * scale,
        height: srcH * scale,
        overflow: 'hidden',
        imageRendering: 'pixelated',
        pointerEvents: 'none',
        ...style,
      }}
    >
      <div
        style={{
          width: srcW,
          height: srcH,
          overflow: 'hidden',
          transform: `scale(${scale})`,
          transformOrigin: 'top left',
        }}
      >
        <img
          src={url}
          alt=""
          aria-hidden
          draggable={false}
          style={{
            position: 'absolute',
            top: -srcY,
            left: -srcX,
            imageRendering: 'pixelated',
            userSelect: 'none',
          }}
        />
      </div>
    </div>
  )
}

/**
 * Hotbar-specific extras rendered inside InventoryBackground alongside the regular slots.
 * Mirrors layouts.mjs Hotbar children:
 *   - Active slot indicator (always)
 *   - Offhand slot left of the strip (when showOffhand)
 *   - Open-inventory button right of the strip (when container)
 */
export function HotbarExtras({ showOffhand, container, offhandItem }: HotbarExtrasProps) {
  const { playerState, sendAction } = useInventoryContext()
  const { scale } = useScale()
  const textures = useTextures()

  const activeSlot = playerState?.activeHotbarSlot ?? 0
  const hotbarUrl = textures.getGuiTextureUrl('1.15/textures/gui/widgets.png')

  // Sprite regions within widgets.png (native pixels):
  //   Hotbar strip : [0, 0, 182, 22]
  //   Active box   : [0, 22, 24, 24]
  //   Offhand box  : [24, 22, 24, 24]
  const GAP = 2

  return (
    <>
      {/* ── Active slot indicator ── */}
      <WidgetSprite
        url={hotbarUrl}
        srcX={0}
        srcY={22}
        srcW={24}
        srcH={24}
        scale={scale}
        style={{
          left: (activeSlot * 20 - 1) * scale,
          top: -1 * scale,
          zIndex: 2,
        }}
      />

      {/* ── Offhand slot (left of hotbar) ── */}
      {showOffhand && (
        <div
          className="mc-inv-hotbar-offhand"
          style={{
            position: 'absolute',
            left: -(24 + GAP) * scale,
            top: -1 * scale,
            width: 24 * scale,
            height: 24 * scale,
            pointerEvents: 'auto',
          }}
        >
          <WidgetSprite
            url={hotbarUrl}
            srcX={24}
            srcY={22}
            srcW={24}
            srcH={24}
            scale={scale}
            style={{ left: 0, top: 0 }}
          />
          {/* Item at slot 45 (offhand) */}
          <div style={{ position: 'absolute', top: 4 * scale, left: 3 * scale }}>
            <Slot index={45} item={offhandItem} size={16 * scale} noBackground disableFocusSwap />
          </div>
        </div>
      )}

      {/* ── Open-inventory button (right of hotbar) ── */}
      {container && (
        <div
          className="mc-inv-hotbar-open-inv"
          title="Open inventory"
          style={{
            position: 'absolute',
            left: (182 + GAP) * scale,
            top: -1 * scale,
            width: 24 * scale,
            height: 24 * scale,
            cursor: 'pointer',
            pointerEvents: 'auto',
          }}
          onClick={() => sendAction({ type: 'open-inventory' })}
          onTouchEnd={(e) => {
            e.stopPropagation()
            e.preventDefault()
            sendAction({ type: 'open-inventory' })
          }}
        >
          <WidgetSprite
            url={hotbarUrl}
            srcX={24}
            srcY={22}
            srcW={24}
            srcH={24}
            scale={scale}
            style={{ left: 0, top: 0 }}
          />
          {/* Three white dots centered */}
          {[0, 1, 2].map((i) => (
            <div
              key={i}
              style={{
                position: 'absolute',
                left: (6 + i * 4) * scale,
                top: 11 * scale,
                width: 2 * scale,
                height: 2 * scale,
                background: 'white',
                pointerEvents: 'none',
              }}
            />
          ))}
        </div>
      )}
    </>
  )
}
