/**
 * Shared utilities for Icon and Pictogram components
 */

/**
 * Copies SVG code to clipboard when an icon/pictogram is clicked
 * @param {HTMLElement} svgElement - The SVG element that was clicked
 * @param {string} type - Type of element ('icon' or 'pictogram')
 */
export const handleSvgClick = async (svgElement, type = "icon") => {
  const useElement = svgElement.querySelector("use");
  const href = useElement.getAttribute("xlink:href");
  const spriteUrl = href.split("#")[0];
  const iconId = href.split("#")[1];

  const response = await fetch(spriteUrl);
  const spriteText = await response.text();
  const parser = new DOMParser();
  const spriteDoc = parser.parseFromString(spriteText, "image/svg+xml");
  const iconSymbol = spriteDoc.getElementById(iconId);

  // Create a new SVG element and copy attributes from the symbol
  const svgElementCopy = document.createElementNS(
    "http://www.w3.org/2000/svg",
    "svg",
  );
  Array.from(iconSymbol.attributes).forEach((attr) => {
    svgElementCopy.setAttribute(attr.name, attr.value);
  });

  // Copy the inner HTML from the symbol to the new SVG element
  svgElementCopy.innerHTML = iconSymbol.innerHTML;

  const svgHTML = svgElementCopy.outerHTML;
  navigator.clipboard.writeText(svgHTML).then(() => {
    const typeName = type.charAt(0).toUpperCase() + type.slice(1);
    window.alert(`${typeName} copied to clipboard`);
  });
};

/**
 * Loads all icon/pictogram names from the assets folder
 * @param {Function} requireContext - webpack require.context function
 * @param {Function} filterFn - Optional filter function to apply to icon names
 * @returns {string[]} Array of icon/pictogram names
 */
export const loadIconNames = (requireContext, filterFn) => {
  try {
    let names = requireContext
      .keys()
      .sort()
      .map((icon) => icon.substring(2).replace(".svg", ""));

    if (filterFn) {
      names = names.filter(filterFn);
    }

    return names;
  } catch (error) {
    console.warn("Could not load icon names:", error);
    return [];
  }
};
