/**
 * SVGIconSetting Icon Modal
 *
 * アイコン選択モーダル関連の機能を管理
 */

import { useState, useEffect } from "@wordpress/element";
import { Button, TextControl } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { isPlus } from "../../../../../../utils/is-pro";
import { renderIconForSelector, renderSVGIcon } from "./IconRenderer";
import {
  featherIconsData,
  fontAwesomeOutlineData,
  fontAwesomeSolidData,
  fontAwesomeBrandsData,
  tablerOutlineData,
  tablerSolidData,
  heroiconsOutlineData,
  heroiconsSolidData,
  remixiconOutlineData,
  remixiconSolidData,
  lucideData,
  iconLicenses,
  getIconCategory,
  adjustViewBoxToPath,
} from "./utils";

/**
 * Unicode対応のBase64エンコード関数
 * @param {string} str - エンコードする文字列
 * @returns {string} Base64エンコードされた文字列
 */
const encodeBase64Unicode = (str) => {
  try {
    // UTF-8バイトシーケンスに変換してからBase64エンコード
    const utf8Bytes = new TextEncoder().encode(str);
    const binaryString = Array.from(utf8Bytes, (byte) => String.fromCharCode(byte)).join("");
    return btoa(binaryString);
  } catch (error) {
    console.error("Base64 encoding failed:", error);
    // フォールバック: 元の方法を試す
    try {
      return btoa(str);
    } catch (fallbackError) {
      console.error("Fallback base64 encoding also failed:", fallbackError);
      throw new Error("Base64 encoding failed for custom SVG");
    }
  }
};

/**
 * アイコン選択インライン表示コンポーネント
 * @param {Object} props - コンポーネントのプロパティ
 */
export const IconModal = ({ isVisible, onClose, onSelectIcon, onDeleteIcon, selectedIcon, lucideStrokeWidth = 1.75, anchorRef, color = "#333333" }) => {
  const [activeCategory, setActiveCategory] = useState(() => getIconCategory(selectedIcon));
  const [searchQuery, setSearchQuery] = useState("");
  const [faSubCategory, setFaSubCategory] = useState("solid");
  const [tablerSubCategory, setTablerSubCategory] = useState("outline");
  const [heroiconsSubCategory, setHeroiconsSubCategory] = useState("outline");
  const [remixiconSubCategory, setRemixiconSubCategory] = useState("outline");

  // カスタムSVG関連の状態
  const [customSVGCode, setCustomSVGCode] = useState("");
  const [customSVGPreview, setCustomSVGPreview] = useState("");
  const [customSVGError, setCustomSVGError] = useState("");

  // ライセンス情報の表示状態
  const [showLicenseInfo, setShowLicenseInfo] = useState(true);

  // アイコンデータのキャッシュ
  const [iconCache, setIconCache] = useState({
    feather: null,
    fontawesome: null,
    tabler: null,
    heroicons: null,
    remixicon: null,
    lucide: null,
    custom: null,
  });

  // アイコンが変更されたとき、そのアイコンのカテゴリーに自動的に切り替える
  useEffect(() => {
    if (selectedIcon) {
      setActiveCategory(getIconCategory(selectedIcon));
    }
  }, [selectedIcon]);

  const isPlusUser = isPlus();

  // Plus限定アイコンライブラリ（Lucide, Heroicons, Custom以外）
  const PLUS_ONLY_ICON_LIBRARIES = ["tabler", "feather", "fontawesome", "remixicon"];

  // アイコンカテゴリー
  const iconCategories = [
    { id: "lucide", label: __("Lucide", "zenblocks") },
    { id: "tabler", label: __("Tabler", "zenblocks"), plusOnly: true },
    { id: "heroicons", label: __("Heroicons", "zenblocks") },
    { id: "feather", label: __("Feather", "zenblocks"), plusOnly: true },
    { id: "fontawesome", label: __("Font Awesome", "zenblocks"), plusOnly: true },
    { id: "remixicon", label: __("RemixIcon", "zenblocks"), plusOnly: true },
    { id: "custom", label: __("Custom SVG", "zenblocks") },
  ];

  // Font Awesomeのサブカテゴリー
  const faSubCategories = [
    { id: "solid", label: __("Solid", "zenblocks") },
    { id: "regular", label: __("Outline", "zenblocks") },
    { id: "brands", label: __("Brands", "zenblocks") },
  ];

  // Tablerのサブカテゴリー
  const tablerSubCategories = [
    { id: "outline", label: __("Outline", "zenblocks") },
    { id: "solid", label: __("Solid", "zenblocks") },
  ];

  // Heroiconsサブカテゴリー
  const heroiconsSubCategories = [
    { id: "outline", label: __("Outline", "zenblocks") },
    { id: "solid", label: __("Solid", "zenblocks") },
  ];

  // RemixIconサブカテゴリー
  const remixiconSubCategories = [
    { id: "outline", label: __("Outline", "zenblocks") },
    { id: "solid", label: __("Solid", "zenblocks") },
  ];

  /**
   * ライセンス情報を取得する関数
   * @param {string} category - カテゴリー名
   * @returns {Object} ライセンス情報
   */
  const getLicenseInfo = (category) => {
    if (category === "none") {
      return iconLicenses["tabler"];
    }
    return iconLicenses[category] || iconLicenses["tabler"];
  };

  /**
   * 各カテゴリーのアイコン一覧を取得
   * @param {string} category - カテゴリー名
   * @returns {Array} アイコンの配列
   */
  const getIconsByCategory = (category) => {
    // キャッシュキーを生成する
    const cacheKey =
      category === "fontawesome"
        ? `${category}_${faSubCategory}`
        : category === "tabler"
        ? `${category}_${tablerSubCategory}`
        : category === "heroicons"
        ? `${category}_${heroiconsSubCategory}`
        : category === "remixicon"
        ? `${category}_${remixiconSubCategory}`
        : category;

    // キャッシュがあればそれを返す
    if (iconCache[cacheKey]) {
      return iconCache[cacheKey];
    }

    let icons = [];
    try {
      switch (category) {
        case "feather":
          icons = Object.keys(featherIconsData).map((name) => `feather-${name}`);
          break;

        case "fontawesome":
          if (searchQuery) {
            // サブカテゴリーに応じて適切なデータを検索
            switch (faSubCategory) {
              case "solid":
                Object.keys(fontAwesomeSolidData).forEach((key) => {
                  const iconName = key.startsWith("solid-") ? key.substring(6) : key;
                  if (iconName.toLowerCase().includes(searchQuery.toLowerCase())) {
                    icons.push(`fa-${iconName}`);
                  }
                });
                break;
              case "regular":
                Object.keys(fontAwesomeOutlineData).forEach((key) => {
                  const iconName = key.startsWith("regular-") ? key.substring(8) : key;
                  if (iconName.toLowerCase().includes(searchQuery.toLowerCase())) {
                    icons.push(`fa-regular-${iconName}`);
                  }
                });
                break;
              case "brands":
                Object.keys(fontAwesomeBrandsData).forEach((key) => {
                  const iconName = key.startsWith("brands-") ? key.substring(7) : key;
                  if (iconName.toLowerCase().includes(searchQuery.toLowerCase())) {
                    icons.push(`fa-brands-${iconName}`);
                  }
                });
                break;
            }
          } else {
            // サブカテゴリーに応じて適切なデータから取得
            switch (faSubCategory) {
              case "solid":
                Object.keys(fontAwesomeSolidData)
                  .slice(0, 300)
                  .forEach((key) => {
                    const iconName = key.startsWith("solid-") ? key.substring(6) : key;
                    icons.push(`fa-${iconName}`);
                  });
                break;

              case "regular":
                Object.keys(fontAwesomeOutlineData)
                  .slice(0, 300)
                  .forEach((key) => {
                    const iconName = key.startsWith("regular-") ? key.substring(8) : key;
                    icons.push(`fa-regular-${iconName}`);
                  });
                break;

              case "brands":
                Object.keys(fontAwesomeBrandsData)
                  .slice(0, 300)
                  .forEach((key) => {
                    const iconName = key.startsWith("brands-") ? key.substring(7) : key;
                    icons.push(`fa-brands-${iconName}`);
                  });
                break;

              default:
                Object.keys(fontAwesomeSolidData)
                  .slice(0, 300)
                  .forEach((key) => {
                    const iconName = key.startsWith("solid-") ? key.substring(6) : key;
                    icons.push(`fa-${iconName}`);
                  });
                break;
            }

            if (icons.length === 0) {
              const initialFaIcons =
                faSubCategory === "regular"
                  ? ["fa-regular-clock", "fa-regular-bell", "fa-regular-calendar", "fa-regular-circle", "fa-regular-square"]
                  : faSubCategory === "brands"
                  ? ["fa-brands-wordpress", "fa-brands-facebook", "fa-brands-twitter", "fa-brands-instagram", "fa-brands-linkedin"]
                  : ["fa-home", "fa-user", "fa-envelope", "fa-search", "fa-check"];

              icons = initialFaIcons;
            }
          }
          break;

        case "tabler":
          if (searchQuery) {
            // アウトラインアイコンを検索
            Object.keys(tablerOutlineData).forEach((key) => {
              if (key.toLowerCase().includes(searchQuery.toLowerCase())) {
                icons.push(`tabler-outline-${key}`);
              }
            });
            // ソリッドアイコンを検索
            Object.keys(tablerSolidData).forEach((key) => {
              if (key.toLowerCase().includes(searchQuery.toLowerCase())) {
                icons.push(`tabler-solid-${key}`);
              }
            });
          } else {
            if (tablerSubCategory === "solid") {
              Object.keys(tablerSolidData).forEach((key) => {
                icons.push(`tabler-solid-${key}`);
              });
            } else {
              Object.keys(tablerOutlineData).forEach((key) => {
                icons.push(`tabler-outline-${key}`);
              });
            }
          }
          break;

        case "heroicons":
          if (searchQuery) {
            // Outline icons
            Object.keys(heroiconsOutlineData).forEach((key) => {
              if (key.toLowerCase().includes(searchQuery.toLowerCase())) {
                icons.push(`heroicons-outline-${key}`);
              }
            });
            // Solid icons
            Object.keys(heroiconsSolidData).forEach((key) => {
              if (key.toLowerCase().includes(searchQuery.toLowerCase())) {
                icons.push(`heroicons-solid-${key}`);
              }
            });
          } else {
            const outlineKeys = Object.keys(heroiconsOutlineData);
            const solidKeys = Object.keys(heroiconsSolidData);

            if (heroiconsSubCategory === "solid") {
              solidKeys.forEach((key) => {
                icons.push(`heroicons-solid-${key}`);
              });
            } else {
              outlineKeys.forEach((key) => {
                icons.push(`heroicons-outline-${key}`);
              });
            }
          }
          break;

        case "remixicon":
          if (searchQuery) {
            // Outline icons
            Object.keys(remixiconOutlineData).forEach((key) => {
              if (key.toLowerCase().includes(searchQuery.toLowerCase())) {
                icons.push(`remixicon-outline-${key}`);
              }
            });
            // Solid icons
            Object.keys(remixiconSolidData).forEach((key) => {
              if (key.toLowerCase().includes(searchQuery.toLowerCase())) {
                icons.push(`remixicon-solid-${key}`);
              }
            });
          } else {
            const outlineKeys = Object.keys(remixiconOutlineData);
            const solidKeys = Object.keys(remixiconSolidData);

            if (remixiconSubCategory === "solid") {
              solidKeys.forEach((key) => {
                icons.push(`remixicon-solid-${key}`);
              });
            } else {
              outlineKeys.forEach((key) => {
                icons.push(`remixicon-outline-${key}`);
              });
            }
          }
          break;

        case "lucide":
          const lucideKeys = Object.keys(lucideData);

          if (searchQuery) {
            lucideKeys.forEach((key) => {
              if (key.toLowerCase().includes(searchQuery.toLowerCase())) {
                icons.push(`lucide-${key}`);
              }
            });
          } else {
            lucideKeys.forEach((key) => {
              icons.push(`lucide-${key}`);
            });
          }
          break;

        case "custom":
          icons = [];
          break;

        default:
          icons = [];
      }
    } catch (e) {
      console.error("Error getting icons by category:", e);
      icons = [];
    }

    // キャッシュを設定
    setIconCache((prevCache) => ({
      ...prevCache,
      [cacheKey]: icons,
    }));

    return icons;
  };

  /**
   * SVGコードをクリーンアップする関数
   * @param {string} svgCode - SVGコード
   * @returns {string} クリーンアップされたSVGコード
   */
  const cleanupSVGCode = (svgCode) => {
    if (!svgCode) return svgCode;

    try {
      // ブラウザ環境でのみ実行
      if (typeof DOMParser === "undefined" || typeof XMLSerializer === "undefined") {
        return svgCode;
      }

      const parser = new DOMParser();
      const svgDoc = parser.parseFromString(svgCode, "image/svg+xml");

      // パーサーエラーをチェック
      const parserError = svgDoc.querySelector("parsererror");
      if (parserError) {
        return svgCode;
      }

      // 背景のパスを削除
      const paths = svgDoc.querySelectorAll("path");
      paths.forEach((path) => {
        const d = path.getAttribute("d");
        if (d && (d.match(/M0\s*0\s*h\d+\s*v\d+\s*H0\s*z/i) || d.match(/M\s*0\s*,?\s*0\s*h\d+\s*v\d+\s*H\s*0\s*z/i) || d === "M0 0h24v24H0z")) {
          if (path.parentNode) {
            path.parentNode.removeChild(path);
          }
        }
      });

      // 空のクラス属性を削除
      const svg = svgDoc.querySelector("svg");
      if (svg && svg.hasAttribute("class")) {
        svg.removeAttribute("class");
      }

      // currentColorの処理（色変更機能のために保持）
      const allElements = svgDoc.querySelectorAll("*");
      allElements.forEach((el) => {
        // currentColorは保持し、その他の色はデフォルトに変換
        const stroke = el.getAttribute("stroke");
        const fill = el.getAttribute("fill");

        // currentColor以外の具体的な色をデフォルトに変換
        if (stroke && stroke !== "currentColor" && stroke !== "none") {
          el.setAttribute("stroke", "currentColor");
        }
        if (fill && fill !== "currentColor" && fill !== "none") {
          el.setAttribute("fill", "currentColor");
        }
      });

      const serializer = new XMLSerializer();
      let cleanedSvg = serializer.serializeToString(svgDoc);

      // viewBoxを自動調整（エラーハンドリングあり）
      try {
        cleanedSvg = adjustViewBoxToPath(cleanedSvg);
      } catch (adjustError) {
        // viewBox adjustment failed, use cleaned SVG without adjustment
      }

      return cleanedSvg;
    } catch (e) {
      return svgCode;
    }
  };

  /**
   * SVGコードを検証する関数
   * @param {string} svgCode - SVGコード
   * @returns {Object} 検証結果
   */
  const validateSVGCode = (svgCode) => {
    if (!svgCode || svgCode.trim() === "") {
      return { isValid: false, message: "SVGコードを入力してください" };
    }

    const trimmedCode = svgCode.trim();

    // 基本的なSVG構造をチェック
    if (!trimmedCode.includes("<svg") || !trimmedCode.includes("</svg>")) {
      return { isValid: false, message: "有効なSVGコードを入力してください（<svg>タグが必要です）" };
    }

    // ブラウザ環境でのみ詳細検証を実行
    if (typeof DOMParser !== "undefined") {
      try {
        const parser = new DOMParser();
        const svgDoc = parser.parseFromString(trimmedCode, "image/svg+xml");
        const parserError = svgDoc.querySelector("parsererror");

        if (parserError) {
          return { isValid: false, message: "SVGの構文エラー：正しいSVG形式で入力してください" };
        }

        // SVG要素が存在するかチェック
        const svgElement = svgDoc.querySelector("svg");
        if (!svgElement) {
          return { isValid: false, message: "SVG要素が見つかりません" };
        }

        return { isValid: true, message: "" };
      } catch (e) {
        return { isValid: false, message: `SVGの検証エラー: ${e.message}` };
      }
    } else {
      // DOM Parserが利用できない場合は簡単なチェックのみ
      return { isValid: true, message: "" };
    }
  };

  /**
   * SVGコードをアイコン形式に変換する
   * @param {string} svgCode - SVGコード
   * @returns {string} アイコン識別子
   */
  const convertSVGToIcon = (svgCode) => {
    try {
      const cleanedSVG = cleanupSVGCode(svgCode);
      const base64Svg = encodeBase64Unicode(cleanedSVG);
      return `custom-svg-${base64Svg}`;
    } catch (error) {
      console.error("Error converting SVG to icon:", error);
      throw new Error("カスタムSVGの変換に失敗しました。SVGコードを確認してください。");
    }
  };

  /**
   * 全カテゴリーからアイコンを取得（検索なし）
   * @param {string} category - カテゴリー名
   * @returns {Array} アイコンの配列
   */
  const getAllIconsByCategory = (category) => {
    let icons = [];
    try {
      switch (category) {
        case "feather":
          icons = Object.keys(featherIconsData).map((name) => `feather-${name}`);
          break;

        case "fontawesome":
          // 全サブカテゴリーのアイコンを取得
          Object.keys(fontAwesomeSolidData).forEach((key) => {
            const iconName = key.startsWith("solid-") ? key.substring(6) : key;
            icons.push(`fa-${iconName}`);
          });
          Object.keys(fontAwesomeOutlineData).forEach((key) => {
            const iconName = key.startsWith("regular-") ? key.substring(8) : key;
            icons.push(`fa-regular-${iconName}`);
          });
          Object.keys(fontAwesomeBrandsData).forEach((key) => {
            const iconName = key.startsWith("brands-") ? key.substring(7) : key;
            icons.push(`fa-brands-${iconName}`);
          });
          break;

        case "tabler":
          Object.keys(tablerOutlineData).forEach((key) => {
            icons.push(`tabler-outline-${key}`);
          });
          Object.keys(tablerSolidData).forEach((key) => {
            icons.push(`tabler-solid-${key}`);
          });
          break;

        case "heroicons":
          Object.keys(heroiconsOutlineData).forEach((key) => {
            icons.push(`heroicons-outline-${key}`);
          });
          Object.keys(heroiconsSolidData).forEach((key) => {
            icons.push(`heroicons-solid-${key}`);
          });
          break;

        case "remixicon":
          Object.keys(remixiconOutlineData).forEach((key) => {
            icons.push(`remixicon-outline-${key}`);
          });
          Object.keys(remixiconSolidData).forEach((key) => {
            icons.push(`remixicon-solid-${key}`);
          });
          break;

        case "lucide":
          Object.keys(lucideData).forEach((key) => {
            icons.push(`lucide-${key}`);
          });
          break;

        case "custom":
          icons = [];
          break;

        default:
          icons = [];
      }
    } catch (e) {
      console.error("Error getting all icons by category:", e);
      icons = [];
    }

    return icons;
  };

  /**
   * 検索に基づいてアイコンをフィルタリング
   * @returns {Array} フィルタリングされたアイコンの配列
   */
  const getFilteredIcons = () => {
    if (searchQuery) {
      const allIcons = [];
      iconCategories.forEach((category) => {
        if (category.id !== "custom") {
          // Plus限定ライブラリはPlus未有効なら除外
          if (category.plusOnly && !isPlusUser) return;
          allIcons.push(...getAllIconsByCategory(category.id));
        }
      });

      const filteredIcons = allIcons.filter((iconKey) => {
        return iconKey.toLowerCase().includes(searchQuery.toLowerCase());
      });

      return filteredIcons.slice(0, 500);
    } else {
      // Plus限定カテゴリが選択されている場合は空を返す
      const currentCategory = iconCategories.find((c) => c.id === activeCategory);
      if (currentCategory?.plusOnly && !isPlusUser) {
        return [];
      }
      const icons = getIconsByCategory(activeCategory);
      const maxIcons = activeCategory === "lucide" ? 2000 : 300;
      return icons.slice(0, maxIcons);
    }
  };

  /**
   * アイコンを選択
   * @param {string} iconKey - アイコン識別子
   */
  const selectIcon = (iconKey) => {
    onSelectIcon(iconKey);

    // カスタムSVGの場合は追加の初期設定を行う
    if (iconKey && iconKey.startsWith("custom-svg-")) {
      // stroke widthが未設定の場合はデフォルト値を設定
      if (!lucideStrokeWidth || lucideStrokeWidth === 1.75) {
        // onStrokeWidthChangeが利用可能な場合のみ実行
        // 注意: このコンポーネントはonStrokeWidthChangeプロパティを受け取っていないため、
        // 親コンポーネント（SVGIconSetting）で処理する必要がある
      }
    }
  };

  // Close on Escape key
  useEffect(() => {
    if (!isVisible) return;
    const handleKeyDown = (e) => {
      if (e.key === "Escape") {
        e.stopPropagation();
        onClose();
      }
    };
    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [isVisible, onClose]);

  if (!isVisible) return null;

  return (
    <div
      className="svg-icon-inline-selector"
      role="dialog"
      aria-label={__("Icon Selector", "zenblocks")}
      style={{
        backgroundColor: "#fff",
        border: "1px solid #ddd",
        borderRadius: "6px",
        marginTop: "12px",
        boxShadow: "0 2px 6px rgba(0,0,0,0.1)",
        maxHeight: "800px",
        position: "relative",
        zIndex: 30,
        width: "100%",
        display: "flex",
        flexDirection: "column",
      }}
    >
      <style
        dangerouslySetInnerHTML={{
          __html: `
          /* アイコン表示のためのSVGとpath要素のスタイル */
          .svg-icon-inline-selector__grid svg,
          .icon-preview-wrapper svg {
            fill: none !important;
          }
          .svg-icon-inline-selector__grid svg path,
          .svg-icon-inline-selector__grid svg rect,
          .svg-icon-inline-selector__grid svg circle,
          .svg-icon-inline-selector__grid svg line,
          .svg-icon-inline-selector__grid svg polyline,
          .svg-icon-inline-selector__grid svg polygon,
          .svg-icon-inline-selector__grid svg ellipse,
          .icon-preview-wrapper svg path,
          .icon-preview-wrapper svg rect,
          .icon-preview-wrapper svg circle,
          .icon-preview-wrapper svg line,
          .icon-preview-wrapper svg polyline,
          .icon-preview-wrapper svg polygon,
          .icon-preview-wrapper svg ellipse {
            fill: none !important;
          }
          /* Lucide Icons専用のスタイル強制 */
          .svg-icon-inline-selector__grid svg[viewBox="0 0 24 24"],
          .icon-preview-wrapper svg[viewBox="0 0 24 24"] {
            fill: none !important;
          }
          .svg-icon-inline-selector__grid svg[viewBox="0 0 24 24"] *,
          .icon-preview-wrapper svg[viewBox="0 0 24 24"] * {
            fill: none !important;
          }
          /* Font Awesome アイコンのためのスタイル上書き */
          .svg-icon-inline-selector__grid svg[fill="#333333"],
          .icon-preview-wrapper svg[fill="#333333"],
          .icon-preview-button svg[fill="#333333"] {
            fill: #333333 !important;
          }
          .svg-icon-inline-selector__grid svg[fill="#333333"] path,
          .icon-preview-wrapper svg[fill="#333333"] path,
          .icon-preview-button svg[fill="#333333"] path {
            fill: #333333 !important;
          }
          /* RemixIcon 特別処理 */
          .svg-icon-inline-selector__grid svg path[fill="#333333"],
          .icon-preview-wrapper svg path[fill="#333333"],
          .icon-preview-button svg path[fill="#333333"] {
            fill: #333333 !important;
          }
        `,
        }}
      />

      {/* ヘッダー部分 */}
      <div className="svg-icon-inline-selector__header" style={{ padding: "16px 16px 0 16px", marginBottom: "16px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "12px" }}>
          <div className="svg-icon-inline-selector__title" style={{ fontWeight: "600", fontSize: "14px" }}>
            {__("Select Icon", "zenblocks")}
          </div>
          <Button
            icon="no-alt"
            onClick={onClose}
            className="close-icon-selector"
            style={{
              padding: "6px",
              height: "28px",
              minWidth: "28px",
              borderRadius: "4px",
              justifyContent: "center",
            }}
            aria-label={__("Close", "zenblocks")}
          />
        </div>

        <div style={{ position: "relative", marginBottom: "12px" }}>
          <TextControl
            placeholder={__("Search... (searches all categories)", "zenblocks")}
            value={searchQuery}
            onChange={setSearchQuery}
            style={{
              marginBottom: "0",
              boxShadow: searchQuery ? "0 0 0 1px #2669e6" : "none",
              border: searchQuery ? "1px solid #2669e6" : "1px solid #757575",
            }}
          />
          {searchQuery && (
            <Button
              icon="no-alt"
              onClick={() => setSearchQuery("")}
              style={{
                position: "absolute",
                right: "8px",
                top: "50%",
                transform: "translateY(-50%)",
                background: "transparent",
                border: "none",
                padding: "2px",
                minWidth: "20px",
                minHeight: "20px",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
              }}
            />
          )}
        </div>

        {/* 選択中のアイコン名を簡易表示 */}
        {selectedIcon && (
          <div style={{ fontSize: "12px", color: "#666", marginBottom: "8px" }}>
            {__("Selected:", "zenblocks")}{" "}
            <span style={{ fontWeight: "600", color: "#333" }}>
              {selectedIcon.startsWith("custom-svg-")
                ? __("Custom SVG", "zenblocks")
                : selectedIcon.split("-").slice(1).join("-")}
            </span>
          </div>
        )}

        <div className="svg-icon-inline-selector__categories" style={{ display: "flex", flexWrap: "wrap", gap: "4px", marginBottom: "12px" }}>
          {searchQuery ? <div style={{ width: "100%", fontSize: "12px", color: "#666", marginBottom: "4px" }}>{__("Searching all categories", "zenblocks")}</div> : null}
          {iconCategories.map((category) => {
            const isLocked = category.plusOnly && !isPlusUser;
            return (
              <Button
                key={category.id}
                isSmall
                variant={!searchQuery && activeCategory === category.id ? "primary" : "secondary"}
                onClick={() => {
                  if (isLocked) return;
                  setActiveCategory(category.id);
                  if (searchQuery) {
                    setSearchQuery("");
                  }
                }}
                disabled={!!searchQuery || isLocked}
                style={isLocked ? { opacity: 0.5 } : undefined}
              >
                {category.label}
                {isLocked && (
                  <span style={{
                    marginLeft: "4px",
                    fontSize: "9px",
                    fontWeight: "700",
                    background: "#2563eb",
                    color: "#fff",
                    padding: "1px 4px",
                    borderRadius: "2px",
                    lineHeight: "1.2",
                  }}>PLUS</span>
                )}
              </Button>
            );
          })}
        </div>

        {!searchQuery && activeCategory === "fontawesome" && (
          <div style={{ marginBottom: "0px", paddingBottom: "0px" }}>
            <div className="svg-icon-inline-selector__subcategories" style={{ display: "flex", flexWrap: "wrap", gap: "4px", background: "#f5f5f5", padding: "8px", borderRadius: "4px" }}>
              <div className="fontawesome-subcategory-buttons" style={{ display: "flex", width: "100%", gap: "4px" }}>
                {faSubCategories.map((subCat) => (
                  <Button
                    key={subCat.id}
                    isSmall
                    variant={faSubCategory === subCat.id ? "primary" : "secondary"}
                    onClick={() => setFaSubCategory(subCat.id)}
                    style={{
                      fontWeight: faSubCategory === subCat.id ? "bold" : "normal",
                    }}
                  >
                    {subCat.label}
                  </Button>
                ))}
              </div>
            </div>
          </div>
        )}

        {!searchQuery && activeCategory === "tabler" && (
          <div style={{ marginBottom: "0px", paddingBottom: "0px" }}>
            <div className="svg-icon-inline-selector__subcategories" style={{ display: "flex", flexWrap: "wrap", gap: "4px", background: "#f5f5f5", padding: "8px", borderRadius: "4px" }}>
              <div style={{ display: "flex", width: "100%", gap: "6px" }}>
                {tablerSubCategories.map((subCat) => (
                  <Button
                    key={subCat.id}
                    isSmall
                    variant={tablerSubCategory === subCat.id ? "primary" : "secondary"}
                    onClick={() => setTablerSubCategory(subCat.id)}
                    style={{
                      flex: 1,
                      justifyContent: "center",
                      margin: "2px",
                      fontWeight: tablerSubCategory === subCat.id ? "bold" : "normal",
                      height: "26px",
                    }}
                  >
                    {subCat.label}
                  </Button>
                ))}
              </div>
            </div>
          </div>
        )}

        {!searchQuery && activeCategory === "heroicons" && (
          <div style={{ marginBottom: "0px", paddingBottom: "0px" }}>
            <div className="svg-icon-inline-selector__subcategories" style={{ display: "flex", flexWrap: "wrap", gap: "4px", background: "#f5f5f5", padding: "8px", borderRadius: "4px" }}>
              <div style={{ display: "flex", width: "100%", gap: "6px" }}>
                {heroiconsSubCategories.map((subCat) => (
                  <Button
                    key={subCat.id}
                    isSmall
                    variant={heroiconsSubCategory === subCat.id ? "primary" : "secondary"}
                    onClick={() => setHeroiconsSubCategory(subCat.id)}
                    style={{
                      flex: 1,
                      justifyContent: "center",
                      margin: "2px",
                      fontWeight: heroiconsSubCategory === subCat.id ? "bold" : "normal",
                      height: "26px",
                    }}
                  >
                    {subCat.label}
                  </Button>
                ))}
              </div>
            </div>
          </div>
        )}

        {!searchQuery && activeCategory === "remixicon" && (
          <div style={{ marginBottom: "0px", paddingBottom: "0px" }}>
            <div className="svg-icon-inline-selector__subcategories" style={{ display: "flex", flexWrap: "wrap", gap: "4px", background: "#f5f5f5", padding: "8px", borderRadius: "4px" }}>
              <div style={{ display: "flex", width: "100%", gap: "6px" }}>
                {remixiconSubCategories.map((subCat) => (
                  <Button
                    key={subCat.id}
                    isSmall
                    variant={remixiconSubCategory === subCat.id ? "primary" : "secondary"}
                    onClick={() => setRemixiconSubCategory(subCat.id)}
                    style={{
                      flex: 1,
                      justifyContent: "center",
                      margin: "2px",
                      fontWeight: remixiconSubCategory === subCat.id ? "bold" : "normal",
                      height: "26px",
                    }}
                  >
                    {subCat.label}
                  </Button>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>

      {/* スクロール可能なコンテンツ部分 */}
      <div
        className="svg-icon-inline-selector__content"
        style={{
          flex: 1,
          overflowY: "auto",
          padding: "0 16px",
          paddingBottom: "16px",
        }}
      >
        <div className="svg-icon-inline-selector__grid" style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: "8px" }}>
          {activeCategory === "custom" ? (
            <div style={{ gridColumn: "1 / span 4", padding: "0px" }}>
              {/* 色変更の説明 */}
              <div
                style={{
                  backgroundColor: "#e6f3ff",
                  padding: "12px",
                  borderRadius: "6px",
                  marginBottom: "16px",
                  border: "1px solid #b3d9ff",
                }}
              >
                <div style={{ fontSize: "13px", fontWeight: "600", marginBottom: "8px", color: "#0066cc" }}>💡 色変更機能を使うには</div>
                <div style={{ fontSize: "12px", lineHeight: "1.4", color: "#004499" }}>
                  SVGコード内で色を変更したい部分に{" "}
                  <code
                    style={{
                      backgroundColor: "#fff3cd",
                      padding: "2px 4px",
                      borderRadius: "3px",
                      fontFamily: "monospace",
                      color: "#856404",
                      border: "1px solid #ffeaa7",
                    }}
                  >
                    currentColor
                  </code>{" "}
                  を使用してください。
                  <br />
                  例:{" "}
                  <code
                    style={{
                      backgroundColor: "#fff3cd",
                      padding: "2px 4px",
                      borderRadius: "3px",
                      fontFamily: "monospace",
                      color: "#856404",
                      border: "1px solid #ffeaa7",
                    }}
                  >
                    stroke="currentColor"
                  </code>{" "}
                  や{" "}
                  <code
                    style={{
                      backgroundColor: "#fff3cd",
                      padding: "2px 4px",
                      borderRadius: "3px",
                      fontFamily: "monospace",
                      color: "#856404",
                      border: "1px solid #ffeaa7",
                    }}
                  >
                    fill="currentColor"
                  </code>
                </div>
              </div>

              <div style={{ marginBottom: "10px" }}>
                <label style={{ display: "block", marginBottom: "8px", fontSize: "11px", fontWeight: "500", textTransform: "uppercase" }}>
                  {__("Enter SVG code", "zenblocks")}
                </label>
                <textarea
                  value={customSVGCode}
                  onChange={(e) => {
                    const value = e.target.value;
                    setCustomSVGCode(value);
                    const validation = validateSVGCode(value);
                    if (validation.isValid) {
                      // プレビューには入力されたSVGをそのまま表示
                      setCustomSVGPreview(value);
                      setCustomSVGError("");
                    } else {
                      setCustomSVGPreview("");
                      setCustomSVGError(validation.message);
                    }
                  }}
                  style={{
                    width: "100%",
                    minHeight: "150px",
                    padding: "8px",
                    fontFamily: "monospace",
                    fontSize: "12px",
                    border: "1px solid #757575",
                    borderRadius: "4px",
                    resize: "vertical",
                    boxSizing: "border-box",
                  }}
                  placeholder={__("Paste SVG code here...", "zenblocks")}
                />
                <p style={{ fontSize: "12px", color: "#757575", marginTop: "8px", marginBottom: "0" }}>
                  {__("To use color change feature, use \"currentColor\" in SVG code", "zenblocks")}
                </p>
              </div>

              {/* currentColorのハイライト表示 */}
              {customSVGCode && customSVGCode.includes("currentColor") && (
                <div
                  style={{
                    backgroundColor: "#d4edda",
                    padding: "8px 12px",
                    borderRadius: "4px",
                    marginBottom: "10px",
                    border: "1px solid #c3e6cb",
                  }}
                >
                  <div style={{ fontSize: "12px", color: "#155724", fontWeight: "600" }}>✅ currentColor が検出されました！</div>
                  <div style={{ fontSize: "11px", color: "#155724", marginTop: "4px" }}>カラーピッカーで色を変更できます</div>
                </div>
              )}

              {customSVGCode && !customSVGCode.includes("currentColor") && customSVGCode.trim() !== "" && (
                <div
                  style={{
                    backgroundColor: "#fff3cd",
                    padding: "8px 12px",
                    borderRadius: "4px",
                    marginBottom: "10px",
                    border: "1px solid #ffeaa7",
                  }}
                >
                  <div style={{ fontSize: "12px", color: "#856404", fontWeight: "600" }}>⚠️ currentColor が見つかりません</div>
                  <div style={{ fontSize: "11px", color: "#856404", marginTop: "4px" }}>色変更機能を使用するには、stroke="currentColor" や fill="currentColor" を追加してください</div>
                </div>
              )}

              {customSVGError && <div style={{ color: "#cc0000", marginBottom: "10px", fontSize: "13px" }}>{customSVGError}</div>}

              {customSVGPreview && (
                <div>
                  <div style={{ marginBottom: "10px" }}>
                    <strong>{__("Preview", "zenblocks")}:</strong>
                  </div>
                  <div
                    style={{
                      width: "100%",
                      padding: "15px",
                      backgroundColor: "#f7f7f7",
                      borderRadius: "4px",
                      display: "flex",
                      justifyContent: "center",
                      alignItems: "center",
                      marginBottom: "15px",
                      border: "1px solid #ddd",
                      minHeight: "80px",
                    }}
                  >
                    <div
                      className="custom-svg-preview"
                      style={{
                        width: "64px",
                        height: "64px",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        color: color || "#333333",
                      }}
                      dangerouslySetInnerHTML={{ __html: customSVGPreview }}
                    />
                  </div>
                  <style dangerouslySetInnerHTML={{ __html: `
                    .custom-svg-preview svg {
                      width: 100%;
                      height: 100%;
                      max-width: 64px;
                      max-height: 64px;
                    }
                  `}} />

                  <Button
                    variant="primary"
                    onClick={() => {
                      if (customSVGPreview) {
                        try {
                          const iconKey = convertSVGToIcon(customSVGPreview);
                          selectIcon(iconKey);
                          onClose();
                        } catch (error) {
                          setCustomSVGError(error.message);
                        }
                      }
                    }}
                    disabled={!customSVGPreview}
                    style={{ width: "100%", justifyContent: "center" }}
                  >
                    {__("Use this SVG", "zenblocks")}
                  </Button>
                </div>
              )}
            </div>
          ) : (
            getFilteredIcons().map((iconKey) => (
              <Button
                key={iconKey}
                className="svg-icon-inline-selector__item"
                onClick={() => selectIcon(iconKey)}
                style={{
                  width: "100%",
                  height: "60px",
                  padding: "6px 3px",
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "center",
                  alignItems: "center",
                  backgroundColor: selectedIcon === iconKey ? "#e8f4fd" : "#f7f7f7",
                  border: selectedIcon === iconKey ? "2px solid #2669e6" : "1px solid #ddd",
                  position: "relative",
                  boxShadow: selectedIcon === iconKey ? "0 0 2px 1px rgba(0, 124, 186, 0.4)" : "none",
                  borderRadius: "4px",
                  overflow: "hidden",
                }}
              >
                <span style={{ position: "relative" }}>
                  <span
                    className="icon-preview-wrapper"
                    style={{
                      width: "24px",
                      height: "24px",
                      display: "flex",
                      alignItems: "center",
                      justifyContent: "center",
                      marginBottom: "3px",
                    }}
                    dangerouslySetInnerHTML={{
                      __html: renderIconForSelector(iconKey, "#333333"),
                    }}
                  />
                  {selectedIcon === iconKey && (
                    <span
                      style={{
                        position: "absolute",
                        top: "-6px",
                        right: "-6px",
                        backgroundColor: "#2669e6",
                        borderRadius: "50%",
                        width: "14px",
                        height: "14px",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        padding: "1px",
                      }}
                    >
                      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="10" height="10" style={{ fill: "#fff" }}>
                        <path d="M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z" />
                      </svg>
                    </span>
                  )}
                </span>
                <span
                  style={{
                    fontSize: "9px",
                    lineHeight: "1.1",
                    color: "#666",
                    textAlign: "center",
                    maxWidth: "100%",
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                    padding: "0 1px",
                  }}
                >
                  {searchQuery ? (
                    <>
                      <span style={{ color: "#888", fontSize: "8px", display: "block", marginBottom: "2px" }}>
                        {iconKey.startsWith("feather-")
                          ? "Feather"
                          : iconKey.startsWith("fa-")
                          ? "Font Awesome"
                          : iconKey.startsWith("heroicons-")
                          ? "Heroicons"
                          : iconKey.startsWith("remixicon-")
                          ? "RemixIcon"
                          : iconKey.startsWith("lucide-")
                          ? "Lucide"
                          : "Tabler"}
                      </span>
                      {iconKey.split("-").slice(1).join("-")}
                    </>
                  ) : (
                    iconKey.split("-").slice(1).join("-")
                  )}
                </span>
              </Button>
            ))
          )}
        </div>

        {getFilteredIcons().length === 0 && activeCategory !== "custom" && (
          <div style={{ padding: "20px 0", textAlign: "center", color: "#888" }}>{__("No icons found", "zenblocks")}</div>
        )}
      </div>

      {/* ライセンス情報表示 - 固定フッター */}
      <div
        className="svg-icon-inline-selector__footer"
        style={{
          borderTop: "1px solid #ddd",
          padding: "10px 16px",
          fontSize: "11px",
          color: "#666",
          backgroundColor: "#fafafa",
          flexShrink: 0,
        }}
      >
        {/* アイコンを削除ボタン */}
        {selectedIcon && (
          <div style={{ marginBottom: "8px", paddingBottom: "8px", borderBottom: "1px dashed #ddd" }}>
            <Button
              variant="secondary"
              onClick={() => {
                if (onDeleteIcon) {
                  onDeleteIcon();
                }
                onClose();
              }}
              style={{
                color: "#cc0000",
                borderColor: "#cc0000",
                width: "100%",
                justifyContent: "center",
                fontSize: "13px",
              }}
            >
              {__("Remove Icon", "zenblocks")}
            </Button>
          </div>
        )}

        {/* ライセンス情報の折りたたみ可能なヘッダー */}
        <div
          style={{
            display: "flex",
            alignItems: "center",
            justifyContent: "space-between",
            cursor: "pointer",
            padding: "4px 0",
            userSelect: "none",
          }}
          onClick={() => setShowLicenseInfo(!showLicenseInfo)}
        >
          <div style={{ fontWeight: "600", fontSize: "12px", display: "flex", alignItems: "center", gap: "6px" }}>
            <span style={{ transition: "transform 0.2s", transform: showLicenseInfo ? "rotate(90deg)" : "rotate(0deg)", display: "inline-block" }}>▶</span>
            {__("License Information", "zenblocks")}
          </div>
          {!showLicenseInfo && <span style={{ fontSize: "10px", color: "#888" }}>{__("Click to show", "zenblocks")}</span>}
        </div>

        {/* 折りたたみ可能なライセンス情報 */}
        {showLicenseInfo && (
          <div style={{ marginTop: "8px", paddingTop: "8px", borderTop: "1px solid #e0e0e0" }}>
            {/* ブランドアイコン使用時の注意書き */}
            {(() => {
              // ブランドアイコンが表示されているかチェック
              const isBrandIconVisible =
                (activeCategory === "fontawesome" && faSubCategory === "brands") ||
                (searchQuery &&
                  getFilteredIcons().some((iconKey) => iconKey.startsWith("fa-brands-")));

              if (isBrandIconVisible) {
                return (
                  <div
                    style={{
                      marginBottom: "10px",
                      padding: "8px 10px",
                      backgroundColor: "#fff8e6",
                      border: "1px solid #f0d58c",
                      borderRadius: "4px",
                      fontSize: "10px",
                      lineHeight: "1.5",
                      color: "#665c3d",
                    }}
                  >
                    <div style={{ fontWeight: "600", marginBottom: "4px", fontSize: "11px" }}>
                      {__("About brand icon usage", "zenblocks")}
                    </div>
                    <div>
                      {__(
                        "Brand logos and icons are trademarks of their respective companies. These icons are provided under the Font Awesome license, but the trademarks belong to their respective companies.",
                        "zenblocks"
                      )}
                    </div>
                    <div style={{ marginTop: "4px" }}>
                      {__(
                        "Please use brand icons only for appropriate purposes such as linking to official services and products. Misleading or unrelated usage may constitute trademark infringement.",
                        "zenblocks"
                      )}
                    </div>
                  </div>
                );
              }
              return null;
            })()}

            {activeCategory === "custom" ? (
              <div style={{ fontSize: "11px", lineHeight: "1.5" }}>
                {__("When using custom SVGs, please be aware of copyright and licensing. Only use SVGs permitted by their license.", "zenblocks")}
              </div>
            ) : (
              <div>
                {searchQuery ? (
                  // 検索時：現在表示されているアイコンのライセンスのみ表示
                  (() => {
                    const displayedCategories = new Set();
                    const filteredIcons = getFilteredIcons();

                    // 表示されているアイコンのカテゴリーを収集
                    filteredIcons.forEach((iconKey) => {
                      if (iconKey.startsWith("feather-")) displayedCategories.add("feather");
                      else if (iconKey.startsWith("fa-")) displayedCategories.add("fontawesome");
                      else if (iconKey.startsWith("tabler-")) displayedCategories.add("tabler");
                      else if (iconKey.startsWith("heroicons-")) displayedCategories.add("heroicons");
                      else if (iconKey.startsWith("remixicon-")) displayedCategories.add("remixicon");
                      else if (iconKey.startsWith("lucide-")) displayedCategories.add("lucide");
                    });

                    const relevantLicenses = Array.from(displayedCategories)
                      .map((cat) => iconLicenses[cat])
                      .filter(Boolean);

                    return (
                      <ul style={{ margin: "0", padding: "0", listStyle: "none" }}>
                        {relevantLicenses.length > 0 ? (
                          relevantLicenses.map((license) => (
                            <li key={license.name} style={{ margin: "4px 0", fontSize: "11px", lineHeight: "1.4" }}>
                              <strong>{license.name}:</strong> {license.license}
                              <div style={{ fontSize: "10px", color: "#888", marginTop: "2px" }}>{license.attribution}</div>
                            </li>
                          ))
                        ) : (
                          <li style={{ margin: "4px 0", fontSize: "11px", color: "#888" }}>{__("No matching icons found", "zenblocks")}</li>
                        )}
                      </ul>
                    );
                  })()
                ) : (
                  // カテゴリー選択時：選択されたカテゴリーのライセンスのみ表示
                  <div style={{ fontSize: "11px", lineHeight: "1.5" }}>
                    <strong>{getLicenseInfo(activeCategory).name}:</strong> {getLicenseInfo(activeCategory).license}
                    <div style={{ fontSize: "10px", color: "#888", marginTop: "4px" }}>{getLicenseInfo(activeCategory).attribution}</div>
                  </div>
                )}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
};

export default IconModal;
