import {
  emptyBlockIcons,
  inferBlockLogoCounts,
  normalizeBlockIcons,
} from "./blockIcons.js";
import { syncPageRowAssets } from "./pageContentRows.js";
import { normalizeCanvasItems } from "./pictureCanvas.js";
import { stampPictureCellRowSpans } from "./pictureRowLayout.js";
import {
  defaultTextBlocks,
  normalizeTextBlocks,
  textBlocksSnippet,
  textBlocksToLegacyFields,
} from "./textBlocks.js";

export const SHARED_FORM_KEYS = [
  "margin_date",
  "margin_ref",
  "station",
  "job_area",
  "document_no",
  "issue_date",
  "part_number",
  "description",
  "process",
  "footer_url",
];

function normalizeMaterialsLabel(value) {
  return value == null ? "" : String(value);
}

function normalizePageMarkers(source = {}) {
  return {
    tips: Boolean(source?.tips ?? source?.marker_tips),
    quality: Boolean(source?.quality ?? source?.marker_quality),
    safety: Boolean(source?.safety ?? source?.marker_safety),
    visual: Boolean(source?.visual ?? source?.marker_visual),
  };
}

export function pickSharedForm(form) {
  const out = {};
  for (const key of SHARED_FORM_KEYS) {
    if (form?.[key] != null) out[key] = form[key];
  }
  return out;
}

export function apiPageRecordToPageForm(page) {
  const rawBlockIcons = {};
  for (const block of page.blocks || []) {
    const key = String(block.block_index);
    if (!rawBlockIcons[key]) {
      rawBlockIcons[key] = Array(6).fill("");
    }
    const ids = Array.isArray(block.icon_ids)
      ? block.icon_ids
      : block.icon_id
        ? [block.icon_id]
        : [];
    ids.forEach((id, i) => {
      if (id && i < rawBlockIcons[key].length) {
        rawBlockIcons[key][i] = String(id);
      }
    });
  }

  const image_slots = {};
  for (const img of page.images || []) {
    if (img.image_data_url) {
      image_slots[String(Number(img.slot_index) - 1)] = img.image_data_url;
    }
  }

  const text_blocks = normalizeTextBlocks({
    blocks: (page.blocks || []).map((block) => ({
      block_index: block.block_index,
      text: block.text,
      height_px: block.height_px,
      pic_merge_next: Boolean(block.pic_merge_next),
    })),
  });
  const picture_merge_next = {};
  for (const block of page.blocks || []) {
    picture_merge_next[String(block.block_index)] = Boolean(block.pic_merge_next);
  }
  const page_markers = normalizePageMarkers(page.page_markers || page);

  const normalizedBlockIcons = normalizeBlockIcons(
    { block_icons: rawBlockIcons },
    {},
    text_blocks.length
  );

  const loaded = syncPageRowAssets({
    page_id: page.page_id ?? null,
    _localId: page.page_id
      ? `page-${page.page_id}`
      : `local-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
    page_num: page.page_num ?? 1,
    materials_label: normalizeMaterialsLabel(page.page_header),
    marker_tips: page_markers.tips,
    marker_quality: page_markers.quality,
    marker_safety: page_markers.safety,
    marker_visual: page_markers.visual,
    page_markers,
    text_blocks,
    block_icons: normalizedBlockIcons,
    block_logo_counts: inferBlockLogoCounts(
      normalizedBlockIcons,
      text_blocks.length,
      page.block_logo_counts
    ),
    show_logo_plus: true,
    image_slots,
    picture_merge_next,
    picture_canvas: normalizeCanvasItems({
      picture_canvas: page.picture_canvas,
      image_slots,
    }),
  });
  return {
    ...loaded,
    picture_canvas: stampPictureCellRowSpans(loaded),
  };
}

export function formPayloadToPageForm(form) {
  const text_blocks = normalizeTextBlocks(form);
  const normalizedBlockIcons = normalizeBlockIcons(form, form, text_blocks.length);
  const page_markers = normalizePageMarkers(form.page_markers || form);
  return syncPageRowAssets({
    page_id: null,
    _localId: `local-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
    page_num: 1,
    materials_label: normalizeMaterialsLabel(form.materials_label),
    marker_tips: page_markers.tips,
    marker_quality: page_markers.quality,
    marker_safety: page_markers.safety,
    marker_visual: page_markers.visual,
    page_markers,
    text_blocks,
    block_icons: normalizedBlockIcons,
    block_logo_counts: inferBlockLogoCounts(
      normalizedBlockIcons,
      text_blocks.length,
      form.block_logo_counts
    ),
    show_logo_plus: form.show_logo_plus !== false,
    image_slots: { ...(form.image_slots || {}) },
    picture_canvas: normalizeCanvasItems(form),
  });
}

export function createBlankPageForm(pageNum, footerUrl = "") {
  const page_markers = normalizePageMarkers();
  return syncPageRowAssets({
    page_id: null,
    _localId: `local-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
    page_num: pageNum,
    materials_label: "",
    marker_tips: page_markers.tips,
    marker_quality: page_markers.quality,
    marker_safety: page_markers.safety,
    marker_visual: page_markers.visual,
    page_markers,
    text_blocks: defaultTextBlocks(),
    block_icons: emptyBlockIcons(),
    block_logo_counts: {},
    show_logo_plus: true,
    image_slots: {},
    picture_canvas: [],
    _footerUrl: footerUrl,
  });
}

/** Clone page content locally (new draft — gets page_id on save). */
export function clonePageFormFromSource(pageForm) {
  const text_blocks = normalizeTextBlocks(pageForm);
  const page_markers = normalizePageMarkers(pageForm.page_markers || pageForm);
  const normalizedBlockIcons = normalizeBlockIcons(
    pageForm,
    pageForm,
    text_blocks.length
  );
  return syncPageRowAssets({
    page_id: null,
    _localId: `local-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
    page_num: pageForm.page_num,
    materials_label: normalizeMaterialsLabel(pageForm.materials_label),
    marker_tips: page_markers.tips,
    marker_quality: page_markers.quality,
    marker_safety: page_markers.safety,
    marker_visual: page_markers.visual,
    page_markers,
    text_blocks,
    block_icons: normalizedBlockIcons,
    block_logo_counts: inferBlockLogoCounts(
      normalizedBlockIcons,
      text_blocks.length,
      pageForm.block_logo_counts
    ),
    show_logo_plus: pageForm.show_logo_plus !== false,
    image_slots: { ...(pageForm.image_slots || {}) },
    picture_canvas: normalizeCanvasItems(pageForm).map(({ image_id, ...rest }) => rest),
  });
}

export function syncPageNumbers(pageForms) {
  const total = pageForms.length || 1;
  return pageForms.map((page, index) => ({
    ...page,
    page_num: index + 1,
  }));
}

export function movePageInList(pageForms, fromIndex, toIndex) {
  if (
    fromIndex === toIndex ||
    fromIndex < 0 ||
    toIndex < 0 ||
    fromIndex >= pageForms.length ||
    toIndex >= pageForms.length
  ) {
    return pageForms;
  }
  const next = [...pageForms];
  const [moved] = next.splice(fromIndex, 1);
  next.splice(toIndex, 0, moved);
  return syncPageNumbers(next);
}

export function buildPageOrderPayload(pageForms) {
  return pageForms
    .map((page, index) => ({
      page_id: page.page_id,
      page_num: index + 1,
    }))
    .filter((row) => row.page_id != null && Number(row.page_id) > 0);
}

export function pageOrderKey(pageForm) {
  if (pageForm?.page_id != null) return `id:${pageForm.page_id}`;
  return pageForm?._localId || `draft:${pageForm?.page_num ?? 0}`;
}

export function buildOrderSignature(pageForms) {
  return (pageForms || []).map(pageOrderKey).join("|");
}

export function isPageOrderDirty(pageForms, savedOrderSignature) {
  if (!savedOrderSignature) return false;
  const savedKeys = savedOrderSignature.split("|");
  const currentKeys = (pageForms || []).map(pageOrderKey);
  const savedFiltered = savedKeys.filter((key) => currentKeys.includes(key));
  const currentFiltered = currentKeys.filter((key) => savedKeys.includes(key));
  if (savedFiltered.length < 2) return false;
  return savedFiltered.join("|") !== currentFiltered.join("|");
}

export function restorePageOrder(pageForms, savedOrderSignature) {
  if (!savedOrderSignature) return syncPageNumbers(pageForms);
  const savedKeys = savedOrderSignature.split("|");
  const byKey = new Map((pageForms || []).map((page) => [pageOrderKey(page), page]));
  const restored = [];

  for (const key of savedKeys) {
    if (byKey.has(key)) {
      restored.push(byKey.get(key));
      byKey.delete(key);
    }
  }

  for (const page of pageForms || []) {
    const key = pageOrderKey(page);
    if (byKey.has(key)) {
      restored.push(page);
      byKey.delete(key);
    }
  }

  return syncPageNumbers(restored);
}

/** @returns {Map<string, number>} key → original 1-based position */
export function buildOriginalPositions(savedOrderKeys) {
  const map = new Map();
  (savedOrderKeys || []).forEach((key, index) => {
    map.set(key, index + 1);
  });
  return map;
}

export function pageShortTitle(pageForm, index) {
  const header = pageForm.materials_label?.trim();
  if (header) return header;
  const preview = textBlocksSnippet(pageForm.text_blocks || normalizeTextBlocks(pageForm))
    ?.slice(0, 36);
  if (preview) return preview;
  if (!pageForm.page_id) return "New page";
  return `Page ${index + 1} content`;
}

/** Snapshot for thumbnail previews in the page filmstrip. */
export function pagePreviewSnapshot(pageForm, index) {
  const canvasItems = normalizeCanvasItems(pageForm);
  const previewImage = canvasItems[0]?.image_data_url || null;

  const snippet =
    textBlocksSnippet(pageForm.text_blocks || normalizeTextBlocks(pageForm))?.slice(
      0,
      120
    ) || "";

  const blockIcons = pageForm.block_icons || {};
  const logoCount = Object.values(blockIcons).reduce(
    (count, slots) => count + (Array.isArray(slots) ? slots.filter(Boolean).length : 0),
    0
  );
  const imageCount = canvasItems.length;

  return {
    title: pageShortTitle(pageForm, index),
    previewImage,
    snippet,
    logoCount,
    imageCount,
    isEmpty: !previewImage && !snippet && logoCount === 0,
  };
}

export function pageMoveHint(pageForm, index, originalPositions) {
  const key = pageOrderKey(pageForm);
  const from = originalPositions.get(key);
  const to = index + 1;
  if (from == null) return null;
  if (from === to) return null;
  return { from, to };
}

export function mergeSavePayload(sharedForm, pageForm, totalPages) {
  const pageNum = pageForm.page_num || 1;
  const text_blocks = normalizeTextBlocks(pageForm);
  const page_markers = normalizePageMarkers(pageForm.page_markers || pageForm);
  return {
    ...sharedForm,
    ...(pageForm.page_id != null ? { page_id: pageForm.page_id } : {}),
    materials_label: normalizeMaterialsLabel(pageForm.materials_label),
    text_blocks,
    ...textBlocksToLegacyFields(text_blocks),
    block_icons: pageForm.block_icons || emptyBlockIcons(),
    block_logo_counts: pageForm.block_logo_counts || {},
    show_logo_plus: pageForm.show_logo_plus !== false,
    picture_canvas: pageForm.picture_canvas || [],
    picture_merge_next: pageForm.picture_merge_next || {},
    marker_tips: page_markers.tips,
    marker_quality: page_markers.quality,
    marker_safety: page_markers.safety,
    marker_visual: page_markers.visual,
    page_markers,
    page: `${pageNum}/${totalPages}`,
    footer_page: `${pageNum}/${totalPages}`,
  };
}
