/* inventory-screen.jsx — equipment + inventory overlay (exports ItemIcon, Heart, SwingDiagram, InventoryScreen) */
const GG = window.GAME;

function ItemIcon(props) {
  const size = props.size || 24;
  const ref = React.useRef(null);
  React.useEffect(() => {
    const ctx = ref.current.getContext("2d");
    ctx.imageSmoothingEnabled = false;
    ctx.clearRect(0, 0, size, size);
    GG.drawItem(ctx, props.id, 0, 0, size / 8);
  }, [props.id, size]);
  return <canvas ref={ref} width={size} height={size} className="iicon" />;
}

function Heart(props) {
  const size = props.size || 16;
  const ref = React.useRef(null);
  React.useEffect(() => {
    const ctx = ref.current.getContext("2d");
    ctx.imageSmoothingEnabled = false;
    ctx.clearRect(0, 0, size, size);
    GG.drawHeart(ctx, 0, 0, size / 8, props.full ? "#e23a4a" : "#3a2030");
  }, [props.full, size]);
  return <canvas ref={ref} width={size} height={size} className="heart" />;
}

function HeartRow(props) {
  const out = [];
  for (let i = 0; i < props.max; i++) out.push(<Heart key={i} full={i < props.hp} size={props.size || 16} />);
  return <span className="heartrow">{out}</span>;
}

function swingSpeed(cd) {
  if (cd <= 300) return "Very fast";
  if (cd <= 600) return "Fast";
  if (cd <= 800) return "Medium";
  if (cd <= 1000) return "Slow";
  return "Very slow";
}

// little top-down diagram of which tiles a weapon's swing hits (you face up)
function SwingDiagram(props) {
  const swing = props.swing || [[1, 0]];
  const accent = props.accent || "#ffd23f";
  const cell = 16, sides = [-2, -1, 0, 1, 2];
  const maxF = Math.max(1, ...swing.map((s) => s[0]));
  const cols = sides.length, rows = maxF + 1;
  const ref = React.useRef(null);
  React.useEffect(() => {
    const ctx = ref.current.getContext("2d");
    ctx.clearRect(0, 0, cols * cell, rows * cell);
    // grid
    for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) {
      ctx.fillStyle = "rgba(255,255,255,0.05)";
      ctx.fillRect(c * cell + 1, r * cell + 1, cell - 2, cell - 2);
    }
    // hero at bottom-center
    const heroCol = 2, heroRow = rows - 1;
    ctx.fillStyle = "#8a8a96";
    ctx.fillRect(heroCol * cell + 3, heroRow * cell + 3, cell - 6, cell - 6);
    // hit tiles
    ctx.fillStyle = accent;
    swing.forEach(([f, s]) => {
      const c = s + 2, r = rows - 1 - f;
      if (c < 0 || c >= cols || r < 0) return;
      ctx.fillRect(c * cell + 2, r * cell + 2, cell - 4, cell - 4);
    });
  }, [swing, accent, cols, rows]);
  return (
    <div className="swingwrap">
      <canvas ref={ref} width={cols * cell} height={rows * cell} className="swingdiag" />
      <span className="swinglabel">▲ you face this way</span>
    </div>
  );
}

function StatBar(props) {
  const pips = [];
  for (let i = 0; i < props.max; i++)
    pips.push(<span key={i} className={"pip " + (i < props.value ? "on" : "")}
      style={i < props.value ? { background: props.accent } : null} />);
  return <span className="statbar">{pips}</span>;
}

function InventoryScreen(props) {
  const { inv, hp, maxHp, box, onClose, onEquip, onUse } = props;
  const ids = Object.keys(inv.items).filter((k) => inv.items[k] > 0);
  const [sel, setSel] = React.useState(inv.weapon || ids[0] || null);
  const item = sel ? GG.ITEMS[sel] : null;
  const accent = box.accent;
  const equippedWeapon = inv.weapon ? GG.ITEMS[inv.weapon] : null;
  const equippedArmor = inv.armor ? GG.ITEMS[inv.armor] : null;
  const isEquipped = item && ((item.type === "weapon" && inv.weapon === sel) || (item.type === "armor" && inv.armor === sel));

  return (
    <div className="invscreen" style={{ background: box.bg, color: box.text, boxShadow: `inset 0 0 0 4px ${box.border}` }}>
      <div className="inv-head">
        <span className="inv-title" style={{ color: accent }}>INVENTORY</span>
        <span className="inv-meta">
          <HeartRow hp={hp} max={maxHp} size={18} />
          <span className="inv-gold" style={{ color: accent }}>● {inv.gold}g</span>
        </span>
        <button className="inv-x" style={{ color: accent }} onClick={onClose} aria-label="Close">✕</button>
      </div>

      <div className="inv-cols">
        <div className="inv-left">
          <div className="inv-h" style={{ color: accent }}>EQUIPPED</div>
          <button className={"slot" + (sel === inv.weapon ? " active" : "")}
            style={sel === inv.weapon ? { borderColor: accent } : null}
            onClick={() => inv.weapon && setSel(inv.weapon)}>
            <span className="slot-tag">WEAPON</span>
            {equippedWeapon
              ? <span className="slot-body"><ItemIcon id={inv.weapon} size={26} /><span>{equippedWeapon.name}</span></span>
              : <span className="slot-empty">— none —</span>}
          </button>
          <button className={"slot" + (sel === inv.armor ? " active" : "")}
            style={sel === inv.armor ? { borderColor: accent } : null}
            onClick={() => inv.armor && setSel(inv.armor)}>
            <span className="slot-tag">ARMOR</span>
            {equippedArmor
              ? <span className="slot-body"><ItemIcon id={inv.armor} size={26} /><span>{equippedArmor.name}</span></span>
              : <span className="slot-empty">— none —</span>}
          </button>

          <div className="inv-h" style={{ color: accent, marginTop: 12 }}>BAG</div>
          <div className="bag-grid">
            {ids.length === 0 && <span className="slot-empty">empty</span>}
            {ids.map((id) => (
              <button key={id} className={"bag-cell" + (sel === id ? " active" : "")}
                style={sel === id ? { borderColor: accent } : null}
                onClick={() => setSel(id)} title={GG.ITEMS[id].name}>
                <ItemIcon id={id} size={28} />
                <span className="bag-qty">{inv.items[id]}</span>
              </button>
            ))}
          </div>
        </div>

        <div className="inv-right">
          {!item && <div className="detail-empty">Select an item to inspect it.</div>}
          {item && (
            <div className="detail">
              <div className="detail-top">
                <ItemIcon id={item.id} size={40} />
                <div>
                  <div className="detail-name" style={{ color: accent }}>{item.name}</div>
                  <div className="detail-type">{item.type}{isEquipped ? " · equipped" : ""}</div>
                </div>
              </div>
              <div className="detail-desc">{item.desc}</div>

              {item.type === "weapon" && (
                <div className="wstats">
                  <div className="wrow"><span>Power</span><StatBar value={item.power} max={4} accent={accent} /></div>
                  <div className="wrow"><span>Reach</span><StatBar value={item.reach} max={3} accent={accent} /></div>
                  <div className="wrow"><span>Speed</span><span className="wval">{swingSpeed(item.cd)}</span></div>
                  <SwingDiagram swing={item.swing} accent={accent} />
                </div>
              )}
              {item.type === "armor" && (
                <div className="wstats">
                  <div className="wrow"><span>Defense</span><StatBar value={item.defense} max={3} accent={accent} /></div>
                </div>
              )}

              <div className="detail-actions">
                {item.type === "weapon" || item.type === "armor" ? (
                  <button className="act-btn" disabled={isEquipped} style={{ borderColor: accent, color: accent }}
                    onClick={() => onEquip(item.id)}>{isEquipped ? "EQUIPPED" : "EQUIP"}</button>
                ) : null}
                {item.type === "consumable" ? (
                  <button className="act-btn" disabled={hp >= maxHp} style={{ borderColor: accent, color: accent }}
                    onClick={() => onUse(item.id)}>{hp >= maxHp ? "FULL HP" : "USE"}</button>
                ) : null}
              </div>
            </div>
          )}
        </div>
      </div>
      <div className="inv-foot">I or ESC to close · arrows to move · SPACE to attack</div>
    </div>
  );
}

Object.assign(window, { ItemIcon, Heart, HeartRow, SwingDiagram, InventoryScreen });
