function textContent(node: Element, namespace: string, localName: string): string {
  const element = node.getElementsByTagNameNS(namespace, localName)[0];
  return element ? element.textContent?.trim() ?? "" : "";
}

export function resolveDavBaseUrl(shareUrlValue: string): string {
  const url = new URL(shareUrlValue.trim());
  const publicShare = url.pathname.match(/\/s\/([^/?#]+)/);
  if (publicShare) {
    return url.origin + "/public.php/dav/files/" + publicShare[1] + "/";
  }

  const davShare = url.pathname.match(/\/public\.php\/dav\/files\/([^/?#]+)\/?/);
  if (davShare) {
    return url.origin + "/public.php/dav/files/" + davShare[1] + "/";
  }

  throw new Error("Please enter a public Nextcloud share link.");
}

export function parseListing(xmlText: string, baseUrl: string) {
  const documentNode = new DOMParser().parseFromString(xmlText, "application/xml");
  const responses = Array.from(documentNode.getElementsByTagNameNS("DAV:", "response"));
  const entries = responses
    .map((response) => {
      const href = textContent(response, "DAV:", "href");
      const prop = response.getElementsByTagNameNS("DAV:", "prop")[0];
      if (!href || !prop) {
        return null;
      }

      const contentType = textContent(prop, "DAV:", "getcontenttype");
      const lastModified = textContent(prop, "DAV:", "getlastmodified") || null;
      const displayName = textContent(prop, "DAV:", "displayname");
      const isCollection = prop.getElementsByTagNameNS("DAV:", "collection").length > 0;
      const absoluteUrl = new URL(href, baseUrl).toString();

      return {
        href: absoluteUrl,
        name: displayName || decodeURIComponent(absoluteUrl.split("/").pop() || "image"),
        lastModified,
        contentType,
        isCollection
      };
    })
    .filter((entry) => entry !== null);

  return entries.filter((entry) => {
    const resolved = entry.href.toLowerCase();
    const imageLike = entry.contentType.startsWith("image/") || /\.(jpe?g|png|gif|webp|heic|heif|tiff?|avif)$/i.test(resolved);
    return !entry.isCollection && imageLike;
  });
}
