import { useCallback, useState, type CSSProperties } from 'react';
import type { EquipmentItem } from '../game/types';
import { RARITY_COLORS, RARITY_GLOW } from '../shared/constants';
import { useT, type Translations } from '../i18n';

/** 5×8 = 40 слотов */
const COLS = 5;
const ROWS = 8;
const MAX_SLOTS = COLS * ROWS;

/** Large slot icons (same family as EquipmentPaperDoll) */
const SLOT_ICONS: Record<string, string> = {
  finger: '\uD83D\uDCBF',
  head: '\u26D1\uFE0F',
  neck: '\uD83D\uDCBF',
  main_hand: '\u2694\uFE0F',
  off_hand: '\uD83D\uDEE1\uFE0F',
  chest: '\uD83D\uDEE1\uFE0F',
  cloak: '\uD83C\uDF83',
  hands: '\uD83D\uDC42',
  wrist: '\uD83D\uDC58',
  feet: '\uD83D\uDC62',
  legs: '\uD83D\uDC56',
  quiver: '\uD83C\uDFF9',
};

function slotIcon(slot: string): string {
  return SLOT_ICONS[slot] ?? '\uD83D\uDCE6';
}

function rarityColor(rarity: string): string {
  return RARITY_COLORS[rarity.toLowerCase()] ?? '#9d9d9d';
}

function rarityGlow(rarity: string): string {
  return RARITY_GLOW[rarity.toLowerCase()] ?? 'none';
}

function statLabel(tr: Translations, statType: string): string {
  switch (statType) {
    case 'attack': return tr.atk;
    case 'defense': return tr.def;
    case 'speed': return tr.spd;
    default: return tr.stat;
  }
}

function slotLabel(tr: Translations, slot: string): string {
  const labels: Record<string, string> = {
    main_hand: tr.slotWeapon,
    off_hand: tr.slotOffHand,
    head: tr.slotHead,
    chest: tr.slotChest,
    legs: tr.slotLegs,
    feet: tr.slotFeet,
    cloak: tr.slotCloak,
    neck: tr.slotNeck,
    finger: tr.slotRing,
    wrist: tr.slotWrist,
    hands: tr.slotHands,
    quiver: tr.slotQuiver,
  };
  return labels[slot] ?? slot;
}

const wrap: CSSProperties = {
  marginTop: 12,
  paddingTop: 10,
  borderTop: '1px solid rgba(255,255,255,0.08)',
};

const title: CSSProperties = {
  fontSize: 11,
  fontWeight: 700,
  color: 'rgba(200,210,230,0.75)',
  textTransform: 'uppercase',
  letterSpacing: 0.6,
  marginBottom: 8,
};

// Предыдущий шаг (−20% от 54px-базы), затем ещё −30% от текущих величин.
const grid: CSSProperties = {
  display: 'grid',
  gridTemplateColumns: `repeat(${COLS}, minmax(30px, 1fr))`,
  gap: 4,
  width: '100%',
  overflow: 'visible',
};

const cellBase: CSSProperties = {
  position: 'relative',
  aspectRatio: '1',
  minHeight: 0,
  borderRadius: 4,
  border: '1px solid rgba(60, 70, 90, 0.85)',
  background:
    'linear-gradient(145deg, rgba(15,18,28,0.95) 0%, rgba(25,30,42,0.85) 50%, rgba(12,14,20,0.95) 100%)',
  boxShadow: 'inset 0 1px 0 rgba(255,255,255,0.06), inset 0 -2px 6px rgba(0,0,0,0.45)',
  display: 'flex',
  alignItems: 'center',
  justifyContent: 'center',
  padding: 3,
  overflow: 'visible',
};

const iconDisplay: CSSProperties = {
  fontSize: 15,
  lineHeight: 1,
  userSelect: 'none',
  pointerEvents: 'none',
};

const tooltipBox: CSSProperties = {
  position: 'absolute',
  top: '100%',
  left: '50%',
  transform: 'translateX(-50%)',
  marginTop: 4,
  minWidth: 88,
  maxWidth: 157,
  padding: '6px 7px',
  borderRadius: 4,
  background: 'rgba(12, 14, 22, 0.96)',
  border: '1px solid rgba(255,255,255,0.14)',
  boxShadow: '0 4px 15px rgba(0,0,0,0.55)',
  zIndex: 50,
  pointerEvents: 'none',
  opacity: 0,
  visibility: 'hidden',
  transition: 'opacity 0.12s ease, visibility 0.12s ease',
};

const tooltipVisible: CSSProperties = {
  opacity: 1,
  visibility: 'visible',
};

const tooltipName: CSSProperties = {
  fontSize: 8,
  fontWeight: 700,
  lineHeight: 1.3,
  marginBottom: 4,
  wordBreak: 'break-word',
};

const tooltipLine: CSSProperties = {
  fontSize: 7,
  color: 'rgba(200,210,230,0.88)',
  lineHeight: 1.45,
};

const tooltipMuted: CSSProperties = {
  fontSize: 7,
  color: 'rgba(160,170,190,0.75)',
  marginTop: 4,
};

interface InventoryGridProps {
  items?: EquipmentItem[];
}

export function InventoryGrid({ items = [] }: InventoryGridProps) {
  const tr = useT();
  const [hoverSlot, setHoverSlot] = useState<number | null>(null);

  const showTip = useCallback((i: number) => setHoverSlot(i), []);
  const hideTip = useCallback(() => setHoverSlot(null), []);

  const cells = Array.from({ length: MAX_SLOTS }, (_, i) => i);

  return (
    <div style={wrap}>
      <div style={title}>{tr.inventory}</div>
      <div style={grid}>
        {cells.map((i) => {
          const item = items[i];
          const color = item ? rarityColor(item.rarity) : undefined;
          const glow = item ? rarityGlow(item.rarity) : 'none';
          const show = hoverSlot === i && item;

          const fallbackTitle = item
            ? `${item.name} — ${item.rarity}, ilvl ${item.ilvl}, ${statLabel(tr, item.statType)} ${item.primaryStat}`
            : undefined;

          return (
            <div
              key={i}
              style={{
                ...cellBase,
                borderColor: item ? `${color}66` : cellBase.border as string,
                boxShadow:
                  item && glow !== 'none'
                    ? `${glow}, inset 0 1px 0 rgba(255,255,255,0.06)`
                    : cellBase.boxShadow,
              }}
              title={fallbackTitle}
              onMouseEnter={() => item && showTip(i)}
              onMouseLeave={hideTip}
              onFocus={() => item && showTip(i)}
              onBlur={hideTip}
              tabIndex={item ? 0 : undefined}
            >
              {item && (
                <div
                  style={{
                    ...tooltipBox,
                    ...(show ? tooltipVisible : {}),
                  }}
                  aria-hidden={!show}
                >
                  <div style={{ ...tooltipName, color }}>{item.name}</div>
                  <div style={tooltipLine}>
                    {item.rarity.charAt(0).toUpperCase() + item.rarity.slice(1)} · ilvl {item.ilvl}
                  </div>
                  <div style={tooltipLine}>
                    {statLabel(tr, item.statType)} +{item.primaryStat}
                  </div>
                  <div style={tooltipMuted}>{slotLabel(tr, item.slot)}</div>
                </div>
              )}

              {item ? (
                <span style={iconDisplay} aria-hidden>
                  {slotIcon(item.slot)}
                </span>
              ) : null}
            </div>
          );
        })}
      </div>
    </div>
  );
}
