/**
 * PresetImageSelector - 再利用可能なプリセット画像セレクター
 * 背景画像、サムネイルなど様々な場面で使用可能
 */
import { useState, createInterpolateElement } from "@wordpress/element";
import { Button } from "@wordpress/components";
import { __ } from "@wordpress/i18n";
import { check, link as linkIcon } from "@wordpress/icons";
import StyledToggle from "./StyledToggle";
import "./PresetImageSelector.css";

const PRESET_LICENSE_MSGID = "Preset images are sourced from <source>StockSnap</source>. License: <license>CC0 1.0</license>. Available for commercial use, no attribution required.";
const PRESET_LICENSE_FALLBACK_JA = "プリセット画像は<source>StockSnap</source>提供です。ライセンスは<license>CC0 1.0</license>で、商用利用可能・クレジット表記は不要です。";

const getPresetLicenseNotice = () => {
  const translated = __(PRESET_LICENSE_MSGID, "zenblocks");
  if (translated !== PRESET_LICENSE_MSGID) {
    return translated;
  }

  if (typeof document !== "undefined") {
    const lang = String(document.documentElement?.lang || "").toLowerCase();
    if (lang.startsWith("ja")) {
      return PRESET_LICENSE_FALLBACK_JA;
    }
  }

  return translated;
};

/**
 * PresetImageSelector コンポーネント
 * @param {Object} props
 * @param {Array} props.images - プリセット画像リスト [{id, url, label, category?}]
 * @param {Array} props.categories - カテゴリリスト [{id, label}] (オプション)
 * @param {string} props.selectedUrl - 現在選択されている画像URL
 * @param {Function} props.onSelect - 画像選択時のコールバック (url) => void
 * @param {string} props.label - セクションラベル (デフォルト: "プリセット")
 * @param {number} props.columns - グリッドの列数 (デフォルト: 4)
 * @param {boolean} props.showCategories - カテゴリフィルタを表示するか (デフォルト: false)
 * @param {boolean} props.initialOpen - 初期状態で開くか (デフォルト: false)
 */
const PresetImageSelector = ({
  images = [],
  categories = [],
  selectedUrl = "",
  onSelect,
  label = __("Preset", "zenblocks"),
  columns = 4,
  showCategories = false,
  initialOpen = false,
  showToggle = true,
  showLicenseNotice = true,
}) => {
  const [activeCategory, setActiveCategory] = useState("all");
  const [isOpen, setIsOpen] = useState(showToggle ? initialOpen : true);

  // カテゴリでフィルタリング
  const filteredImages = activeCategory === "all"
    ? images
    : images.filter((img) => img.category === activeCategory);

  // 選択中かどうかを判定
  const isSelected = (imageUrl) => {
    if (!selectedUrl || !imageUrl) return false;
    // URLの末尾部分で比較（異なるドメインでも同じファイルなら一致）
    const selectedFileName = selectedUrl.split("/").pop();
    const imageFileName = imageUrl.split("/").pop();
    return selectedFileName === imageFileName;
  };

  const handleSelect = (url) => {
    if (onSelect) {
      onSelect(url);
    }
  };

  if (images.length === 0) {
    return null;
  }

  return (
    <div className="zenblocks-preset-image-selector">
      {/* トグルボタン */}
      {showToggle && (
        <StyledToggle
          label={label}
          checked={isOpen}
          onChange={setIsOpen}
        />
      )}

      {(showToggle ? isOpen : true) && (
        <div className="zenblocks-preset-image-selector__content">
          {/* カテゴリフィルタ */}
          {showCategories && categories.length > 0 && (
            <div className="zenblocks-preset-image-selector__categories">
              {categories.map((cat) => (
                <Button
                  key={cat.id}
                  isSmall
                  variant={activeCategory === cat.id ? "primary" : "secondary"}
                  onClick={() => setActiveCategory(cat.id)}
                  className="zenblocks-preset-image-selector__category-btn"
                >
                  {cat.label}
                </Button>
              ))}
            </div>
          )}

          {/* 画像グリッド */}
          <div
            className="zenblocks-preset-image-selector__grid"
            style={{
              display: "grid",
              gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))`,
              gap: "6px",
              rowGap: "6px",
              columnGap: "6px",
              maxHeight: "280px",
              overflowY: "auto",
              padding: "2px",
            }}
          >
            {filteredImages.map((image) => (
              <div key={image.id} className="zenblocks-preset-image-selector__item-card">
                <div className="zenblocks-preset-image-selector__image-wrap">
                  <button
                    type="button"
                    className={`zenblocks-preset-image-selector__item ${
                      isSelected(image.url) ? "is-selected" : ""
                    }`}
                    onClick={() => handleSelect(image.url)}
                    title={image.label}
                  >
                    <img src={image.url} alt={image.label} />
                    {isSelected(image.url) && (
                      <span className="zenblocks-preset-image-selector__check">
                        {check}
                      </span>
                    )}
                  </button>
                </div>
                <div className="zenblocks-preset-image-selector__item-actions">
                  {(image.creatorUrl || image.sourceUrl) && (
                    <a
                      href={image.creatorUrl || image.sourceUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="zenblocks-preset-image-selector__action-icon"
                      title={__("Author", "zenblocks")}
                      aria-label={__("Author", "zenblocks")}
                    >
                      <svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
                        <circle cx="12" cy="8" r="3.5" fill="none" stroke="currentColor" strokeWidth="1.8" />
                        <path d="M5.5 19c0-3.2 2.9-5.5 6.5-5.5s6.5 2.3 6.5 5.5" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
                      </svg>
                    </a>
                  )}
                  {image.sourceUrl && (
                    <a
                      href={image.sourceUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="zenblocks-preset-image-selector__action-icon"
                      title={__("Source", "zenblocks")}
                      aria-label={__("Source", "zenblocks")}
                    >
                      {linkIcon}
                    </a>
                  )}
                  {image.licenseUrl && (
                    <a
                      href={image.licenseUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="zenblocks-preset-image-selector__action-icon"
                      title={__("License (CC0)", "zenblocks")}
                      aria-label={__("License (CC0)", "zenblocks")}
                    >
                      {check}
                    </a>
                  )}
                </div>
              </div>
            ))}
          </div>

          {/* ライセンス説明 */}
          {showLicenseNotice && (
            <p className="zenblocks-preset-image-selector__license">
              {createInterpolateElement(
                getPresetLicenseNotice(),
                {
                  source: <a href="https://stocksnap.io/" target="_blank" rel="noopener noreferrer">StockSnap</a>,
                  license: <a href="https://creativecommons.org/publicdomain/zero/1.0/" target="_blank" rel="noopener noreferrer">CC0 1.0</a>,
                }
              )}
            </p>
          )}

          {/* クリア動線は ImageSelector 側の「画像を削除」に統一 */}
        </div>
      )}
    </div>
  );
};

export default PresetImageSelector;
