const LICENSE_KEY_PATTERN = /^DB-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$/;

export function getLicenseElements(rootDocument = document) {
  return {
    licenseKeyIcon: rootDocument.getElementById("licenseKeyIcon"),
    licenseKeyPopup: rootDocument.getElementById("licenseKeyPopup"),
    closeLicensePopup: rootDocument.getElementById("closeLicensePopup"),
    licenseKeyInput: rootDocument.getElementById("licenseKeyInput"),
    validateLicenseBtn: rootDocument.getElementById("validateLicenseBtn"),
    licenseMessage: rootDocument.getElementById("licenseMessage"),
    licenseStatusCard: rootDocument.getElementById("licenseStatusCard"),
    licenseStatusIcon: rootDocument.getElementById("licenseStatusIcon"),
    licenseStatusLabel: rootDocument.getElementById("licenseStatusLabel"),
    licenseStatusDetail: rootDocument.getElementById("licenseStatusDetail"),
    licenseDeactivateRow: rootDocument.getElementById("licenseDeactivateRow"),
    deactivateLicenseBtn: rootDocument.getElementById("deactivateLicenseBtn"),
    copyFingerprintBtn: rootDocument.getElementById("copyFingerprintBtn")
  };
}

export function normalizeLicenseKey(value) {
  const normalized = String(value ?? "").toUpperCase().replace(/[^A-Z0-9]/g, "");
  if (!normalized) {
    return "";
  }

  if (!normalized.startsWith("DB")) {
    return normalized.slice(0, 24);
  }

  const body = normalized.slice(2, 18);
  const groups = body.match(/.{1,4}/g) || [];
  return ["DB", ...groups].join("-");
}

export function isLicenseKeyFormatValid(value) {
  return LICENSE_KEY_PATTERN.test(String(value ?? "").trim().toUpperCase());
}

export function maskLicenseKey(value) {
  const normalized = normalizeLicenseKey(value);
  if (!isLicenseKeyFormatValid(normalized)) {
    return normalized;
  }

  const parts = normalized.split("-");
  return `${parts[0]}-${parts[1]}-****-****-${parts[4]}`;
}
