(function registerHestiaYcdCommunicationPolicyParser(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,
    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 POJAZD$/.test(normalizeForDetection(line))
    ));
    return lines.slice(startIndex, endIndex > startIndex ? endIndex : startIndex + 5);
  }

  function findRiskSummary(lines) {
    const normalizedLines = lines.map(normalizeForDetection);
    const startIndex = normalizedLines.findIndex((line) => /^PRODUKT UBEZPIECZENIOWY\b/.test(line));
    const endIndex = normalizedLines.findIndex((line, index) => (
      index > startIndex && /^RAZEM DO ZAPLATY\b/.test(line)
    ));
    if (startIndex < 0 || endIndex <= startIndex) return "";
    const riskDefinitions = [
      ["OC", /OC POSIADACZ(?:A|Y) POJAZD/],
      ["AC", /^AUTOCASCO\b/],
      ["NNW kierowcy", /^NNW KIEROWCY\b/],
      ["Szyby", /^SZYBY\b/],
      ["Assistance", /ASSISTANCE/],
      ["Zielona Karta", /ZIELONA KARTA/],
    ];
    const risks = [];
    for (let index = startIndex + 1; index < endIndex; index += 1) {
      const definition = riskDefinitions.find(([, pattern]) => pattern.test(normalizedLines[index]));
      if (!definition || risks.some(([label]) => label === definition[0])) continue;
      
      
      const amount = normalizeLine(lines[index]).match(/(?:^|\s)([0-9]{1,3}(?:,[0-9]{2})?|[0-9]{1,3} [0-9]{3}(?:,[0-9]{2})?)$/)?.[1] || "";
      risks.push([definition[0], amount]);
    }
    return risks
      .map(([label, amount]) => (amount ? `${label} ${amount} zł` : label))
      .join(" • ")
      .slice(0, 400);
  }

  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 parseHestiaYcdCommunicationPolicy({ 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: firstMatch(holderText, [
        /(?:REGON|PESEL|NIP)\s*:\s*([0-9][0-9 .-]{7,18})/i,
      ]).replace(/\D/g, ""),
      contact: findContact(holderText),
      policyNumber: firstMatch(allText, [
        /Polisa Pakiet ubezpieczeń komunikacyjnych YCD\s+([0-9]{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,
      ])),
      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 .,' ]*)/i,
      ])),
      riskSummary: findRiskSummary(lines),
    };
    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 You Can Drive.");
      error.code = "POLICY_FIELDS_MISSING";
      error.insurer = "You Can Drive";
      error.missingFields = missingRequiredFields;
      throw error;
    }
    return {
      policy,
      missingOptionalFields: ["identityNumber", "validFrom", "premium"]
        .filter((fieldName) => !policy[fieldName]),
    };
  }

  registry.register({
    id: "hestia-ycd-komunikacja",
    insurer: "You Can Drive",
    product: "Komunikacja YCD",
    detect: ({ detectionText }) => /POLISA PAKIET UBEZPIECZEN KOMUNIKACYJNYCH YCD\s+[0-9]/.test(detectionText)
      && /ERGO HESTIA/.test(detectionText),
    parse: parseHestiaYcdCommunicationPolicy,
  });
})(globalThis);
