(function registerHestiaE7CommunicationPolicyParser(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 hestiaCommon = globalScope.HestiaPolicyParserCommon;
  if (!hestiaCommon) throw new Error("Najpierw wczytaj wspólny parser Hestii (afbulhgrbezwnsyxjotopfireaualjcslosoizmuzlmyyoqxngjcj.js).");

  const {
    normalizeLine,
    normalizeForDetection,
    firstMatch,
    normalizeVehicleIdentifier,
    findVehicleMakeAndModel,
    findFirstRegistrationDate,
    findVehicleExtraDetails,
    findClientAddress,
    cleanPremium,
  } = helpers;

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

  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 email = firstMatch(holderText, [/([^\s\n,;]+@[^\s\n,;]+)/i]);
    const phone = firstMatch(holderText, [
      /TEL\.?\s*:?\s*([+]?[0-9][0-9 ()-]{6,20})/i,
    ]).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+od\s+(\d{4}-\d{2}-\d{2})(?:\s+\d{1,2}:\d{2})?\s+do\s+(\d{4}-\d{2}-\d{2})(?:\s+\d{1,2}:\d{2})?/i,
    );
    return match ? [match[1], match[2]] : ["", ""];
  }

  function parseHestiaE7CommunicationPolicy({ lines, allText }) {
    const holderText = getPolicyHolderSection(lines).join("\n");
    const insurancePeriod = findInsurancePeriod(allText);
    const policy = {
      clientName: firstMatch(holderText, [
        /Ubezpieczający(?:\s*\/\s*Ubezpieczony)?\s*\n([^,\n]{3,180})(?=\s*,\s*DATA URODZENIA\s*:)/i,
      ]),
      identityNumber: findIdentityNumber(holderText),
      contact: findContact(holderText),
      policyNumber: firstMatch(allText, [/Polisa\s+E7-Kom\s+([0-9A-Z/-]{6,})/i]),
      registration: firstMatch(allText, [
        /Ubezpieczony pojazd[\s\S]{0,500}?,\s*([A-Z]{1,3}[A-Z0-9]{3,8})\s*,\s*ROK PRODUKCJI\s*:/i,
      ]).replace(/\s+/g, "").toLocaleUpperCase("pl"),
      ...findVehicleMakeAndModel(allText),
      vin: normalizeVehicleIdentifier(firstMatch(allText, [
        /\bVIN\s*:?\s*([A-Z0-9][A-Z0-9 -]{3,23})/i,
        /nr\s+nadwozia\s*:?\s*([A-Z0-9][A-Z0-9 -]{3,23})/i,
      ])),
      firstRegistrationDate: findFirstRegistrationDate(allText),
      ...findVehicleExtraDetails(allText),
      clientAddress: findClientAddress(holderText),
      validFrom: insurancePeriod[0],
      validUntil: insurancePeriod[1],
      premium: cleanPremium(firstMatch(allText, [
        /RAZEM DO ZAPŁATY\s+([0-9][0-9 .,'\u00a0]*)/i,
      ])),
      riskSummary: hestiaCommon.findCommunicationRiskSummary(allText),
    };
    const missingRequiredFields = ["clientName", "policyNumber", "registration", "validUntil"]
      .filter((fieldName) => !policy[fieldName]);
    if (missingRequiredFields.length > 0) {
      const error = new Error("Nie udało się pewnie odczytać danych klienta, numeru polisy, rejestracji lub okresu z polisy komunikacyjnej E7 ERGO Hestii.");
      error.code = "POLICY_FIELDS_MISSING";
      error.insurer = "Hestia";
      error.missingFields = missingRequiredFields;
      throw error;
    }
    return {
      policy,
      missingOptionalFields: ["identityNumber", "validFrom", "premium"]
        .filter((fieldName) => !policy[fieldName]),
    };
  }

  registry.register({
    id: "hestia-e7-komunikacja",
    insurer: "Hestia",
    product: "Komunikacja E7",
    detect: ({ detectionText }) => /POLISA E7-KOM\s+[0-9A-Z/-]+/.test(detectionText)
      && /ERGO HESTIA/.test(detectionText),
    parse: parseHestiaE7CommunicationPolicy,
  });
})(globalThis);
