  const DEFAULT_BOARD_SIZE = { width: 900, height: 620 };

  export function defaultLayout(stableIndex, total = 1, size = DEFAULT_BOARD_SIZE) {
    return autoLayoutForArtifacts(
      Array.from({ length: total }, (_, idx) => ({ id: String(idx) })),
      size
    )[stableIndex] || { x: 16, y: 16, width: 520, height: 380 };
  }

  export function chooseLayoutColumns(count, width) {
    if (width < 640) return { cols: 1, rows: count };
    if (count <= 1) return { cols: 1, rows: 1 };
    if (count <= 3) return { cols: count, rows: 1 };
    if (count <= 4) return { cols: 2, rows: 2 };
    if (count <= 6) return { cols: 3, rows: 2 };
    if (count <= 8) return { cols: 4, rows: 2 };
    return { cols: Math.ceil(count / 2), rows: 2 };
  }

  export function autoLayoutForArtifacts(arts, size = DEFAULT_BOARD_SIZE) {
    const count = Math.max(1, arts.length);
    const width = Math.max(320, size.width || 900);
    const height = Math.max(360, size.height || 620);
    const pad = width < 640 ? 10 : 16;
    const gap = width < 640 ? 10 : 14;
    const { cols, rows } = chooseLayoutColumns(count, width);
    const availableW = Math.max(cols * 280, width - pad * 2 - gap * (cols - 1));
    const availableH = Math.max(rows * 180, height - pad * 2 - gap * (rows - 1));
    const baseColW = Math.floor(availableW / cols);
    const baseRowH = Math.floor(availableH / rows);
    const extraW = availableW - baseColW * cols;
    const extraH = availableH - baseRowH * rows;

    return arts.map((_, idx) => {
      const col = idx % cols;
      const row = Math.floor(idx / cols);
      const colW = baseColW + (col === cols - 1 ? extraW : 0);
      const rowH = baseRowH + (row === rows - 1 ? extraH : 0);
      return {
        x: pad + col * (baseColW + gap),
        y: pad + row * (baseRowH + gap),
        width: Math.max(280, colW),
        height: Math.max(180, rowH),
      };
    });
  }

