import { getEnabledBreakpoints } from "../../../core/breakpoints";

const getSpacingValueV2 = (data, device, position) => {
  if (!data) return null;

  const enabledBreakpoints = getEnabledBreakpoints();
  const currentIndex = enabledBreakpoints.indexOf(device);

  for (let i = currentIndex; i >= 0; i--) {
    const bp = enabledBreakpoints[i];
    const bpData = data[bp];
    if (bpData) {
      const useIndividual = bpData.useIndividual;
      const key = useIndividual ? position : "bulk";
      const unitKey = `${key}Unit`;
      const unit = bpData[unitKey] || "px";

      if (unit === "auto") return "auto";

      const value = bpData[key];
      if (value !== "" && value !== undefined && value !== null) {
        return `${value}${unit}`;
      }
    }
  }

  return null;
};

const getDirectSpacingV2 = (data, device, position) => {
  if (!data || !data[device]) return null;

  const bpData = data[device];
  const useIndividual = bpData.useIndividual;

  if (useIndividual) {
    const unit = bpData[`${position}Unit`] || "px";
    if (unit === "auto") return "auto";
    const value = bpData[position];
    if (value !== "" && value !== undefined && value !== null) {
      return `${value}${unit}`;
    }
  } else {
    const bulkUnit = bpData.bulkUnit || "px";
    if (bulkUnit === "auto") return "auto";
    const bulkValue = bpData.bulk;
    if (bulkValue !== "" && bulkValue !== undefined && bulkValue !== null) {
      return `${bulkValue}${bulkUnit}`;
    }
  }

  return null;
};

/**
 * save.js用: PC用CSS変数のみ出力
 * MD/TB/SP用はPHP CSSのフォールバックに任せる
 */
export const getSpacingStyles = (attributes) => {
  if (!attributes) return {};

  const styles = {};
  const paddingData = attributes.paddingV2;
  const marginData = attributes.marginV2;
  const enabledBreakpoints = getEnabledBreakpoints();

  ["top", "right", "bottom", "left"].forEach((position) => {
    enabledBreakpoints.forEach((bp, index) => {
      const isPC = index === 0;

      // PC用CSS変数のみインラインスタイルに出力
      if (isPC) {
        const paddingValue = getDirectSpacingV2(paddingData, bp, position);
        if (paddingValue !== null) {
          styles[`--spacing-padding-${position}-${bp}`] = paddingValue;
        }

        const marginValue = getDirectSpacingV2(marginData, bp, position);
        if (marginValue !== null) {
          styles[`--spacing-margin-${position}-${bp}`] = marginValue;
        }
      }
    });
  });

  return styles;
};

/**
 * edit.js用: PC変数のみ出力、値はプレビューデバイスに応じて変更
 * インラインスタイルの肥大化を防ぎつつ、プレビュー機能に対応
 *
 * @param {Object} attributes - ブロック属性
 * @param {string} previewDevice - プレビューデバイス ('pc', 'md', 'tb', 'sp')
 */
export const getSpacingStylesForEditor = (attributes, previewDevice = "pc") => {
  if (!attributes) return {};

  const styles = {};
  const paddingData = attributes.paddingV2;
  const marginData = attributes.marginV2;

  ["top", "right", "bottom", "left"].forEach((position) => {
    // プレビューデバイスに応じた値を取得（フォールバック付き）
    const paddingValue = getSpacingValueV2(paddingData, previewDevice, position);
    if (paddingValue !== null) {
      // PC変数名で出力、値はプレビューデバイスの値
      styles[`--spacing-padding-${position}-pc`] = paddingValue;
    }

    const marginValue = getSpacingValueV2(marginData, previewDevice, position);
    if (marginValue !== null) {
      styles[`--spacing-margin-${position}-pc`] = marginValue;
    }
  });

  return styles;
};

export const getPaddingValue = (attributes, device = "pc", position = "bulk") => {
  return getSpacingValueV2(attributes.paddingV2, device, position) || "0px";
};

export const getMarginValue = (attributes, device = "pc", position = "bulk") => {
  return getSpacingValueV2(attributes.marginV2, device, position) || "0px";
};

export const getDirectPadding = (attributes, device = "pc", position = "bulk") => {
  return getDirectSpacingV2(attributes.paddingV2, device, position);
};

export const getDirectMargin = (attributes, device = "pc", position = "bulk") => {
  return getDirectSpacingV2(attributes.marginV2, device, position);
};
