// Pixel-art sprites. Rows delimited by newlines.
// '.' = transparent, '0' = lightest, '3' = darkest
const { useMemo } = React;

const SHADES = ['transparent', 'var(--light)', 'var(--mid)', 'var(--dark)', 'var(--ink)'];
function shadeFor(ch) {
  if (ch === '.') return SHADES[0];
  const n = parseInt(ch, 10);
  if (isNaN(n)) return SHADES[0];
  return SHADES[Math.min(4, n + 1)];
}

function Sprite({ data, scale = 4, style = {} }) {
  const rows = data.replace(/^\n+|\n+$/g, '').split('\n').map(r => r.replace(/\s/g, ''));
  const h = rows.length;
  const w = Math.max(...rows.map(r => r.length));
  return (
    <div style={{
      display: 'grid',
      gridTemplateColumns: `repeat(${w}, ${scale}px)`,
      gridTemplateRows: `repeat(${h}, ${scale}px)`,
      width: w * scale,
      height: h * scale,
      imageRendering: 'pixelated',
      ...style,
    }}>
      {rows.flatMap((row, y) =>
        row.padEnd(w, '.').split('').map((ch, x) => (
          <div key={`${x}-${y}`} style={{ background: shadeFor(ch) }} />
        ))
      )}
    </div>
  );
}

// Avatar 16x16 — pixel portrait
const SPRITE_AVATAR = `
.....333333.....
....33222233....
...3222222223...
..322111111223..
.32211000011223.
.32110000000123.
.32110303030123.
.32110000000123.
.32211000011223.
.32222111112233.
..3332222222333.
....33333333....
...3111111113...
..311222222113..
.31122222221113.
..333333333333..
`;

// Cartridge 16x15
const SPRITE_CART = `
3333333333333333
3222222222222223
3222222222222223
3211111111111123
3210000000000123
3210000000000123
3210000000000123
3210000000000123
3210000000000123
3211111111111123
3222222222222223
3222222222222223
3333322222223333
3..333333333..3.
3..3..3..3..3..3
`;

// Play button 16x12
const SPRITE_PLAY = `
3333333333333333
3222222222222223
3211111000011223
3211110000011223
3211100000011223
3211000000011223
3211000000011223
3211000000011223
3211111111111223
3222222222222223
3333333333333333
3111111111111113
`;

// Coin 12x12
const SPRITE_COIN = `
....3333....
..33222233..
.3211111123.
.3210330123.
3211033012.3
3210033012.3
3210303012.3
3210330112.3
.3210001123.
.3211111223.
..33222233..
....3333....
`;

// Trophy 12x14
const SPRITE_CUP = `
333333333333
322222222223
321111111123
321000000123
321000000123
321000000123
321000000123
.3211111123.
...3111113..
....3003....
....3003....
...322223...
..32222223..
3333333333 3
`;

window.Sprite = Sprite;
window.SPRITE_AVATAR = SPRITE_AVATAR;
window.SPRITE_CART = SPRITE_CART;
window.SPRITE_PLAY = SPRITE_PLAY;
window.SPRITE_COIN = SPRITE_COIN;
window.SPRITE_CUP = SPRITE_CUP;
