(function registerWartaHomePolicyParser(globalScope) {
  "use strict";
  const registry = globalScope.PolicyPdfParserRegistry;
  const common = globalScope.WartaPolicyParserCommon;
  const helpers = globalScope.PolicyPdfParserHelpers;
  if (!registry || !common || !helpers) throw new Error("Najpierw wczytaj wspólny parser Warty.");

  function parseAmount(value) {
    const amount = Number(String(value ?? "").replace(/[\s\u00a0]/g, "").replace(",", "."));
    return Number.isFinite(amount) ? amount : null;
  }

  function findHomeRiskSummary(allText) {
    const lines = String(allText ?? "").split(/\r?\n/).map(helpers.normalizeLine).filter(Boolean);
    const normalizedLines = lines.map(helpers.normalizeForDetection);
    const startIndex = normalizedLines.findIndex((line) => /^PRZEDMIOT I ZAKRES UBEZPIECZENIA$/.test(line));
    const endIndex = normalizedLines.findIndex((line, index) => index > startIndex && /^SKLADKA LACZNA\b/.test(line));
    if (startIndex < 0 || endIndex <= startIndex) return helpers.findRiskSummary(allText);
    const rowPattern = /^(?:DOM JEDNORODZINNY|LOKAL MIESZKALNY|STALE ELEMENTY|RUCHOMOSCI DOMOWE|KOSZTY POSZUKIWANIA|ODPOWIEDZIALNOSC CYWILNA|USLUGI ASSISTANCE|GARAZ\s*\/\s*INNY BUDYNEK|MALA ARCHITEKTURA|UTRATA CZYNSZU)\b/;
    const rows = [];
    let current = null;
    for (let index = startIndex + 1; index < endIndex; index += 1) {
      if (rowPattern.test(normalizedLines[index])) {
        if (current) rows.push(current);
        current = { lines: [lines[index]], normalized: [normalizedLines[index]] };
      } else if (current) {
        current.lines.push(lines[index]);
        current.normalized.push(normalizedLines[index]);
      }
    }
    if (current) rows.push(current);

    const risks = new Map();
    for (const row of rows) {
      const text = row.lines.join(" ");
      const normalized = row.normalized.join(" ");
      let label = "";
      if (/^DOM JEDNORODZINNY\b/.test(normalized)) label = "Dom jednorodzinny";
      else if (/^LOKAL MIESZKALNY\b/.test(normalized)) label = "Lokal mieszkalny";
      else if (/^STALE ELEMENTY\b/.test(normalized)) label = "Stałe elementy";
      else if (/^RUCHOMOSCI DOMOWE\b/.test(normalized)) label = "Ruchomości domowe";
      else if (/^KOSZTY POSZUKIWANIA\b/.test(normalized)) label = "Koszty usunięcia awarii";
      else if (/^ODPOWIEDZIALNOSC CYWILNA\b/.test(normalized)) label = "OC w życiu prywatnym";
      else if (/^USLUGI ASSISTANCE\b/.test(normalized)) label = "Assistance";
      else if (/^GARAZ\s*\/\s*INNY BUDYNEK\b/.test(normalized)) label = "Garaż/inny budynek";
      else if (/^MALA ARCHITEKTURA\b/.test(normalized)) label = "Mała architektura";
      else if (/^UTRATA CZYNSZU\b/.test(normalized)) label = "Utrata czynszu";
      if (!label) continue;

      const amounts = [...text.matchAll(/([0-9][0-9\s\u00a0]*(?:[.,][0-9]{1,2})?)\s*zł/gi)];
      let premium = null;
      if (!/\bW CENIE\b/.test(normalized)) {
        if (amounts.length >= 2 || (label === "Assistance" && amounts.length === 1)) {
          premium = parseAmount(amounts.at(-1)[1]);
        }
      }
      const previous = risks.get(label);
      if (premium !== null) risks.set(label, { amount: (previous?.amount ?? 0) + premium });
      else if (!previous) risks.set(label, { amount: null });
    }
    return [...risks]
      .map(([label, data]) => (
        data.amount === null
          ? label
          : `${label} ${new Intl.NumberFormat("pl-PL", { maximumFractionDigits: 2 }).format(data.amount)} zł`
      ))
      .join(" • ")
      .slice(0, 400);
  }
  registry.register({
    id: "warta-mieszkanie",
    insurer: "Warta",
    product: "Dom",
    detect: ({ detectionText }) => common.isWartaPolicy(detectionText)
      && /WNIOSEK-POLISA WARTA DOM(?: KOMFORT)?\s+NR/.test(detectionText),
    parse: (context) => common.parse(context, {
      registrationLabel: "Mieszkanie",
      riskSummaryResolver: findHomeRiskSummary,
    }),
  });
})(globalThis);
