export const LOGOS_PER_BLOCK = 6;
export const DEFAULT_ROW_COUNT = 1;
export const DEFAULT_LOGO_SLOTS_PER_BLOCK = 1;

export function emptyBlockIcons(rowCount = DEFAULT_ROW_COUNT) {
  const out = {};
  const count = Math.max(1, rowCount);
  for (let b = 1; b <= count; b += 1) {
    out[String(b)] = Array(LOGOS_PER_BLOCK).fill("");
  }
  return out;
}

export function maxBlockIconKey(raw) {
  let max = DEFAULT_ROW_COUNT;
  if (raw?.block_icons && typeof raw.block_icons === "object") {
    for (const key of Object.keys(raw.block_icons)) {
      const num = Number(key);
      if (Number.isInteger(num) && num > max) max = num;
    }
  }
  return max;
}

export function normalizeBlockIcons(raw, legacy = {}, rowCount = DEFAULT_ROW_COUNT) {
  const count = Math.max(rowCount, maxBlockIconKey(raw), DEFAULT_ROW_COUNT);
  const out = emptyBlockIcons(count);

  if (raw?.block_icons && typeof raw.block_icons === "object") {
    for (const [blockKey, ids] of Object.entries(raw.block_icons)) {
      if (!out[blockKey]) {
        out[blockKey] = Array(LOGOS_PER_BLOCK).fill("");
      }
      const arr = Array.isArray(ids) ? ids : Object.values(ids);
      for (let i = 0; i < LOGOS_PER_BLOCK; i += 1) {
        const id = arr[i];
        out[blockKey][i] =
          id != null && id !== "" ? String(id) : "";
      }
    }
  }

  const legacyMap = [
    ["1", legacy.logo_icon_id || legacy.block1_icon_id],
    ["2", legacy.logo2_icon_id || legacy.block2_icon_id],
    ["3", legacy.logo3_icon_id || legacy.block3_icon_id],
  ];

  for (const [blockKey, iconId] of legacyMap) {
    if (iconId && !out[blockKey]?.[0]) {
      if (!out[blockKey]) out[blockKey] = Array(LOGOS_PER_BLOCK).fill("");
      out[blockKey][0] = String(iconId);
    }
  }

  return out;
}

export function ensureBlockIconsForRows(blockIcons, rowCount) {
  const merged = normalizeBlockIcons({ block_icons: blockIcons }, {}, rowCount);
  for (const key of Object.keys(merged)) {
    if (Number(key) > rowCount) {
      delete merged[key];
    }
  }
  return emptyBlockIconsWithMerge(rowCount, merged);
}

function emptyBlockIconsWithMerge(rowCount, merged = {}) {
  const out = emptyBlockIcons(rowCount);
  for (const [key, ids] of Object.entries(merged)) {
    if (!out[key]) continue;
    const arr = Array.isArray(ids) ? ids : [];
    for (let i = 0; i < LOGOS_PER_BLOCK; i += 1) {
      out[key][i] = arr[i] != null && arr[i] !== "" ? String(arr[i]) : "";
    }
  }
  return out;
}

export function reindexBlockIconsAfterRowRemove(blockIcons, removedBlockIndex) {
  const next = {};
  const keys = Object.keys(blockIcons)
    .map(Number)
    .filter((key) => key >= 1)
    .sort((a, b) => a - b);

  let newIndex = 1;
  for (const key of keys) {
    if (key === removedBlockIndex) continue;
    next[String(newIndex)] = [...(blockIcons[String(key)] || Array(LOGOS_PER_BLOCK).fill(""))];
    newIndex += 1;
  }

  return next;
}

export function blockIconsToLegacyFields(blockIcons) {
  return {
    logo_icon_id: blockIcons["1"]?.[0] || "",
    logo2_icon_id: blockIcons["2"]?.[0] || "",
    logo3_icon_id: blockIcons["3"]?.[0] || "",
    block1_icon_id: blockIcons["1"]?.[0] || "",
    block2_icon_id: blockIcons["2"]?.[0] || "",
    block3_icon_id: blockIcons["3"]?.[0] || "",
  };
}

export function setBlockIconSlot(blockIcons, blockNum, slotIndex, iconId) {
  const key = String(blockNum);
  const next = {
    ...blockIcons,
    [key]: [...(blockIcons[key] || Array(LOGOS_PER_BLOCK).fill(""))],
  };
  next[key][slotIndex] = iconId ? String(iconId) : "";
  return next;
}

/**
 * Visible logo-slot count per row for UI controls.
 * Uses explicit counts when provided; otherwise infers from non-empty saved icons.
 */
export function inferBlockLogoCounts(
  blockIcons,
  rowCount = DEFAULT_ROW_COUNT,
  explicitCounts = {}
) {
  const counts = {};
  const maxRowFromIcons = Math.max(
    0,
    ...Object.keys(blockIcons || {})
      .map(Number)
      .filter((n) => Number.isInteger(n) && n > 0)
  );
  const maxRowFromExplicit = Math.max(
    0,
    ...Object.keys(explicitCounts || {})
      .map(Number)
      .filter((n) => Number.isInteger(n) && n > 0)
  );
  const count = Math.max(1, rowCount, maxRowFromIcons, maxRowFromExplicit);

  for (let b = 1; b <= count; b += 1) {
    const key = String(b);
    const explicit = Number(explicitCounts?.[key]);
    const inferredFromIcons = (blockIcons?.[key] || []).filter(Boolean).length;
    const base = Number.isFinite(explicit)
      ? explicit
      : Math.max(DEFAULT_LOGO_SLOTS_PER_BLOCK, inferredFromIcons);
    counts[key] = Math.max(
      DEFAULT_LOGO_SLOTS_PER_BLOCK,
      Math.min(LOGOS_PER_BLOCK, Math.trunc(base) || DEFAULT_LOGO_SLOTS_PER_BLOCK)
    );
  }

  return counts;
}
