(function registerPzuHomePolicyParser(globalScope) {
  "use strict";

  const registry = globalScope.PolicyPdfParserRegistry;
  const helpers = globalScope.PolicyPdfParserHelpers;
  if (!registry || !helpers) throw new Error("Najpierw wczytaj wspólny silnik importu polis PDF.");

  const { normalizeLine, normalizeForDetection, firstMatch, toIsoDate, cleanPremium } = helpers;

  function getPolicyHolderSection(lines) {
    const startIndex = lines.findIndex((line) => /^UBEZPIECZAJACY$/.test(normalizeForDetection(line)));
    if (startIndex < 0) return [];
    const endIndex = lines.findIndex((line, index) => (
      index > startIndex && /^UBEZPIECZONY$/.test(normalizeForDetection(line))
    ));
    return lines.slice(startIndex + 1, endIndex > startIndex ? endIndex : startIndex + 10);
  }

  function findClientName(holderLines) {
    const nameParts = [];
    for (const line of holderLines) {
      if (/^(PESEL|NIP|REGON|ADRES|E-?MAIL|TELEFON)\s*:/i.test(normalizeForDetection(line))) break;
      const candidate = normalizeLine(line);
      if (candidate) nameParts.push(candidate);
    }
    return nameParts.join(" ");
  }

  function findIdentityNumber(holderText) {
    const regon = firstMatch(holderText, [
      /REGON\s*:\s*([0-9][0-9 .-]{6,19})/i,
    ]).replace(/\D/g, "");
    if (regon) return regon;
    const pesel = firstMatch(holderText, [
      /PESEL\s*:\s*([0-9][0-9 .-]{9,15})/i,
    ]).replace(/\D/g, "");
    if (pesel) return pesel;
    return firstMatch(holderText, [
      /NIP\s*:\s*([0-9][0-9 .-]{8,15})/i,
    ]).replace(/\D/g, "");
  }

  function findContact(holderText) {
    const rawEmail = firstMatch(holderText, [/e-?mail\s*:\s*([^\n]+)/i]);
    const rawPhone = firstMatch(holderText, [/telefon\s*:\s*([^\n]+)/i]);
    const email = /@/.test(rawEmail) && !/NIEUSTALON|ODMOW/i.test(normalizeForDetection(rawEmail))
      ? rawEmail
      : "";
    const phoneDigits = rawPhone.replace(/\D/g, "");
    const phone = phoneDigits.length >= 7 && !/NIEUSTALON|ODMOW/i.test(normalizeForDetection(rawPhone))
      ? rawPhone.replace(/[()\s-]+/g, "")
      : "";
    return [
      phone ? `Telefon: ${phone}` : "",
      email ? `E-mail: ${email}` : "",
    ].filter(Boolean).join("\n");
  }

  function findInsurancePeriod(allText) {
    const match = allText.match(
      /Okres ubezpieczenia\s*:\s*od\s+(\d{2}\.\d{2}\.\d{4})(?:\s*r\.)?(?:\s*godz\.\s*\d{1,2}:\d{2})?\s+do\s+(\d{2}\.\d{2}\.\d{4})(?:\s*r\.)?/i,
    );
    return match ? [toIsoDate(match[1]), toIsoDate(match[2])] : ["", ""];
  }

  function parsePzuHomePolicy({ lines, allText }) {
    const holderLines = getPolicyHolderSection(lines);
    const holderText = holderLines.join("\n");
    const insurancePeriod = findInsurancePeriod(allText);
    const policy = {
      clientName: findClientName(holderLines),
      identityNumber: findIdentityNumber(holderText),
      contact: findContact(holderText),
      policyNumber: firstMatch(allText, [
        /Numer polisy\s+([0-9A-Z/-]{6,})/i,
      ]),
      registration: "Mieszkanie",
      clientAddress: helpers.findClientAddress(holderText),
      validFrom: insurancePeriod[0],
      validUntil: insurancePeriod[1],
      premium: cleanPremium(firstMatch(allText, [
        
        
        /Składka łączna\s*:?\s*([0-9][0-9 .,'\u00a0]*)\s*zł/i,
      ])),
      riskSummary: helpers.findRiskSummary(allText),
    };
    const missingRequiredFields = ["clientName", "policyNumber", "validUntil"]
      .filter((fieldName) => !policy[fieldName]);
    if (missingRequiredFields.length > 0) {
      const error = new Error("Nie udało się pewnie odczytać danych klienta, numeru polisy lub okresu z polisy PZU Dom.");
      error.code = "POLICY_FIELDS_MISSING";
      error.insurer = "PZU";
      error.missingFields = missingRequiredFields;
      throw error;
    }
    return {
      policy,
      missingOptionalFields: ["identityNumber", "validFrom", "premium"]
        .filter((fieldName) => !policy[fieldName]),
    };
  }

  registry.register({
    id: "pzu-dom",
    insurer: "PZU",
    product: "Dom",
    detect: ({ detectionText }) => /POLISA UBEZPIECZENIA PZU DOM/.test(detectionText)
      && /POWSZECHNY ZAKLAD UBEZPIECZEN/.test(detectionText),
    parse: parsePzuHomePolicy,
  });
})(globalThis);
