import React from 'react'
import { useTextures } from '../../context/TextureContext'
import { useScale } from '../../context/ScaleContext'
import { MessageFormattedString } from '../Text/MessageFormattedString'
import type { InventoryTypeDefinition } from '../../registry'

/**
 * For generic_9xN (N < 6): CSS-stitch the 6-row generic_54 texture using two
 * overlapping img elements with objectPosition to clip top and bottom portions.
 * No canvas or async loading needed — works with any URL including remote ones.
 *
 * The source texture (generic_54.png, 176×222) fixed layout:
 *   y=0   ..16  — title bar (17px)
 *   y=17  ..124 — 6 container rows (6×18 = 108px)
 *   y=125 ..221 — player inventory section (97px)
 *
 * Output height = topH + playerH = N*18+17 + 97 = N*18+114.
 * Registry backgroundHeight must equal N*18+114 for the div to match.
 */
const SRC_PLAYER_Y = 17 + 6 * 18 // 125 — fixed position where player section starts
const PLAYER_H = 222 - SRC_PLAYER_Y // 97px — height of player section in generic_54.png

interface InventoryBackgroundProps {
  definition: InventoryTypeDefinition
  children: React.ReactNode
  title?: string
  showDebug?: boolean
}

export function InventoryBackground({
  definition,
  children,
  title,
  showDebug
}: InventoryBackgroundProps) {
  const textures = useTextures()
  const { scale } = useScale()

  const bgUrl = textures.getGuiTextureUrl(definition.backgroundTexture)
  const isStitched = definition.containerRows != null && definition.containerRows <= 6

  const w = definition.backgroundWidth * scale
  const h = definition.backgroundHeight * scale

  const srcW = definition.backgroundWidth
  const srcH = definition.backgroundHeight

  const sharedImgStyle: React.CSSProperties = {
    display: 'block',
    width: srcW,
    imageRendering: 'pixelated',
    pointerEvents: 'none',
    userSelect: 'none',
    objectFit: 'none',
  }

  return (
    <div
      className="mc-inv-background"
      style={{
        position: 'relative',
        width: w,
        height: h,
        imageRendering: 'pixelated',
        display: 'inline-block',
        outline: showDebug ? '1px solid rgba(255, 0, 0, 0.7)' : 'none',
        outlineOffset: 0,
      }}
    >
      {isStitched ? (
        /* CSS two-part stitch: clips top (title+N rows) and bottom (player section)
           from the same source image using objectPosition — no canvas/async needed. */
        <div
          className="mc-inv-background-wrapper"
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            transform: `scale(${scale})`,
            transformOrigin: 'top left',
          }}
        >
          {/* Top: title bar + N container rows */}
          <div style={{ width: srcW, height: definition.containerRows! * 18 + 17, overflow: 'hidden' }}>
            <img className="mc-inv-background-image" src={bgUrl} alt="" aria-hidden draggable={false}
              style={{ ...sharedImgStyle, objectPosition: '0 0' }} />
          </div>
          {/* Bottom: player inventory section starting at SRC_PLAYER_Y in source */}
          <div style={{ width: srcW, height: PLAYER_H, overflow: 'hidden' }}>
            <img src={bgUrl} alt="" aria-hidden draggable={false}
              style={{ ...sharedImgStyle, objectPosition: `0 -${SRC_PLAYER_Y}px` }} />
          </div>
        </div>
      ) : (
        /* Standard: clip source to srcW×srcH via overflow:hidden, then scale */
        <div
          className="mc-inv-background-wrapper"
          style={{
            position: 'absolute',
            top: 0,
            left: 0,
            width: srcW,
            height: srcH,
            overflow: 'hidden',
            transform: `scale(${scale})`,
            transformOrigin: 'top left',
          }}
        >
          <img
            className="mc-inv-background-image"
            src={bgUrl}
            alt=""
            aria-hidden
            draggable={false}
            style={{ ...sharedImgStyle, objectPosition: '0 0' }}
          />
        </div>
      )}

      {/* Title */}
      {title !== undefined && (
        <div
          className="mc-inv-background-title"
          style={{
            position: 'absolute',
            top: (6 + (definition.titleOffset?.y ?? 0)) * scale,
            left: (8 + (definition.titleOffset?.x ?? 0)) * scale,
            fontSize: 7 * scale,
            fontFamily: "'Minecraftia', 'Minecraft', monospace",
            pointerEvents: 'none',
            lineHeight: 1,
          }}
        >
          <MessageFormattedString text={title} fallbackColor="#404040" />
        </div>
      )}

      {/* Slot layer */}
      <div
        className="mc-inv-background-slots"
        style={{
          position: 'absolute',
          top: 0,
          left: 0,
          width: w,
          height: h,
        }}
      >
        {children}
      </div>
    </div>
  )
}
