import getBackgroundPattern from "./getBackgroundPattern";

/**
 * 背景設定を表示するコンポーネント
 *
 * @param {Object} props コンポーネントのプロパティ
 * @param {Object} props.attributes ブロックの属性
 * @param {string} props.className 背景コンテナのクラス名
 * @param {Object} props.style 追加のスタイル（オプション）
 * @returns {JSX.Element} 背景要素
 */
const BackgroundBasicRender = ({ attributes, className = "background-basic", style = {} }) => {
  // column-basic内でのカードスタイル適用かどうかを判定
  const isInCardStyleProvider = className.includes("card-basic");

  // column-basicからのCSS変数を使用する場合のdata属性を取得
  const getCardStyleDataAttributes = () => {
    if (!isInCardStyleProvider) return {};

    // CSS変数からパターンタイプを取得（実際のDOM要素が必要なので、useEffectまたはrefを使用する必要がある）
    // 今回は、CSS変数の存在を前提として、デフォルト値を設定
    return {
      "data-has-gradient-pc": "false",
      "data-has-gradient-sp": "false",
      "data-pattern-type-pc": "none",
      "data-pattern-type-sp": "none",
    };
  };

  const cardStyleDataAttributes = getCardStyleDataAttributes();
  // デバッグ: 実際に渡される属性を確認
  // console.log('=== BackgroundBasicRender ===');
  // console.log('backgroundColorPC:', attributes.backgroundColorPC);
  // console.log('backgroundColorSP:', attributes.backgroundColorSP);
  // console.log('useGradientBackgroundPC:', attributes.useGradientBackgroundPC);
  // console.log('backgroundGradientPC:', attributes.backgroundGradientPC);
  // console.log('className:', className);

  // 実際の属性値をチェック
  // console.log('backgroundColorPC type:', typeof attributes.backgroundColorPC);
  // console.log('backgroundColorPC length:', attributes.backgroundColorPC ? attributes.backgroundColorPC.length : 'N/A');
  // console.log('backgroundColorPC value check:', {
  //   isEmpty: attributes.backgroundColorPC === '',
  //   isNull: attributes.backgroundColorPC === null,
  //   isUndefined: attributes.backgroundColorPC === undefined,
  //   isFalsy: !attributes.backgroundColorPC
  // });

  // グラデーション値の正規化と有効性チェック
  const normalizeGradient = (gradient) => {
    if (!gradient || gradient === null || gradient === undefined || gradient === "" || gradient === "none") {
      return "none";
    }
    return gradient;
  };

  const hasValidGradientPC = normalizeGradient(attributes.backgroundGradientPC) !== "none";
  const hasValidGradientMD = normalizeGradient(attributes.backgroundGradientMD) !== "none";
  const hasValidGradientTB = normalizeGradient(attributes.backgroundGradientTB) !== "none";
  const hasValidGradientSP = normalizeGradient(attributes.backgroundGradientSP) !== "none";

  // CSS変数の値を生成
  const cssVars = {
    "--background-color-pc": attributes.backgroundColorPC && attributes.backgroundColorPC !== "" ? attributes.backgroundColorPC : "transparent",
    "--background-gradient-pc": normalizeGradient(attributes.backgroundGradientPC),
    "--background-color-opacity-pc": `${attributes.backgroundColorOpacityPC !== undefined ? attributes.backgroundColorOpacityPC : 1}`,
    "--background-color-mix-blend-mode-pc": attributes.backgroundColorMixBlendModePC || "normal",
    "--background-color-md": attributes.backgroundColorMD && attributes.backgroundColorMD !== "" ? attributes.backgroundColorMD : "transparent",
    "--background-gradient-md": normalizeGradient(attributes.backgroundGradientMD),
    "--background-color-opacity-md": `${attributes.backgroundColorOpacityMD !== undefined ? attributes.backgroundColorOpacityMD : 1}`,
    "--background-color-mix-blend-mode-md": attributes.backgroundColorMixBlendModeMD || "normal",
    "--background-color-tb": attributes.backgroundColorTB && attributes.backgroundColorTB !== "" ? attributes.backgroundColorTB : "transparent",
    "--background-gradient-tb": normalizeGradient(attributes.backgroundGradientTB),
    "--background-color-opacity-tb": `${attributes.backgroundColorOpacityTB !== undefined ? attributes.backgroundColorOpacityTB : 1}`,
    "--background-color-mix-blend-mode-tb": attributes.backgroundColorMixBlendModeTB || "normal",
    "--background-color-sp": attributes.backgroundColorSP && attributes.backgroundColorSP !== "" ? attributes.backgroundColorSP : "transparent",
    "--background-gradient-sp": normalizeGradient(attributes.backgroundGradientSP),
    "--background-color-opacity-sp": `${attributes.backgroundColorOpacitySP !== undefined ? attributes.backgroundColorOpacitySP : 1}`,
    "--background-color-mix-blend-mode-sp": attributes.backgroundColorMixBlendModeSP || "normal",
  };

  // CSS変数の設定をデバッグ出力
  // console.log('CSS変数設定:', cssVars);

  return (
    <div className={`${className}__bg`} style={style}>
      {/* 背景色レイヤー */}
      <div
        className={`${className}__bg_color`}
        data-use-gradient-pc={attributes.useGradientBackgroundPC && hasValidGradientPC ? "true" : "false"}
        data-use-gradient-md={attributes.useGradientBackgroundMD && hasValidGradientMD ? "true" : "false"}
        data-use-gradient-tb={attributes.useGradientBackgroundTB && hasValidGradientTB ? "true" : "false"}
        data-use-gradient-sp={attributes.useGradientBackgroundSP && hasValidGradientSP ? "true" : "false"}
        data-has-gradient-pc={attributes.useGradientBackgroundPC && hasValidGradientPC ? "true" : "false"}
        data-has-gradient-md={attributes.useGradientBackgroundMD && hasValidGradientMD ? "true" : "false"}
        data-has-gradient-tb={attributes.useGradientBackgroundTB && hasValidGradientTB ? "true" : "false"}
        data-has-gradient-sp={attributes.useGradientBackgroundSP && hasValidGradientSP ? "true" : "false"}
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          width: "100%",
          height: "100%",
          ...cssVars,
        }}
      ></div>

      {/* 背景画像レイヤー */}
      <div
        className={`${className}__bg_image`}
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          width: "100%",
          height: "100%",
          // PC版設定
          "--background-image-pc": attributes.backgroundImagePC ? `url(${attributes.backgroundImagePC})` : "none",
          "--background-position-pc": attributes.backgroundImagePositionPC || "50% 50%",
          "--background-size-pc": attributes.backgroundImageSizePC || "cover",
          "--background-repeat-pc": attributes.backgroundImageRepeatPC || "no-repeat",
          // MD版設定
          "--background-image-md": attributes.backgroundImageMD ? `url(${attributes.backgroundImageMD})` : "none",
          "--background-position-md": attributes.backgroundImagePositionMD || "50% 50%",
          "--background-size-md": attributes.backgroundImageSizeMD || "cover",
          "--background-repeat-md": attributes.backgroundImageRepeatMD || "no-repeat",
          // TB版設定
          "--background-image-tb": attributes.backgroundImageTB ? `url(${attributes.backgroundImageTB})` : "none",
          "--background-position-tb": attributes.backgroundImagePositionTB || "50% 50%",
          "--background-size-tb": attributes.backgroundImageSizeTB || "cover",
          "--background-repeat-tb": attributes.backgroundImageRepeatTB || "no-repeat",
          // SP版設定
          "--background-image-sp": attributes.backgroundImageSP ? `url(${attributes.backgroundImageSP})` : "none",
          "--background-position-sp": attributes.backgroundImagePositionSP || "50% 50%",
          "--background-size-sp": attributes.backgroundImageSizeSP || "cover",
          "--background-repeat-sp": attributes.backgroundImageRepeatSP || "no-repeat",
        }}
      >
        {/* 背景画像のデバッグ情報を追加 */}
        {(() => {
          // console.log('=== BackgroundBasicRender bg_image layer ===');
          // console.log('backgroundImagePC:', attributes.backgroundImagePC);
          // console.log('backgroundImageSP:', attributes.backgroundImageSP);
          // console.log('CSS variables for bg_image:', {
          //   "--background-image-pc": attributes.backgroundImagePC ? `url(${attributes.backgroundImagePC})` : "none",
          //   "--background-position-pc": attributes.backgroundImagePositionPC || "50% 50%",
          //   "--background-size-pc": attributes.backgroundImageSizePC || "cover",
          //   "--background-repeat-pc": attributes.backgroundImageRepeatPC || "no-repeat",
          //   "--background-image-sp": attributes.backgroundImageSP ? `url(${attributes.backgroundImageSP})` : "none",
          //   "--background-position-sp": attributes.backgroundImagePositionSP || "50% 50%",
          //   "--background-size-sp": attributes.backgroundImageSizeSP || "cover",
          //   "--background-repeat-sp": attributes.backgroundImageRepeatSP || "no-repeat",
          // });
          // console.log('className for bg_image:', `${className}__bg_image`);
          return null;
        })()}
      </div>

      {/* 背景パターンレイヤー */}
      <div
        className={`${className}__bg_pattern`}
        style={{
          position: "absolute",
          top: 0,
          left: 0,
          width: "100%",
          height: "100%",
          // 通常の背景パターン設定（column-basic内でない場合）
          "--background-pattern-color-pc": attributes.backgroundPatternColorPC || "#e0e0e0",
          "--background-pattern-opacity-pc": `${attributes.backgroundPatternOpacityPC !== undefined ? attributes.backgroundPatternOpacityPC : 1}`,
          "--background-pattern-size-pc": `${attributes.backgroundPatternSizePC || 20}${attributes.backgroundPatternSizeUnitPC || "px"}`,
          "--background-pattern-rotate-pc": attributes.backgroundPatternRotatePC || 0,
          "--background-pattern-color-md": attributes.backgroundPatternColorMD || "#e0e0e0",
          "--background-pattern-opacity-md": `${attributes.backgroundPatternOpacityMD !== undefined ? attributes.backgroundPatternOpacityMD : 1}`,
          "--background-pattern-size-md": `${attributes.backgroundPatternSizeMD || 20}${attributes.backgroundPatternSizeUnitMD || "px"}`,
          "--background-pattern-rotate-md": attributes.backgroundPatternRotateMD || 0,
          "--background-pattern-color-tb": attributes.backgroundPatternColorTB || "#e0e0e0",
          "--background-pattern-opacity-tb": `${attributes.backgroundPatternOpacityTB !== undefined ? attributes.backgroundPatternOpacityTB : 1}`,
          "--background-pattern-size-tb": `${attributes.backgroundPatternSizeTB || 20}${attributes.backgroundPatternSizeUnitTB || "px"}`,
          "--background-pattern-rotate-tb": attributes.backgroundPatternRotateTB || 0,
          "--background-pattern-color-sp": attributes.backgroundPatternColorSP || "#e0e0e0",
          "--background-pattern-opacity-sp": `${attributes.backgroundPatternOpacitySP !== undefined ? attributes.backgroundPatternOpacitySP : 1}`,
          "--background-pattern-size-sp": `${attributes.backgroundPatternSizeSP || 20}${attributes.backgroundPatternSizeUnitSP || "px"}`,
          "--background-pattern-rotate-sp": attributes.backgroundPatternRotateSP || 0,
          // パターン表示制御
          display:
            (attributes.backgroundPatternTypePC && attributes.backgroundPatternTypePC !== "none") ||
            (attributes.backgroundPatternTypeMD && attributes.backgroundPatternTypeMD !== "none") ||
            (attributes.backgroundPatternTypeTB && attributes.backgroundPatternTypeTB !== "none") ||
            (attributes.backgroundPatternTypeSP && attributes.backgroundPatternTypeSP !== "none")
              ? "block"
              : "none",
        }}
        data-pattern-pc={attributes.backgroundPatternTypePC || "none"}
        data-pattern-md={attributes.backgroundPatternTypeMD || "none"}
        data-pattern-tb={attributes.backgroundPatternTypeTB || "none"}
        data-pattern-sp={attributes.backgroundPatternTypeSP || "none"}
        // column-basic内でのカードスタイル適用を示すクラスを追加
        {...(isInCardStyleProvider ? { "data-use-card-style": "true" } : {})}
      />
    </div>
  );
};

export default BackgroundBasicRender;
