/**
 * Preview-only segmentation for the merged initiative DOCX (aligned with
 * `bieu_mau_sang_kien_template.json` top-level sections).
 */

export type BieuMauPreviewSectionId =
  | 'cover'
  | 'm01'
  | 'm02'
  | 'm03'
  | 'm04'
  | 'ban_cam_ket'
  | 'xac_nhan_tailieu'
  | 'xac_nhan_baibao';

export type DraftFormTab = 'application' | 'report' | 'contribution';

export type BieuMauPreviewSectionDef = {
  id: BieuMauPreviewSectionId;
  label: string;
  /** Substrings searched in paragraph text (document order). First match advances section. */
  markers: readonly string[];
  primaryTab?: DraftFormTab;
};

/**
 * Order matches typical template flow. Markers must stay in sync with visible titles in `template_application_form.docx`.
 */
export const BIEU_MAU_PREVIEW_SECTION_DEFS: readonly BieuMauPreviewSectionDef[] = [
  { id: 'cover', label: 'Trang bìa', markers: [], primaryTab: 'report' },
  { id: 'm01', label: 'Mẫu 01 — Báo cáo mô tả', markers: ['MẪU SỐ 01'], primaryTab: 'report' },
  { id: 'm02', label: 'Mẫu 02 — Đơn đề nghị', markers: ['MẪU SỐ 02'], primaryTab: 'application' },
  { id: 'm03', label: 'Mẫu 03 — Tỷ lệ đóng góp', markers: ['MẪU SỐ 03'], primaryTab: 'contribution' },
  { id: 'm04', label: 'Mẫu 04 — Phiếu đánh giá', markers: ['MẪU SỐ 04'], primaryTab: undefined },
  { id: 'ban_cam_ket', label: 'Bản cam kết', markers: ['BẢN CAM KẾT'], primaryTab: 'application' },
  {
    id: 'xac_nhan_tailieu',
    label: 'Xác nhận TLTK (2.2.2)',
    markers: ['BẢN XÁC NHẬN TÀI LIỆU THAM KHẢO'],
    primaryTab: 'application',
  },
  {
    id: 'xac_nhan_baibao',
    label: 'Xác nhận bài báo (2.1.2)',
    markers: ['BẢN XÁC NHẬN BÀI BÁO TRONG NƯỚC'],
    primaryTab: 'application',
  },
] as const;

export const ALL_BIEU_MAU_PREVIEW_SECTION_IDS: ReadonlySet<BieuMauPreviewSectionId> = new Set(
  BIEU_MAU_PREVIEW_SECTION_DEFS.map((d) => d.id),
);

function normalizePreviewText(raw: string): string {
  return raw.replace(/\s+/g, ' ').trim();
}

/** Tables as a unit; paragraphs outside tables only. */
export function collectDocxPreviewBlocks(wrapper: HTMLElement): HTMLElement[] {
  const blocks: HTMLElement[] = [];
  for (const table of wrapper.querySelectorAll<HTMLElement>('table')) {
    blocks.push(table);
  }
  for (const p of wrapper.querySelectorAll<HTMLElement>('p')) {
    if (!p.closest('table')) blocks.push(p);
  }
  blocks.sort((a, b) => {
    const pos = a.compareDocumentPosition(b);
    if (pos & Node.DOCUMENT_POSITION_FOLLOWING) return -1;
    if (pos & Node.DOCUMENT_POSITION_PRECEDING) return 1;
    return 0;
  });
  return blocks;
}

/**
 * Clears previous marks, walks blocks in order, assigns `data-bieu-section`.
 * Call after each docx-preview render.
 */
export function applyBieuMauSectionMarkers(docxWrapper: HTMLElement): void {
  docxWrapper.querySelectorAll('[data-bieu-section]').forEach((el) => {
    el.removeAttribute('data-bieu-section');
    el.classList.remove('bieu-section-visible');
  });

  const blocks = collectDocxPreviewBlocks(docxWrapper);
  let sectionIdx = 0;

  for (const el of blocks) {
    const text = normalizePreviewText(el.textContent ?? '');
    if (text.length > 0) {
      for (let j = sectionIdx + 1; j < BIEU_MAU_PREVIEW_SECTION_DEFS.length; j++) {
        const def = BIEU_MAU_PREVIEW_SECTION_DEFS[j];
        if (def.markers.some((m) => text.includes(m))) {
          sectionIdx = j;
          break;
        }
      }
    }
    const id = BIEU_MAU_PREVIEW_SECTION_DEFS[sectionIdx].id;
    el.dataset.bieuSection = id;
    el.classList.add('bieu-section-visible');
  }
}

export function applyBieuMauSectionVisibility(
  previewRoot: HTMLElement,
  docxWrapper: HTMLElement | null,
  visible: ReadonlySet<BieuMauPreviewSectionId>,
): void {
  const allCount = ALL_BIEU_MAU_PREVIEW_SECTION_IDS.size;
  const showAll = visible.size === 0 || visible.size >= allCount;

  if (showAll) {
    previewRoot.removeAttribute('data-bieu-layout-filter-active');
    docxWrapper?.querySelectorAll('[data-bieu-section]').forEach((el) => {
      el.classList.add('bieu-section-visible');
    });
    return;
  }

  previewRoot.setAttribute('data-bieu-layout-filter-active', 'true');
  docxWrapper?.querySelectorAll('[data-bieu-section]').forEach((el) => {
    const id = el.getAttribute('data-bieu-section') as BieuMauPreviewSectionId | null;
    const on = id ? visible.has(id) : true;
    el.classList.toggle('bieu-section-visible', on);
  });
}

export function sectionIdsForDraftTab(tab: DraftFormTab): ReadonlySet<BieuMauPreviewSectionId> {
  return new Set(BIEU_MAU_PREVIEW_SECTION_DEFS.filter((d) => d.primaryTab === tab).map((d) => d.id));
}

export function scrollPreviewToSection(docxWrapper: HTMLElement | null, sectionId: BieuMauPreviewSectionId): void {
  if (!docxWrapper) return;
  const el = docxWrapper.querySelector(`[data-bieu-section="${sectionId}"]`);
  el?.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
