/**
 * SVGIconSetting Icon Renderer
 *
 * アイコンレンダリング関連の機能を管理
 */

import { featherIconsData, fontAwesomeOutlineData, fontAwesomeSolidData, fontAwesomeBrandsData, tablerOutlineData, tablerSolidData, heroiconsOutlineData, heroiconsSolidData, remixiconOutlineData, remixiconSolidData, lucideData, adjustViewBoxToPath } from "./utils";

/**
 * Unicode対応のBase64デコード関数
 * @param {string} base64String - デコードするBase64文字列
 * @returns {string} デコードされた文字列
 */
const decodeBase64Unicode = (base64String) => {
  try {
    // Base64デコードしてUTF-8バイトシーケンスに変換
    const binaryString = atob(base64String);
    const bytes = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
      bytes[i] = binaryString.charCodeAt(i);
    }
    // UTF-8バイトシーケンスから文字列に変換
    return new TextDecoder().decode(bytes);
  } catch (error) {
    // console.error("Base64 decoding failed:", error);
    // フォールバック: 元の方法を試す
    try {
      return atob(base64String);
    } catch (fallbackError) {
      // console.error("Fallback base64 decoding also failed:", fallbackError);
      throw new Error("Base64 decoding failed for custom SVG");
    }
  }
};

/**
 * アイコン選択モーダルで使用するアイコン描画関数
 * 素線（アウトライン）スタイルで統一する
 * @param {string} icon - アイコン識別子
 * @param {string} color - アイコンの色
 * @returns {string} SVG文字列
 */
export const renderIconForSelector = (icon, color = "#333333") => {
  // Feather Icons
  if (icon && icon.startsWith("feather-")) {
    const iconName = icon.replace("feather-", "");
    if (featherIconsData[iconName]) {
      const iconContent = featherIconsData[iconName];
      // Check if the content is SVG format (contains SVG elements) or old path format
      if (iconContent.includes("<")) {
        // New SVG format - use the SVG content directly and replace currentColor
        let processedContent = iconContent.replace(/stroke="currentColor"/g, `stroke="currentColor"`).replace(/fill="currentColor"/g, 'fill="none"');

        // First, remove ALL existing stroke-width attributes to ensure consistency
        processedContent = processedContent.replace(/stroke-width="[^"]*"/g, "");

        // Process all SVG elements to ensure proper attributes and self-closing tags
        processedContent = processedContent.replace(/<(path|circle|rect|line|polyline|polygon|ellipse)([^>]*?)\s*\/?>/g, (match, tagName, attributes) => {
          let newAttributes = attributes;

          // Force fill="none" for all path and circle elements
          if (["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"].includes(tagName)) {
            // Remove existing fill attribute first
            newAttributes = newAttributes.replace(/fill="[^"]*"/g, "");
            // Add fill="none"
            newAttributes += ' fill="none"';
          }

          // Add stroke if not present (for elements that typically have stroke)
          if (!newAttributes.includes("stroke=") && ["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"].includes(tagName)) {
            newAttributes += ` stroke="currentColor"`;
          }

          // Add consistent stroke-width for all stroke elements (for selector display)
          if (["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"].includes(tagName)) {
            newAttributes += ' stroke-width="2"';
          }

          return `<${tagName}${newAttributes} />`;
        });

        return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
        ${processedContent}
      </svg>`;
      } else {
        // Old path format - wrap in a single path element
        return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
        <path d="${iconContent}" fill="none" />
      </svg>`;
      }
    }
  }

  // Font Awesome
  if (icon && icon.startsWith("fa-")) {
    // アイコン名とプレフィックスを抽出
    let iconName = "";
    let prefix = "";
    let cssClass = "fas"; // デフォルトは solid

    if (icon.startsWith("fa-brands-")) {
      prefix = "brands";
      iconName = icon.replace("fa-brands-", "");
      cssClass = "fab";
    } else if (icon.startsWith("fa-regular-")) {
      prefix = "regular";
      iconName = icon.replace("fa-regular-", "");
      cssClass = "far";
    } else if (icon.startsWith("fa-light-")) {
      prefix = "light";
      iconName = icon.replace("fa-light-", "");
      cssClass = "fal";
    } else if (icon.startsWith("fa-duotone-")) {
      prefix = "duotone";
      iconName = icon.replace("fa-duotone-", "");
      cssClass = "fad";
    } else {
      // デフォルトは solid
      prefix = "solid";
      iconName = icon.replace("fa-", "");
      cssClass = "fas";
    }

    // 検索する可能性のあるキーのバリエーションを生成
    const possibleKeys = [
      `${prefix}-${iconName}`, // solid-trophy
      iconName, // trophy
      `${prefix}${iconName}`, // solidtrophy
      iconName.replace(/-/g, ""), // trophyからハイフンを取り除いたもの
    ];

    // brandsアイコンの場合の特別扱い
    if (prefix === "brands") {
      // brands-twitter => brands-twitter, twitter
      possibleKeys.push(iconName); // twitter
    }

    // solid以外の場合は、solid版も試す
    if (prefix !== "solid") {
      possibleKeys.push(`solid-${iconName}`);
      possibleKeys.push(`solid${iconName}`);
    }

    // プレフィックスに応じて適切なデータソースを選択
    let dataSource = null;
    if (prefix === "brands") {
      dataSource = fontAwesomeBrandsData;
    } else if (prefix === "regular") {
      dataSource = fontAwesomeOutlineData;
    } else {
      dataSource = fontAwesomeSolidData;
    }

    // すべてのキーを試してパスを見つける
    let svgPath = null;
    let foundKey = null;

    for (const key of possibleKeys) {
      if (dataSource[key]) {
        svgPath = dataSource[key];
        foundKey = key;
        break;
      }
    }

    // デバッグ用ログ
    // // console.log("FontAwesome icon search:", icon, "tried keys:", possibleKeys, "found:", foundKey);

    if (svgPath) {
      // fill属性にcolor引数を直接使用（currentColorだと親要素のcolor継承に依存するため）
      return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 512 512" fill="${color}" stroke="none" style="overflow: visible;">
        <path d="${svgPath}" />
      </svg>`;
    }

    // デバッグ情報をコンソールに出力
    // // console.log("FontAwesome icon not found:", icon, "Tried all keys but found nothing");

    // フォールバック: spanタグを使用（FontAwesome CSSが読み込まれていない場合は表示されない）
    return `<span class="${cssClass} fa-${iconName}" style="color:${color};font-size:24px;display:inline-block;"></span>`;
  }

  // Tabler Icons
  if (icon && icon.startsWith("tabler-")) {
    let iconName = "";
    let prefix = "";
    let iconData = null;

    if (icon.startsWith("tabler-solid-")) {
      prefix = "solid";
      iconName = icon.replace("tabler-solid-", "");
      iconData = tablerSolidData;
    } else if (icon.startsWith("tabler-outline-")) {
      prefix = "outline";
      iconName = icon.replace("tabler-outline-", "");
      iconData = tablerOutlineData;
    } else {
      // 旧形式との互換性のため
      prefix = "outline";
      iconName = icon.replace("tabler-", "");
      iconData = tablerOutlineData;
    }

    const iconContent = iconData[iconName];

    if (iconContent) {
      let processedContent = iconContent;

      // TablerアイコンのJSONデータは<path>タグを含まないパス文字列のみ
      // <path>タグが含まれているかチェック
      const hasPathTag = iconContent.includes("<path");

      if (!hasPathTag) {
        // <path>タグがない場合は、パス文字列をラップする
        if (prefix === "solid") {
          processedContent = `<path d="${iconContent}" fill="currentColor" stroke="none" />`;
        } else {
          processedContent = `<path d="${iconContent}" fill="none" stroke="currentColor" stroke-width="2" />`;
        }
      } else {
        // <path>タグがある場合は、既存の処理を実行
        if (prefix === "solid") {
          // solidの場合: fillを色に設定、strokeをnoneに
          processedContent = processedContent.replace(/fill="[^"]*"/g, `fill="currentColor"`);
          processedContent = processedContent.replace(/stroke="[^"]*"/g, 'stroke="none"');
          // fillが設定されていない場合は追加
          if (!processedContent.includes("fill=")) {
            processedContent = processedContent.replace(/<path/g, `<path fill="currentColor"`);
          }
        } else {
          // outlineの場合: strokeを色に設定、fillをnoneに
          processedContent = processedContent.replace(/stroke="[^"]*"/g, `stroke="currentColor"`);
          processedContent = processedContent.replace(/fill="[^"]*"/g, 'fill="none"');
          // strokeが設定されていない場合は追加
          if (!processedContent.includes("stroke=")) {
            processedContent = processedContent.replace(/<path/g, `<path stroke="currentColor"`);
          }
          // stroke-widthが設定されていない場合は追加（プレビュー用は2で固定）
          if (!processedContent.includes("stroke-width=")) {
            processedContent = processedContent.replace(/<path/g, '<path stroke-width="2"');
          }
        }
      }

      return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="${prefix === "solid" ? color : "none"}" stroke="${prefix === "solid" ? "none" : color}" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible;${prefix === "solid" ? "" : " fill: none !important;"}">
        ${processedContent}
      </svg>`;
    }

    // デフォルトのアイコンを返す
    return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
      <path d="${tablerOutlineData["question-mark"] || "M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 5.25h.008v.008H12v-.008Z"}" style="fill: none !important;" />
    </svg>`;
  }

  // Heroicons
  if (icon && icon.startsWith("heroicons-")) {
    // アイコン名とプレフィックスを抽出
    let iconName = "";
    let prefix = "";
    let iconData = null;

    if (icon.startsWith("heroicons-solid-")) {
      prefix = "solid";
      iconName = icon.replace("heroicons-solid-", "");
      iconData = heroiconsSolidData;
    } else if (icon.startsWith("heroicons-outline-")) {
      prefix = "outline";
      iconName = icon.replace("heroicons-outline-", "");
      iconData = heroiconsOutlineData;
    } else {
      // デフォルトはoutline
      prefix = "outline";
      iconName = icon.replace("heroicons-", "");
      iconData = heroiconsOutlineData;
    }

    // アイコンデータを取得
    const iconContent = iconData[iconName];

    // デバッグ用ログ
    // // console.log("Heroicons icon search:", icon, "iconName:", iconName, "found:", !!iconContent);

    if (iconContent) {
      // Lucideと同様の処理で、SVG要素を含む形式に対応
      let processedContent = iconContent;

      // solidタイプの場合は塗りつぶしあり、線なし
      // outlineタイプの場合は塗りつぶしなし、線あり
      if (prefix === "solid") {
        // solidの場合: fillを色に設定、strokeをnoneに
        processedContent = processedContent.replace(/fill="[^"]*"/g, `fill="currentColor"`);
        processedContent = processedContent.replace(/stroke="[^"]*"/g, 'stroke="none"');
        // fillが設定されていない場合は追加
        if (!processedContent.includes("fill=")) {
          processedContent = processedContent.replace(/<path/g, `<path fill="currentColor"`);
        }
      } else {
        // outlineの場合: strokeを色に設定、fillをnoneに
        processedContent = processedContent.replace(/stroke="[^"]*"/g, `stroke="currentColor"`);
        processedContent = processedContent.replace(/fill="[^"]*"/g, 'fill="none"');
        // strokeが設定されていない場合は追加
        if (!processedContent.includes("stroke=")) {
          processedContent = processedContent.replace(/<path/g, `<path stroke="currentColor"`);
        }
        // stroke-widthが設定されていない場合は追加
        if (!processedContent.includes("stroke-width=")) {
          processedContent = processedContent.replace(/<path/g, '<path stroke-width="1.0"');
        } else {
          // 既存のstroke-widthを置き換え
          processedContent = processedContent.replace(/stroke-width="[^"]*"/g, 'stroke-width="1.0"');
        }
      }

      return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="${prefix === "solid" ? color : "none"}" stroke="${prefix === "solid" ? "none" : color}" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible;${prefix === "solid" ? "" : " fill: none !important;"}">
        ${processedContent}
      </svg>`;
    }

    // デフォルトのアイコンを返す
    return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
      <path d="${tablerOutlineData["question-mark"] || "M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 5.25h.008v.008H12v-.008Z"}" style="fill: none !important;" />
    </svg>`;
  }

  // RemixIcon
  if (icon && icon.startsWith("remixicon-")) {
    // アイコン名とプレフィックスを抽出
    let iconName = "";
    let prefix = "";
    let iconData = null;

    if (icon.startsWith("remixicon-solid-")) {
      prefix = "solid";
      iconName = icon.replace("remixicon-solid-", "");
      iconData = remixiconSolidData;
    } else if (icon.startsWith("remixicon-outline-")) {
      prefix = "outline";
      iconName = icon.replace("remixicon-outline-", "");
      iconData = remixiconOutlineData;
    } else {
      // デフォルトはoutline
      prefix = "outline";
      iconName = icon.replace("remixicon-", "");
      iconData = remixiconOutlineData;
    }

    // アイコンデータを取得
    const iconContent = iconData[iconName];

    if (iconContent) {
      // RemixIconは他のアイコンライブラリと異なり、solidとoutlineの両方でfill属性を使用
      let processedContent = iconContent;

      // RemixIconの場合：solidとoutlineの両方でfill属性を使用
      // solidの場合は塗りつぶし、outlineの場合も細い線の塗りつぶし
      // color引数を直接使用（currentColorだと親要素のcolor継承に依存するため）
      processedContent = processedContent.replace(/fill="[^"]*"/g, `fill="${color}"`);
      processedContent = processedContent.replace(/stroke="[^"]*"/g, 'stroke="none"');
      // fillが設定されていない場合は追加
      if (!processedContent.includes("fill=")) {
        processedContent = processedContent.replace(/<path/g, `<path fill="${color}"`);
      }

      return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="${color}" stroke="none" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible;">
        ${processedContent}
      </svg>`;
    }

    // デフォルトのアイコンを返す
    return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="${color}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
      <path d="${tablerOutlineData["question-mark"] || "M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 5.25h.008v.008H12v-.008Z"}" style="fill: none !important;" />
    </svg>`;
  }

  // Lucide Icons
  if (icon && icon.startsWith("lucide-")) {
    const iconName = icon.replace("lucide-", "");
    if (lucideData[iconName]) {
      const iconContent = lucideData[iconName];
      // Check if the content is SVG format (starts with <path, <circle, <rect, etc.) or old path format
      if (iconContent.includes("<")) {
        // New SVG format - use the SVG content directly and replace currentColor
        let processedContent = iconContent.replace(/stroke="currentColor"/g, `stroke="currentColor"`).replace(/fill="currentColor"/g, 'fill="none"'); // Force fill="none" for line icons

        // First, remove ALL existing stroke-width attributes to ensure consistency
        processedContent = processedContent.replace(/stroke-width="[^"]*"/g, "");

        // Process all SVG elements to ensure proper attributes and self-closing tags
        processedContent = processedContent.replace(/<(path|circle|rect|line|polyline|polygon|ellipse)([^>]*?)\s*\/?>/g, (match, tagName, attributes) => {
          let newAttributes = attributes;

          // Force fill="none" for all path and circle elements
          if (["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"].includes(tagName)) {
            // Remove existing fill attribute first
            newAttributes = newAttributes.replace(/fill="[^"]*"/g, "");
            // Add fill="none"
            newAttributes += ' fill="none"';
          }

          // Add stroke if not present (for elements that typically have stroke)
          if (!newAttributes.includes("stroke=") && ["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"].includes(tagName)) {
            newAttributes += ` stroke="currentColor"`;
          }

          // Add consistent stroke-width for all stroke elements (for selector display)
          if (["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"].includes(tagName)) {
            newAttributes += ' stroke-width="1.0"';
          }

          return `<${tagName}${newAttributes} />`;
        });

        return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
        ${processedContent}
      </svg>`;
      } else {
        // Old path format - wrap in a single path element
        return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.0" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
        <path d="${iconContent}" fill="none" />
      </svg>`;
      }
    }

    // デフォルトのアイコンを返す
    return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.0" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
    <path d="${tablerIconsData["question-mark"] || "M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 5.25h.008v.008H12v-.008Z"}" style="fill: none !important;" />
  </svg>`;
  }

  // カスタムSVG
  if (icon && icon.startsWith("custom-svg-")) {
    const svgContent = icon.replace("custom-svg-", "");
    if (svgContent) {
      try {
        // Unicode対応のBase64デコードでSVGを取得
        let customSvg = decodeBase64Unicode(svgContent);

        // SVGが正常かチェック
        if (!customSvg.includes("<svg") || !customSvg.includes("</svg>")) {
          throw new Error("Invalid SVG structure");
        }

        // DOM Parserを使用してSVGを解析・処理（プレビュー用）
        if (typeof DOMParser !== "undefined" && typeof XMLSerializer !== "undefined") {
          try {
            const parser = new DOMParser();
            const svgDoc = parser.parseFromString(customSvg, "image/svg+xml");
            const parserError = svgDoc.querySelector("parsererror");

            if (!parserError) {
              const svg = svgDoc.querySelector("svg");
              if (svg) {
                // SVGのfill属性を確認
                const svgFill = svg.getAttribute("fill");
                const shouldBeFillNone = svgFill === "none" || svgFill === null;

                // すべてのグラフィック要素にfillとstroke属性を適切に設定
                const graphicElements = svgDoc.querySelectorAll("path, circle, rect, ellipse, line, polyline, polygon");
                graphicElements.forEach((element) => {
                  // fill属性の処理
                  const currentFill = element.getAttribute("fill");
                  if (currentFill === "currentColor") {
                    element.setAttribute("fill", color);
                  } else if (!currentFill && shouldBeFillNone) {
                    // 親のSVGがfill="none"の場合、子要素にも明示的にfill="none"を設定
                    element.setAttribute("fill", "none");
                  }

                  // stroke属性の処理
                  const currentStroke = element.getAttribute("stroke");
                  if (currentStroke === "currentColor") {
                    element.setAttribute("stroke", color);
                  } else if (currentStroke && currentStroke !== "none") {
                    element.setAttribute("stroke", color);
                  }

                  // stroke-width属性の処理（プレビュー用は固定値）
                  if (currentStroke && currentStroke !== "none") {
                    // strokeがある要素にはstroke-widthを設定（プレビュー用は1.75で固定）
                    element.setAttribute("stroke-width", "1.75");
                  }
                });

                // SVG要素の属性を処理
                if (svg.getAttribute("stroke") === "currentColor") {
                  svg.setAttribute("stroke", color);
                }
                if (svg.getAttribute("fill") === "currentColor") {
                  svg.setAttribute("fill", color);
                }

                // プレビュー用にSVGサイズを制限
                svg.setAttribute("width", "16");
                svg.setAttribute("height", "16");

                // overflowスタイルを追加
                const existingStyle = svg.getAttribute("style") || "";
                const newStyle = existingStyle + (existingStyle ? "; " : "") + "overflow: visible; max-width: 16px; max-height: 16px; object-fit: contain;";
                svg.setAttribute("style", newStyle);

                const serializer = new XMLSerializer();
                customSvg = serializer.serializeToString(svgDoc);
              }
            }
          } catch (domError) {
            // console.warn("DOM parsing failed for preview, using fallback processing:", domError);
            // フォールバック処理
            customSvg = customSvg.replace(/stroke="currentColor"/g, `stroke="currentColor"`);
            customSvg = customSvg.replace(/fill="currentColor"/g, `fill="currentColor"`);
            customSvg = customSvg.replace(/stroke="((?!none)[^"]*)"/g, `stroke="currentColor"`);

            // プレビュー用にSVGサイズを制限
            customSvg = customSvg.replace(/width="[^"]*"/g, 'width="16"');
            customSvg = customSvg.replace(/height="[^"]*"/g, 'height="16"');

            // overflowスタイルを追加
            customSvg = customSvg.replace(/<svg([^>]*)>/i, '<svg$1 style="overflow: visible; max-width: 16px; max-height: 16px; object-fit: contain;">');
          }
        }

        // viewBoxを自動調整（ブラウザ環境でのみ実行）
        if (typeof document !== "undefined") {
          try {
            customSvg = adjustViewBoxToPath(customSvg);
          } catch (adjustError) {
            // console.warn("ViewBox adjustment failed, using original SVG:", adjustError);
          }
        }

        return customSvg;
      } catch (e) {
        // console.error("カスタムSVGのレンダリングエラー:", e);
        return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
          <path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3Z" style="fill: none !important;" />
        </svg>`;
      }
    }
  }

  return "";
};

/**
 * アイコンをカラー付きで描画する関数
 * @param {string} icon - アイコン識別子
 * @param {string} color - アイコンの色
 * @param {number} strokeWidth - ストローク幅
 * @returns {string} SVG文字列
 */
export const renderSVGIcon = (icon, color = "#FFFFFF", strokeWidth = 1.75) => {
  // Use currentColor for CSS control - color parameter is now ignored for stroke/fill
  const useCurrentColor = true;
  const strokeColor = useCurrentColor ? "currentColor" : color;

  // Feather Icons
  if (icon && icon.startsWith("feather-")) {
    const iconName = icon.replace("feather-", "");
    if (featherIconsData[iconName]) {
      const iconContent = featherIconsData[iconName];
      // Check if the content is SVG format (contains SVG elements) or old path format
      if (iconContent.includes("<")) {
        // New SVG format - use the SVG content directly and replace currentColor
        let processedContent = iconContent.replace(/stroke="currentColor"/g, `stroke="${strokeColor}"`).replace(/fill="currentColor"/g, 'fill="none"');

        // Process all SVG elements to ensure proper attributes and self-closing tags
        processedContent = processedContent.replace(/<(path|circle|rect|line|polyline|polygon|ellipse)([^>]*?)\s*\/?>/g, (match, tagName, attributes) => {
          let newAttributes = attributes;

          // Force fill="none" for all path and circle elements
          if (["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"].includes(tagName)) {
            // Remove existing fill attribute first
            newAttributes = newAttributes.replace(/fill="[^"]*"/g, "");
            // Add fill="none"
            newAttributes += ' fill="none"';
          }

          // Add stroke if not present (for elements that typically have stroke)
          if (!newAttributes.includes("stroke=") && ["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"].includes(tagName)) {
            newAttributes += ` stroke="${strokeColor}"`;
          } else {
            // Replace existing stroke with currentColor
            newAttributes = newAttributes.replace(/stroke="[^"]*"/g, `stroke="${strokeColor}"`);
          }

          // Update or add stroke-width for all stroke elements
          if (["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"].includes(tagName)) {
            // Remove existing stroke-width attribute
            newAttributes = newAttributes.replace(/stroke-width="[^"]*"/g, "");
            // Add the new stroke-width
            newAttributes += ` stroke-width="${strokeWidth}"`;
          }

          return `<${tagName}${newAttributes} />`;
        });

        return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
        ${processedContent}
      </svg>`;
      } else {
        // Old path format - wrap in a single path element
        return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="${strokeColor}" stroke-width="${strokeWidth}" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
        <path d="${iconContent}" fill="none" />
      </svg>`;
      }
    }
  }

  // Font Awesome
  if (icon && icon.startsWith("fa-")) {
    // アイコン名とプレフィックスを抽出
    let iconName = "";
    let prefix = "";
    let cssClass = "fas"; // デフォルトは solid

    if (icon.startsWith("fa-brands-")) {
      prefix = "brands";
      iconName = icon.replace("fa-brands-", "");
      cssClass = "fab";
    } else if (icon.startsWith("fa-regular-")) {
      prefix = "regular";
      iconName = icon.replace("fa-regular-", "");
      cssClass = "far";
    } else if (icon.startsWith("fa-light-")) {
      prefix = "light";
      iconName = icon.replace("fa-light-", "");
      cssClass = "fal";
    } else if (icon.startsWith("fa-duotone-")) {
      prefix = "duotone";
      iconName = icon.replace("fa-duotone-", "");
      cssClass = "fad";
    } else {
      // デフォルトは solid
      prefix = "solid";
      iconName = icon.replace("fa-", "");
      cssClass = "fas";
    }

    // 検索する可能性のあるキーのバリエーションを生成
    const possibleKeys = [
      `${prefix}-${iconName}`, // solid-trophy
      iconName, // trophy
      `${prefix}${iconName}`, // solidtrophy
      iconName.replace(/-/g, ""), // trophyからハイフンを取り除いたもの
    ];

    // brandsアイコンの場合の特別扱い
    if (prefix === "brands") {
      // brands-twitter => brands-twitter, twitter
      possibleKeys.push(iconName); // twitter
    }

    // solid以外の場合は、solid版も試す
    if (prefix !== "solid") {
      possibleKeys.push(`solid-${iconName}`);
      possibleKeys.push(`solid${iconName}`);
    }

    // プレフィックスに応じて適切なデータソースを選択
    let dataSource = null;
    if (prefix === "brands") {
      dataSource = fontAwesomeBrandsData;
    } else if (prefix === "regular") {
      dataSource = fontAwesomeOutlineData;
    } else {
      dataSource = fontAwesomeSolidData;
    }

    // すべてのキーを試してパスを見つける
    let svgPath = null;
    let foundKey = null;

    for (const key of possibleKeys) {
      if (dataSource[key]) {
        svgPath = dataSource[key];
        foundKey = key;
        break;
      }
    }

    if (svgPath) {
      return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 512 512" fill="currentColor" stroke="none" style="overflow: visible;">
        <path d="${svgPath}" />
      </svg>`;
    }

    // フォールバック: spanタグを使用
    return `<span class="${cssClass} fa-${iconName}" style="color:currentColor;font-size:24px;display:inline-block;"></span>`;
  }

  // Tabler Icons
  if (icon && icon.startsWith("tabler-")) {
    let iconName = "";
    let prefix = "";
    let iconData = null;

    if (icon.startsWith("tabler-solid-")) {
      prefix = "solid";
      iconName = icon.replace("tabler-solid-", "");
      iconData = tablerSolidData;
    } else if (icon.startsWith("tabler-outline-")) {
      prefix = "outline";
      iconName = icon.replace("tabler-outline-", "");
      iconData = tablerOutlineData;
    } else {
      // 旧形式との互換性のため
      prefix = "outline";
      iconName = icon.replace("tabler-", "");
      iconData = tablerOutlineData;
    }

    const iconContent = iconData[iconName];

    if (iconContent) {
      let processedContent = iconContent;

      // TablerアイコンのJSONデータは<path>タグを含まないパス文字列のみ
      // <path>タグが含まれているかチェック
      const hasPathTag = iconContent.includes("<path");

      if (!hasPathTag) {
        // <path>タグがない場合は、パス文字列をラップする
        if (prefix === "solid") {
          processedContent = `<path d="${iconContent}" fill="currentColor" stroke="none" />`;
        } else {
          processedContent = `<path d="${iconContent}" fill="none" stroke="currentColor" stroke-width="${strokeWidth}" />`;
        }
      } else {
        // <path>タグがある場合は、既存の処理を実行
        if (prefix === "solid") {
          // solidの場合: fillを色に設定、strokeをnoneに
          processedContent = processedContent.replace(/fill="[^"]*"/g, 'fill="currentColor"');
          processedContent = processedContent.replace(/stroke="[^"]*"/g, 'stroke="none"');
          // fillが設定されていない場合は追加
          if (!processedContent.includes("fill=")) {
            processedContent = processedContent.replace(/<path/g, '<path fill="currentColor"');
          }
        } else {
          // outlineの場合: strokeを色に設定、fillをnoneに、stroke-widthを調整
          processedContent = processedContent.replace(/stroke="[^"]*"/g, 'stroke="currentColor"');
          processedContent = processedContent.replace(/fill="[^"]*"/g, 'fill="none"');
          // strokeが設定されていない場合は追加
          if (!processedContent.includes("stroke=")) {
            processedContent = processedContent.replace(/<path/g, '<path stroke="currentColor"');
          }
          // stroke-widthが設定されていない場合は追加
          if (!processedContent.includes("stroke-width=")) {
            processedContent = processedContent.replace(/<path/g, `<path stroke-width="${strokeWidth}"`);
          } else {
            // 既存のstroke-widthを置き換え
            processedContent = processedContent.replace(/stroke-width="[^"]*"/g, `stroke-width="${strokeWidth}"`);
          }
        }
      }

      return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="${prefix === "solid" ? "currentColor" : "none"}" stroke="${prefix === "solid" ? "none" : "currentColor"}" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible;${prefix === "solid" ? "" : " fill: none !important;"}">
        ${processedContent}
      </svg>`;
    }

    // デフォルトのアイコンを返す
    return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${strokeWidth}" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
      <path d="${tablerOutlineData["question-mark"] || "M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 5.25h.008v.008H12v-.008Z"}" style="fill: none !important;" />
    </svg>`;
  }

  // Heroicons
  if (icon && icon.startsWith("heroicons-")) {
    // アイコン名とプレフィックスを抽出
    let iconName = "";
    let prefix = "";

    if (icon.startsWith("heroicons-solid-")) {
      prefix = "solid";
      iconName = icon.replace("heroicons-solid-", "");
    } else if (icon.startsWith("heroicons-outline-")) {
      prefix = "outline";
      iconName = icon.replace("heroicons-outline-", "");
    } else {
      // デフォルトはoutline
      prefix = "outline";
      iconName = icon.replace("heroicons-", "");
    }

    // 検索する可能性のあるキーのバリエーションを生成
    const possibleKeys = [`${prefix}-${iconName}`, iconName];

    // すべてのキーを試してパスを見つける
    let svgPath = null;
    let foundKey = null;

    // 新しいデータ構造に対応
    let iconData = null;
    if (prefix === "solid") {
      iconData = heroiconsSolidData;
    } else {
      iconData = heroiconsOutlineData;
    }

    const iconContent = iconData[iconName];
    if (iconContent) {
      svgPath = iconContent;
      foundKey = iconName;
    }

    if (svgPath) {
      // Lucideと同様の処理で、SVG要素を含む形式に対応
      let processedContent = svgPath;

      // solidタイプの場合は塗りつぶしあり、線なし
      // outlineタイプの場合は塗りつぶしなし、線あり
      if (prefix === "solid") {
        // solidの場合: fillを色に設定、strokeをnoneに
        processedContent = processedContent.replace(/fill="[^"]*"/g, 'fill="currentColor"');
        processedContent = processedContent.replace(/stroke="[^"]*"/g, 'stroke="none"');
        // fillが設定されていない場合は追加
        if (!processedContent.includes("fill=")) {
          processedContent = processedContent.replace(/<path/g, '<path fill="currentColor"');
        }
      } else {
        // outlineの場合: strokeを色に設定、fillをnoneに、stroke-widthを調整
        processedContent = processedContent.replace(/stroke="[^"]*"/g, 'stroke="currentColor"');
        processedContent = processedContent.replace(/fill="[^"]*"/g, 'fill="none"');
        // strokeが設定されていない場合は追加
        if (!processedContent.includes("stroke=")) {
          processedContent = processedContent.replace(/<path/g, '<path stroke="currentColor"');
        }
        // stroke-widthが設定されていない場合は追加
        if (!processedContent.includes("stroke-width=")) {
          processedContent = processedContent.replace(/<path/g, `<path stroke-width="${strokeWidth}"`);
        } else {
          // 既存のstroke-widthを置き換え
          processedContent = processedContent.replace(/stroke-width="[^"]*"/g, `stroke-width="${strokeWidth}"`);
        }
      }

      return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="${prefix === "solid" ? "currentColor" : "none"}" stroke="${prefix === "solid" ? "none" : "currentColor"}" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible;${prefix === "solid" ? "" : " fill: none !important;"}">
        ${processedContent}
      </svg>`;
    }

    // デフォルトのアイコンを返す
    return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
      <path d="${tablerOutlineData["question-mark"] || "M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 5.25h.008v.008H12v-.008Z"}" style="fill: none !important;" />
    </svg>`;
  }

  // RemixIcon
  if (icon && icon.startsWith("remixicon-")) {
    // アイコン名とプレフィックスを抽出
    let iconName = "";
    let prefix = "";
    let iconData = null;

    if (icon.startsWith("remixicon-solid-")) {
      prefix = "solid";
      iconName = icon.replace("remixicon-solid-", "");
      iconData = remixiconSolidData;
    } else if (icon.startsWith("remixicon-outline-")) {
      prefix = "outline";
      iconName = icon.replace("remixicon-outline-", "");
      iconData = remixiconOutlineData;
    } else {
      // デフォルトはoutline
      prefix = "outline";
      iconName = icon.replace("remixicon-", "");
      iconData = remixiconOutlineData;
    }

    // アイコンデータを取得
    const iconContent = iconData[iconName];

    if (iconContent) {
      // RemixIconは他のアイコンライブラリと異なり、solidとoutlineの両方でfill属性を使用
      let processedContent = iconContent;

      // RemixIconの場合：solidとoutlineの両方でfill属性を使用
      // solidの場合は塗りつぶし、outlineの場合も細い線の塗りつぶし
      processedContent = processedContent.replace(/fill="[^"]*"/g, `fill="currentColor"`);
      processedContent = processedContent.replace(/stroke="[^"]*"/g, 'stroke="none"');
      // fillが設定されていない場合は追加
      if (!processedContent.includes("fill=")) {
        processedContent = processedContent.replace(/<path/g, `<path fill="currentColor"`);
      }

      return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor" stroke="none" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible;">
        ${processedContent}
      </svg>`;
    }

    // デフォルトのアイコンを返す
    return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${strokeWidth}" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
      <path d="${tablerOutlineData["question-mark"] || "M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 5.25h.008v.008H12v-.008Z"}" style="fill: none !important;" />
    </svg>`;
  }

  // Lucide Icons
  if (icon && icon.startsWith("lucide-")) {
    const iconName = icon.replace("lucide-", "");
    if (lucideData[iconName]) {
      const iconContent = lucideData[iconName];
      // Check if the content is SVG format (starts with <path, <circle, <rect, etc.) or old path format
      if (iconContent.includes("<")) {
        // New SVG format - use the SVG content directly and replace currentColor
        let processedContent = iconContent.replace(/stroke="currentColor"/g, `stroke="currentColor"`).replace(/fill="currentColor"/g, 'fill="none"'); // Force fill="none" for line icons

        // Process all SVG elements to ensure proper attributes and self-closing tags
        processedContent = processedContent.replace(/<(path|circle|rect|line|polyline|polygon|ellipse)([^>]*?)\s*\/?>/g, (match, tagName, attributes) => {
          let newAttributes = attributes;

          // Force fill="none" for all path and circle elements
          if (["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"].includes(tagName)) {
            // Remove existing fill attribute first
            newAttributes = newAttributes.replace(/fill="[^"]*"/g, "");
            // Add fill="none"
            newAttributes += ' fill="none"';
          }

          // Add stroke if not present (for elements that typically have stroke)
          if (!newAttributes.includes("stroke=") && ["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"].includes(tagName)) {
            newAttributes += ` stroke="currentColor"`;
          }

          // Update or add stroke-width for all stroke elements
          if (["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"].includes(tagName)) {
            // Remove existing stroke-width attribute
            newAttributes = newAttributes.replace(/stroke-width="[^"]*"/g, "");
            // Add the new stroke-width
            newAttributes += ` stroke-width="${strokeWidth}"`;
          }

          return `<${tagName}${newAttributes} />`;
        });

        return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
        ${processedContent}
      </svg>`;
      } else {
        // Old path format - wrap in a single path element
        return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${strokeWidth}" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
        <path d="${iconContent}" fill="none" />
      </svg>`;
      }
    }

    // デフォルトのアイコンを返す
    return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="${strokeWidth}" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
    <path d="${tablerIconsData["question-mark"] || "M9.879 7.519c1.171-1.025 3.071-1.025 4.242 0 1.172 1.025 1.172 2.687 0 3.712-.203.179-.43.326-.67.442-.745.361-1.45.999-1.45 1.827v.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9 5.25h.008v.008H12v-.008Z"}" style="fill: none !important;" />
  </svg>`;
  }

  // カスタムSVG
  if (icon && icon.startsWith("custom-svg-")) {
    const svgContent = icon.replace("custom-svg-", "");
    if (svgContent) {
      try {
        // Unicode対応のBase64デコードでSVGを取得
        let customSvg = decodeBase64Unicode(svgContent);

        // // console.log("🔍 カスタムSVG処理開始:", {
        //   icon: icon,
        //   originalSVG: customSvg.substring(0, 200) + "...",
        //   targetColor: color,
        //   strokeWidth: strokeWidth,
        //   strokeWidthType: typeof strokeWidth
        // });

        // SVGが正常かチェック
        if (!customSvg.includes("<svg") || !customSvg.includes("</svg>")) {
          throw new Error("Invalid SVG structure");
        }

        // DOM Parserを使用してSVGを解析・処理
        if (typeof DOMParser !== "undefined" && typeof XMLSerializer !== "undefined") {
          try {
            const parser = new DOMParser();
            const svgDoc = parser.parseFromString(customSvg, "image/svg+xml");
            const parserError = svgDoc.querySelector("parsererror");

            if (!parserError) {
              const svg = svgDoc.querySelector("svg");
              if (svg) {
                // // console.log("📝 DOM Parser処理開始");

                // SVGのfill属性を確認
                const svgFill = svg.getAttribute("fill");
                const shouldBeFillNone = svgFill === "none" || svgFill === null;

                // すべてのグラフィック要素にfillとstroke属性を適切に設定
                const graphicElements = svgDoc.querySelectorAll("path, circle, rect, ellipse, line, polyline, polygon");

                // // console.log("🎯 処理対象要素数:", graphicElements.length);

                graphicElements.forEach((element, index) => {
                  const originalStroke = element.getAttribute("stroke");
                  const originalFill = element.getAttribute("fill");

                  // // console.log(`🔧 要素${index + 1}処理前:`, {
                  //   tag: element.tagName,
                  //   originalStroke,
                  //   originalFill
                  // });

                  // fill属性の処理
                  const currentFill = element.getAttribute("fill");
                  if (currentFill === "currentColor") {
                    element.setAttribute("fill", color);
                    // // console.log(`✅ fill currentColor → ${color}`);
                  } else if (!currentFill && shouldBeFillNone) {
                    // 親のSVGがfill="none"の場合、子要素にも明示的にfill="none"を設定
                    element.setAttribute("fill", "none");
                  }

                  // stroke属性の処理
                  const currentStroke = element.getAttribute("stroke");
                  if (currentStroke === "currentColor") {
                    element.setAttribute("stroke", color);
                    // // console.log(`✅ stroke currentColor → ${color}`);
                  } else if (currentStroke && currentStroke !== "none") {
                    // 具体的な色（#000000等）も変更対象にする
                    element.setAttribute("stroke", color);
                    // // console.log(`✅ stroke ${currentStroke} → ${color}`);
                  } else {
                    // strokeが未設定の場合、親のSVGのstrokeを継承する
                    const parentStroke = svg.getAttribute("stroke");
                    if (parentStroke && parentStroke !== "none") {
                      element.setAttribute("stroke", color);
                      // // console.log(`✅ stroke inherited from parent → ${color}`);
                    }
                  }

                  // stroke-width属性の処理（改善版）
                  // カスタムアイコンでは、stroke属性の有無に関わらずstroke-widthを設定可能にする
                  const hasStroke = currentStroke && currentStroke !== "none";
                  const hasStrokeWidth = element.getAttribute("stroke-width");
                  const finalStroke = element.getAttribute("stroke"); // 更新後のstrokeを取得

                  // // console.log(`📝 stroke-width処理情報:`, {
                  //   elementTag: element.tagName,
                  //   hasStroke,
                  //   hasStrokeWidth,
                  //   finalStroke,
                  //   strokeWidthParam: strokeWidth,
                  //   strokeWidthType: typeof strokeWidth,
                  // });

                  if (strokeWidth && strokeWidth > 0) {
                    // stroke-widthが指定されている場合
                    if (finalStroke && finalStroke !== "none") {
                      // strokeがある要素には直接設定
                      element.setAttribute("stroke-width", strokeWidth.toString());
                      // // console.log(`🎨 stroke-width 設定: ${strokeWidth}`);
                    } else {
                      // strokeがないfill onlyのアイコンの場合、strokeを追加してstroke-widthを設定
                      const currentFillAfter = element.getAttribute("fill");
                      if (currentFillAfter !== "none" && currentFillAfter) {
                        // fill onlyのアイコンにもstroke-widthのみ設定（outline効果用）
                        element.setAttribute("stroke-width", strokeWidth.toString());
                        // // console.log(`🎨 fill-only要素にstroke-width 設定: ${strokeWidth}`);
                      }
                    }
                  } else if (finalStroke && finalStroke !== "none" && !hasStrokeWidth) {
                    // strokeがあるがstroke-widthが未設定の場合はデフォルト値を設定
                    element.setAttribute("stroke-width", "1.75");
                    // // console.log(`🎨 デフォルトstroke-width 設定: 1.75`);
                  }

                  // // console.log(`🔧 要素${index + 1}処理後:`, {
                  //   tag: element.tagName,
                  //   stroke: element.getAttribute("stroke"),
                  //   fill: element.getAttribute("fill"),
                  //   strokeWidth: element.getAttribute("stroke-width"),
                  // });
                });

                // SVG要素の属性を処理
                const svgStroke = svg.getAttribute("stroke");
                const svgFillAttr = svg.getAttribute("fill");

                // console.log("🏷️ SVG要素の属性処理前:", {
                //   stroke: svgStroke,
                //   fill: svgFillAttr,
                //   strokeWidthParam: strokeWidth,
                // });

                if (svg.getAttribute("stroke") === "currentColor") {
                  svg.setAttribute("stroke", color);
                  // console.log(`✅ SVG stroke currentColor → ${color}`);
                } else if (svgStroke && svgStroke !== "none") {
                  // SVG要素の具体的な色（#000000等）も変更対象にする
                  svg.setAttribute("stroke", color);
                  // console.log(`✅ SVG stroke ${svgStroke} → ${color}`);
                }
                if (svg.getAttribute("fill") === "currentColor") {
                  svg.setAttribute("fill", color);
                  // console.log(`✅ SVG fill currentColor → ${color}`);
                } else if (svgFillAttr && svgFillAttr !== "none") {
                  // SVG要素の具体的な色も変更対象にする
                  svg.setAttribute("fill", color);
                  // console.log(`✅ SVG fill ${svgFillAttr} → ${color}`);
                }

                // SVG要素のstroke-width処理
                if (strokeWidth && strokeWidth > 0) {
                  const svgStrokeAfter = svg.getAttribute("stroke");
                  if (svgStrokeAfter && svgStrokeAfter !== "none") {
                    svg.setAttribute("stroke-width", strokeWidth.toString());
                    // console.log(`🎨 SVG stroke-width 設定: ${strokeWidth}`);
                  }
                }

                // overflowスタイルを追加
                const existingStyle = svg.getAttribute("style") || "";
                const newStyle = existingStyle + (existingStyle ? "; " : "") + "overflow: visible;";
                svg.setAttribute("style", newStyle);

                const serializer = new XMLSerializer();
                customSvg = serializer.serializeToString(svgDoc);

                // console.log("✨ 最終的なSVG:", customSvg);
              }
            }
          } catch (domError) {
            // console.warn("DOM parsing failed, using fallback processing:", domError);
            // フォールバック処理
            // console.log("🔄 フォールバック処理開始");
            const originalSvg = customSvg;

            // currentColorを置き換え
            customSvg = customSvg.replace(/stroke="currentColor"/g, `stroke="currentColor"`);
            customSvg = customSvg.replace(/fill="currentColor"/g, `fill="currentColor"`);

            // 具体的な色（#000000等）も置き換える
            customSvg = customSvg.replace(/stroke="#[0-9a-fA-F]{3,6}"/g, `stroke="currentColor"`);
            customSvg = customSvg.replace(/fill="#[0-9a-fA-F]{3,6}"/g, `fill="currentColor"`);

            // 色名（red, blue等）も置き換える（noneとtransparent以外）
            customSvg = customSvg.replace(/stroke="(?!none|transparent)[a-zA-Z]+"/g, `stroke="currentColor"`);
            customSvg = customSvg.replace(/fill="(?!none|transparent)[a-zA-Z]+"/g, `fill="currentColor"`);

            // console.log("🔄 フォールバック結果:", {
            //   before: originalSvg,
            //   after: customSvg,
            // });

            // stroke-widthを調整（改善版）
            if (strokeWidth) {
              // 既存のstroke-widthを置き換え
              customSvg = customSvg.replace(/stroke-width="[^"]*"/g, `stroke-width="${strokeWidth}"`);

              // stroke属性を持つ要素でstroke-widthがない場合、追加
              customSvg = customSvg.replace(/(<(?:path|circle|rect|ellipse|line|polyline|polygon)[^>]*stroke="[^"]+"[^>]*?)(?!.*stroke-width)>/g, `$1 stroke-width="${strokeWidth}">`);

              // fillのみの要素にもstroke-widthを追加（outline効果用）
              customSvg = customSvg.replace(/(<(?:path|circle|rect|ellipse|line|polyline|polygon)[^>]*fill="(?!none)[^"]+"[^>]*?)(?!.*stroke-width)>/g, `$1 stroke-width="${strokeWidth}">`);
            }

            // overflowスタイルを追加
            customSvg = customSvg.replace(/<svg([^>]*)>/i, '<svg$1 style="overflow: visible;">');
          }
        } else {
          // DOM Parserが利用できない場合のフォールバック
          // console.log("⚠️ DOM Parser利用不可、フォールバック処理");

          // currentColorを置き換え
          customSvg = customSvg.replace(/stroke="currentColor"/g, `stroke="currentColor"`);
          customSvg = customSvg.replace(/fill="currentColor"/g, `fill="currentColor"`);

          // 具体的な色（#000000等）も置き換える
          customSvg = customSvg.replace(/stroke="#[0-9a-fA-F]{3,6}"/g, `stroke="currentColor"`);
          customSvg = customSvg.replace(/fill="#[0-9a-fA-F]{3,6}"/g, `fill="currentColor"`);

          // 色名（red, blue等）も置き換える（noneとtransparent以外）
          customSvg = customSvg.replace(/stroke="(?!none|transparent)[a-zA-Z]+"/g, `stroke="currentColor"`);
          customSvg = customSvg.replace(/fill="(?!none|transparent)[a-zA-Z]+"/g, `fill="currentColor"`);

          // stroke-widthを調整（改善版）
          if (strokeWidth) {
            // 既存のstroke-widthを置き換え
            customSvg = customSvg.replace(/stroke-width="[^"]*"/g, `stroke-width="${strokeWidth}"`);

            // stroke属性を持つ要素でstroke-widthがない場合、追加
            customSvg = customSvg.replace(/(<(?:path|circle|rect|ellipse|line|polyline|polygon)[^>]*stroke="[^"]+"[^>]*?)(?!.*stroke-width)>/g, `$1 stroke-width="${strokeWidth}">`);

            // fillのみの要素にもstroke-widthを追加（outline効果用）
            customSvg = customSvg.replace(/(<(?:path|circle|rect|ellipse|line|polyline|polygon)[^>]*fill="(?!none)[^"]+"[^>]*?)(?!.*stroke-width)>/g, `$1 stroke-width="${strokeWidth}">`);
          }

          // overflowスタイルを追加
          customSvg = customSvg.replace(/<svg([^>]*)>/i, '<svg$1 style="overflow: visible;">');
        }

        // viewBoxを自動調整（ブラウザ環境でのみ実行）
        if (typeof document !== "undefined") {
          try {
            customSvg = adjustViewBoxToPath(customSvg);
          } catch (adjustError) {
            // console.warn("ViewBox adjustment failed, using original SVG:", adjustError);
          }
        }

        // console.log("🎉 カスタムSVG処理完了:", {
        //   icon: icon,
        //   finalSVG: customSvg.substring(0, 300) + "...",
        //   strokeWidthInFinalSVG: customSvg.includes("stroke-width") ? customSvg.match(/stroke-width="([^"]*)"/g) : "No stroke-width found",
        //   appliedStrokeWidth: strokeWidth,
        // });
        return customSvg;
      } catch (e) {
        // console.error("カスタムSVGのレンダリングエラー:", e);
        return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="overflow: visible; fill: none !important;">
          <path d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3Z" style="fill: none !important;" />
        </svg>`;
      }
    }
  }

  return "";
};
