import Sortable from "sortablejs";
import { CKEditorWrapper } from "../../common/form/wysiwyg/ckeditor";

// 型定義
type SortableContainer = HTMLElement & { __sortable?: Sortable };
type BlockType = "frame" | "content" | "image-with-text" | string;

// スタイル定数
const STYLE_CONSTANTS = {
  OVERLAY_BACKGROUND_COLOR: "rgba(239, 68, 68, 0.1)",
  WARNING_BACKGROUND_COLOR: "rgba(239, 68, 68, 0.9)",
  HIGHLIGHT_BACKGROUND_COLOR: "rgba(59, 130, 246, 0.1)",
  HIGHLIGHT_BORDER_COLOR: "rgba(59, 130, 246, 0.5)",
  WARNING_BORDER_COLOR: "rgba(239, 68, 68, 0.5)",
};

// CSS クラス定数
const CSS_CLASSES = {
  SORTABLE_GHOST: "sortable-ghost",
  SORTABLE_CHOSEN: "sortable-chosen",
  SORTABLE_DRAG: "sortable-drag",
  SORTABLE_DRAG_AREA: "sortable-drag-area",
  FRAME_DROP_ZONE: "frame-drop-zone",
  FRAME_DROP_ZONE_ACTIVE: "frame-drop-zone-active",
  FRAME_DROP_ZONE_FULL: "frame-drop-zone-full",
  WARNING_OVERLAY: "frame-block-limit-warning",
  WARNING_BG_OVERLAY: "frame-block-limit-warning-bg",
};

/**
 * ブロック管理クラス
 * 記事作成/編集画面でのブロック項目の追加・編集・並び替え機能を提供
 *
 * 主な機能:
 * - ブロックの追加・削除・並び替え
 * - 枠ブロック内のネストされたブロック管理
 * - ドラッグ&ドロップによる操作
 * - 上限チェック
 */
export class BlockManager {
  private currentFrameElement: HTMLElement | null = null;
  private blocksContainer!: HTMLElement;
  private addBlockBtn!: HTMLElement;
  // 全体の展開/折りたたみのためのクラス追加
  private expandAllBtn!: HTMLElement;
  private collapseAllBtn!: HTMLElement;

  private blockModal!: HTMLElement;
  private innerBlockModal!: HTMLElement;
  private closeModalBtn!: HTMLElement;
  private closeInnerModalBtn!: HTMLElement;
  private addBlockTypeBtns!: NodeListOf<HTMLElement>;
  private addInnerBlockTypeBtns!: NodeListOf<HTMLElement>;

  // ドラッグ&ドロップ関連
  private isDragging: boolean = false;

  // セレクタのキャッシュ
  private selectors = {
    container: "#blocks-container",
    addBtn: "#add-block-btn",
    blockModal: "#block-modal",
    innerBlockModal: "#inner-block-modal",
    closeModalBtn: "#close-modal-btn",
    closeInnerModalBtn: "#close-inner-modal-btn",
    addBlockTypeBtn: ".add-block-type-btn",
    addInnerBlockTypeBtn: ".add-inner-block-type-btn",
    // 全体の展開/折りたたみのキャッシュ追加
    expandAllBtn: ".expand-blocks-btn",
    collapseAllBtn: ".collapse-blocks-btn",

    // ブロック単位の展開/折りたたみのキャッシュ追加
    toggleBtn: ".toggle-block-btn",

    innerBlockBtn: ".add-inner-block-btn",
    frameContainer: ".frame-blocks-container",
    blockWrapper: ".block-wrapper",
    innerBlockWrapper: ".inner-block-wrapper",
    dragHandle: ".drag-handle",
    moveUpBtn: ".move-up-btn",
    moveDownBtn: ".move-down-btn",
    deleteBtn: ".delete-block-btn",
    ckeditorContainer: ".ck-editor",
    ckeditorContent: ".ck-content",
  };

  // Sortable設定の共通オプション
  private commonSortableOptions = {
    animation: 150,
    handle: ".drag-handle",
    ghostClass: CSS_CLASSES.SORTABLE_GHOST,
    chosenClass: CSS_CLASSES.SORTABLE_CHOSEN,
    dragClass: CSS_CLASSES.SORTABLE_DRAG,
    forceAutoScrollFallback: true,
    scrollSpeed: 30,
  };

  // 削除されたブロックIDを管理
  private deletedBlockIds: Set<number> = new Set();
  private deletedBlockIdsInput: HTMLInputElement | null = null;

  // ブロック数の上限設定
  private maxBlocks: number = 100; // デフォルト値
  private maxInnerBlocks: number = 10; // 枠内ブロックの上限

  /**
   * コンストラクタ
   */
  constructor() {
    if (!document.querySelector(this.selectors.container)) return;

    this.initCache();
    this.initStyles();
    this.initEventListeners();
    this.initMainSortable();
    this.loadBlockLimits();
    this.initExistingBlocks();
    this.initExistingContentBlocks();
    this.updateAddBlockButtonState();

    // 削除されたブロックID保持フィールドを取得
    this.deletedBlockIdsInput = document.getElementById(
      "deleted-block-ids"
    ) as HTMLInputElement;

    // 隠しフィールドに初期値がある場合はそれを読み込む
    this.initDeletedBlockIds();
  }

  /**
   * 要素キャッシュの初期化
   */
  private initCache(): void {
    // シングル要素のキャッシュ
    this.blocksContainer = document.querySelector(
      this.selectors.container
    ) as HTMLElement;
    this.addBlockBtn = document.querySelector(
      this.selectors.addBtn
    ) as HTMLElement;
    //  開閉ボタンのキャッシュ初期化
    this.expandAllBtn = document.querySelector(
      this.selectors.expandAllBtn
    ) as HTMLElement;
    this.collapseAllBtn = document.querySelector(
      this.selectors.collapseAllBtn
    ) as HTMLElement;

    this.blockModal = document.querySelector(
      this.selectors.blockModal
    ) as HTMLElement;
    this.innerBlockModal = document.querySelector(
      this.selectors.innerBlockModal
    ) as HTMLElement;
    this.closeModalBtn = document.querySelector(
      this.selectors.closeModalBtn
    ) as HTMLElement;
    this.closeInnerModalBtn = document.querySelector(
      this.selectors.closeInnerModalBtn
    ) as HTMLElement;

    // 複数要素のキャッシュ
    this.addBlockTypeBtns = document.querySelectorAll(
      this.selectors.addBlockTypeBtn
    );
    this.addInnerBlockTypeBtns = document.querySelectorAll(
      this.selectors.addInnerBlockTypeBtn
    );
  }

  /**
   * スタイルの初期化
   */
  private initStyles(): void {
    if (document.getElementById("block-manager-styles")) return;

    const style = document.createElement("style");
    style.id = "block-manager-styles";
    style.textContent = `
            .${CSS_CLASSES.SORTABLE_GHOST} { opacity: 0.4; border-radius: var(--radius-lg); }
            .${CSS_CLASSES.SORTABLE_CHOSEN} { border-radius: var(--radius-lg); }
            .${CSS_CLASSES.SORTABLE_DRAG} { opacity: 0.8; border-radius: var(--radius-lg); }
            .${CSS_CLASSES.FRAME_DROP_ZONE} {
                min-height: 100px;
                transition: all 0.2s ease;
                position: relative;
            }

            .${CSS_CLASSES.FRAME_DROP_ZONE_ACTIVE} {
                background-color: ${STYLE_CONSTANTS.HIGHLIGHT_BACKGROUND_COLOR};
                border: 2px dashed ${STYLE_CONSTANTS.HIGHLIGHT_BORDER_COLOR} !important;
                min-height: 120px !important;
                padding: 20px 5px !important;
                border-radius: var(--radius-lg);
            }

            .${CSS_CLASSES.FRAME_DROP_ZONE_FULL} {
                background-color: ${STYLE_CONSTANTS.OVERLAY_BACKGROUND_COLOR};
                border: 2px dashed ${STYLE_CONSTANTS.WARNING_BORDER_COLOR} !important;
                position: relative;
            }

            .${this.selectors.frameContainer}.${CSS_CLASSES.SORTABLE_DRAG_AREA} {
                background-color: ${STYLE_CONSTANTS.HIGHLIGHT_BACKGROUND_COLOR};
                border: 3px dashed ${STYLE_CONSTANTS.HIGHLIGHT_BORDER_COLOR};
                min-height: 110px;
                padding: 20px 4px;
            }

            #blocks-container.${CSS_CLASSES.SORTABLE_DRAG_AREA} {
                background-color: ${STYLE_CONSTANTS.HIGHLIGHT_BACKGROUND_COLOR};
                border: 2px dashed ${STYLE_CONSTANTS.HIGHLIGHT_BORDER_COLOR};
                padding: 4px;
            }

            [data-frame-drop-candidate="true"] {
                z-index: 1000;
            }
        `;
    document.head.appendChild(style);
  }

  /**
   * イベントリスナーの初期化
   */
  private initEventListeners(): void {
    // モーダル操作
    this.addBlockBtn.addEventListener("click", this.openBlockModal.bind(this));
    this.closeModalBtn.addEventListener(
      "click",
      this.closeBlockModal.bind(this)
    );
    this.closeInnerModalBtn.addEventListener(
      "click",
      this.closeInnerBlockModal.bind(this)
    );

    // モーダル外クリックでも閉じる
    this.blockModal.addEventListener("click", (e) => {
      if (e.target === this.blockModal) this.closeBlockModal();
    });

    this.innerBlockModal.addEventListener("click", (e) => {
      if (e.target === this.innerBlockModal) this.closeInnerBlockModal();
    });

    // 全体展開ボタンのクリックイベントを処理
    this.expandAllBtn.addEventListener("click", () => {
      this.expandAllBlockContents();
    });

    this.collapseAllBtn.addEventListener("click", () => {
      this.collapseAllBlockContents();
    });

    // ブロック追加ボタン
    this.addBlockTypeBtns.forEach((btn) => {
      btn.addEventListener("click", () => {
        const blockType = btn.dataset.blockType;
        if (blockType) {
          this.addBlock(blockType);
          this.closeBlockModal();
        }
      });
    });

    // 枠内ブロック追加ボタン
    this.addInnerBlockTypeBtns.forEach((btn) => {
      btn.addEventListener("click", () => {
        const blockType = btn.dataset.blockType;
        if (blockType && this.currentFrameElement) {
          this.addInnerBlock(blockType, this.currentFrameElement);
          this.closeInnerBlockModal();
        }
      });
    });

    // 枠内ブロック操作のイベント委任
    document.addEventListener("click", (e) => {
      const target = e.target as HTMLElement;
      const innerBlockBtn = target.closest(this.selectors.innerBlockBtn);

      if (innerBlockBtn) {
        const frameElement = target.closest(".block-item");
        if (frameElement) {
          this.currentFrameElement = frameElement as HTMLElement;
          this.innerBlockModal.classList.remove("hidden");
        }
      }
    });
  }

  /**
   * メインのSortable初期化
   */
  private initMainSortable(): void {
    const container = this.blocksContainer as SortableContainer;
    if (container.__sortable) {
      container.__sortable.destroy();
    }

    const sortableConfig = {
      ...this.commonSortableOptions,
      group: {
        name: "blocks",
        put: () => true,
      },
      onStart: this.sharedHandlers.onStart.bind(this),
      onMove: this.sharedHandlers.onMove.bind(this),
      onEnd: this.sharedHandlers.onEnd.bind(this),
    };

    const sortable = new Sortable(this.blocksContainer, sortableConfig);
    container.__sortable = sortable;
  }

  /**
   * Sortableで共有するイベントハンドラー
   */
  private sharedHandlers = {
    onStart: (evt: Sortable.SortableEvent) => {
      this.isDragging = true;
      this.highlightDropTargets(evt.item);

      // ドラッグ開始時にCKEditorを一時的に無効化
      this.toggleCKEditorInteraction(false);
    },

    onMove: (evt: Sortable.MoveEvent) => {
      if (!this.isDragging) return true;

      // 枠ブロックを枠内にドロップできないように制限
      if (this.isFrameBlock(evt.dragged) && evt.to !== this.blocksContainer) {
        return false;
      }

      // 枠内の上限チェック
      if (evt.to !== this.blocksContainer) {
        // 移動先が枠内の場合
        const frameContainer = evt.to as HTMLElement;
        // 現在の枠内ブロック数を取得
        const innerBlockCount = frameContainer.querySelectorAll(
          `${this.selectors.innerBlockWrapper}:not(.ui-sortable-placeholder)`
        ).length;

        // 既に上限に達していたら移動を許可しない
        if (innerBlockCount >= this.maxInnerBlocks) {
          return false;
        }
      }

      return true;
    },

    onEnd: (evt: Sortable.SortableEvent) => {
      this.resetDragState();

      // ドラッグ終了時にCKEditorを再有効化
      this.toggleCKEditorInteraction(true);

      // 移動後の処理
      if (evt.to !== evt.from) {
        if (evt.to === this.blocksContainer) {
          // 枠内から外への移動
          this.updateBlockNamesAfterMove(evt.item, null);

          // 移動元の枠ブロックのボタン状態を更新
          const frameElement = evt.from.closest(".block-item") as HTMLElement;
          if (frameElement) {
            this.updateInnerAddBlockButtonState(frameElement);
          }
        } else {
          // 枠外から枠内への移動
          const frameContainer = evt.to as HTMLElement;
          const parentIndex = frameContainer.getAttribute("data-parent-index");
          if (parentIndex) {
            this.updateBlockNamesAfterMove(evt.item, parentIndex);

            // 移動先の枠ブロックのボタン状態を更新
            const frameElement = frameContainer.closest(
              ".block-item"
            ) as HTMLElement;
            if (frameElement) {
              this.updateInnerAddBlockButtonState(frameElement);
            }
          }
        }

        // メイン追加ボタンの状態も更新
        this.updateAddBlockButtonState();
      }
    },
  };


  /**
   * CKEditorとの干渉を制御するためのインタラクションを制御
   * @param enable エディタの有効/無効を切り替え
   */
  private toggleCKEditorInteraction(enable: boolean): void {
    const editors = document.querySelectorAll(this.selectors.ckeditorContainer);

    if (editors.length === 0) return;

    editors.forEach((editor) => {
      const contentArea = editor.querySelector(this.selectors.ckeditorContent);
      if (!contentArea) return;

      if (enable) {
        // エディタを再有効化
        (contentArea as HTMLElement).style.pointerEvents = "";
      } else {
        // エディタを一時的に無効化
        (contentArea as HTMLElement).style.pointerEvents = "none";
      }
    });
  }

  /**
   * 要素が枠ブロックかどうかチェック（効率化）
   */
  private isFrameBlock(element: HTMLElement): boolean {
    if (element.dataset.blockType === "frame") return true;
    if (element.getAttribute("data-block-type") === "frame") return true;

    return (
      element.querySelector(".frame-block, [data-block-type='frame']") !== null
    );
  }

  /**
   * ドラッグ状態をリセット
   */
  private resetDragState(): void {
    this.isDragging = false;

    this.clearHighlightStyles();
    this.removeDropCandidateFlags();
    this.removeWarningOverlays();
    this.resetBlockOpacity();
  }

  /**
   * ハイライトスタイルをクリア
   */
  private clearHighlightStyles(): void {
    document
      .querySelectorAll(
        `.${CSS_CLASSES.SORTABLE_DRAG_AREA}, .${CSS_CLASSES.FRAME_DROP_ZONE_ACTIVE}, .${CSS_CLASSES.FRAME_DROP_ZONE_FULL}`
      )
      .forEach((el) => {
        el.classList.remove(
          CSS_CLASSES.SORTABLE_DRAG_AREA,
          CSS_CLASSES.FRAME_DROP_ZONE_ACTIVE,
          CSS_CLASSES.FRAME_DROP_ZONE_FULL
        );
      });
  }

  /**
   * 警告オーバーレイを削除
   */
  private removeWarningOverlays(): void {
    document
      .querySelectorAll(
        `.${CSS_CLASSES.WARNING_OVERLAY}, .${CSS_CLASSES.WARNING_BG_OVERLAY}`
      )
      .forEach((el) => {
        el.remove();
      });
  }

  /**
   * ブロック項目の透明度をリセット
   */
  private resetBlockOpacity(): void {
    document
      .querySelectorAll(this.selectors.innerBlockWrapper)
      .forEach((block) => {
        (block as HTMLElement).style.opacity = "";
      });
  }

  /**
   * 上限に達した枠へ警告オーバーレイを追加
   */
  private addWarningOverlay(container: HTMLElement): void {
    // 既存の警告オーバーレイを削除
    const existingOverlay = container.querySelector(
      `.${CSS_CLASSES.WARNING_OVERLAY}`
    );
    if (existingOverlay) {
      existingOverlay.remove();
    }
  }

  /**
   * ドロップ可能なコンテナすべてを取得
   */
  private getAllDropContainers(): HTMLElement[] {
    return [
      this.blocksContainer,
      ...(Array.from(
        document.querySelectorAll(this.selectors.frameContainer)
      ) as HTMLElement[]),
    ];
  }

  /**
   * ドロップ対象コンテナをハイライト表示
   */
  private highlightDropTargets(draggedItem: HTMLElement | null): void {
    if (!draggedItem) return;

    // 一旦すべてのハイライト削除
    this.resetDragState();
    this.isDragging = true; // resetで消されるので再設定

    // ドラッグ中の要素が枠ブロックかどうか判定
    const isFrameBlock = this.isFrameBlock(draggedItem);

    // コンテナをハイライト
    this.getAllDropContainers().forEach((container) => {
      if (isFrameBlock) {
        // 枠ブロックは枠外のみドロップ可能
        this.highlightContainerForFrameBlock(container);
      } else {
        // 通常ブロックは枠内外どちらもドロップ可能
        this.highlightContainerForNormalBlock(container);
      }
    });
  }

  /**
   * 枠ブロック用のコンテナハイライト処理
   */
  private highlightContainerForFrameBlock(container: HTMLElement): void {
    // 枠ブロックは枠外のみドロップ可能
    if (container === this.blocksContainer) {
      container.classList.add(CSS_CLASSES.SORTABLE_DRAG_AREA);
    }
  }

  /**
   * 通常ブロック用のコンテナハイライト処理
   */
  private highlightContainerForNormalBlock(container: HTMLElement): void {
    if (container !== this.blocksContainer) {
      // 枠内ブロック数をチェック
      const innerBlockCount = container.querySelectorAll(
        `${this.selectors.innerBlockWrapper}:not(.ui-sortable-placeholder)`
      ).length;

      if (innerBlockCount >= this.maxInnerBlocks) {
        // 上限に達している場合は特別なスタイルを適用
        container.classList.add(CSS_CLASSES.FRAME_DROP_ZONE_FULL);

        // 枠内の既存ブロックアイテムの上に半透明の警告マスクを追加
        this.addWarningOverlay(container);
      } else {
        // 通常のドラッグ対象スタイル
        container.classList.add(CSS_CLASSES.FRAME_DROP_ZONE_ACTIVE);
      }
    } else {
      container.classList.add(CSS_CLASSES.SORTABLE_DRAG_AREA);
    }
  }

  /**
   * モーダル操作メソッド
   */
  public openBlockModal(): void {
    this.blockModal.classList.remove("hidden");
  }

  public closeBlockModal(): void {
    this.blockModal.classList.add("hidden");
  }

  public closeInnerBlockModal(): void {
    this.innerBlockModal.classList.add("hidden");
  }

  /**
   * name属性のユニークインデックスを生成
   */
  public uniqueIndex(element: HTMLElement): number {
    let uniqueIndex = parseInt(
      element.getAttribute("data-unique-index") ?? "0",
      10
    );
    uniqueIndex = isNaN(uniqueIndex) ? 0 : uniqueIndex;
    uniqueIndex++;
    element.setAttribute("data-unique-index", uniqueIndex.toString());
    return uniqueIndex;
  }

  /**
   * メインコンテナにブロックを追加
   */
  public addBlock(blockType: BlockType): void {
    // 現在のブロック数を取得して上限チェック
    const blockCount = this.blocksContainer.querySelectorAll(
      `${this.selectors.blockWrapper}:not(.ui-sortable-placeholder)`
    ).length;

    if (blockCount >= this.maxBlocks) {
      alert(`ブロック数の上限(${this.maxBlocks})に達しました`);
      return;
    }

    const templateId = `block-template-${blockType}`;
    const template = document.getElementById(templateId);
    if (!template) return;

    // テンプレートの内容をクローン
    const index = this.uniqueIndex(this.blocksContainer);
    let content = template.innerHTML.replace(/\${index}/g, index.toString());

    // ブロック要素の作成と追加
    const blockWrapper = document.createElement("div");
    blockWrapper.className = "block-wrapper";
    blockWrapper.innerHTML = content;
    this.blocksContainer.appendChild(blockWrapper);
    this.setupBlockEventListeners(blockWrapper);

    // 枠ブロックの場合は内部のブロック管理も初期化
    if (blockType === "frame") {
      const frameContainer = blockWrapper.querySelector(
        this.selectors.frameContainer
      );
      if (frameContainer) {
        this.initFrameBlocksContainer(frameContainer as HTMLElement);
      }
    }

    // 本文の場合はCKEditorを初期化
    if (this.isContentBlock(blockType)) {
      this.initCKEditor(blockWrapper);
    }

    // ブロック追加後にボタン状態を更新
    this.updateAddBlockButtonState();
  }

  /**
   * コンテンツ編集ブロックかどうかを判定
   */
  private isContentBlock(blockType: BlockType): boolean {
    return blockType === "content" || blockType === "image-with-text";
  }

  /**
   * CKEditorを初期化
   */
  private initCKEditor(container: HTMLElement): void {
    const editorContainers = container.querySelectorAll(
      "textarea.ckeditor"
    ) as NodeListOf<HTMLElement>;

    if (!editorContainers.length) return;

    editorContainers.forEach((editorContainer) => {
      const editor = new CKEditorWrapper({
        container: editorContainer,
        placeholder: "入力してください...",
        height: "300px",
      });

      editor
        .init()
        .then(() => {
          (editorContainer as HTMLTextAreaElement & { __ckeditorInstance?: CKEditorWrapper }).__ckeditorInstance = editor;
          console.log("Editor initialized");
        })
        .catch((error) => {
          console.error("Editor initialization failed:", error);
        });
    });
  }

  /**
   * 枠内にブロックを追加
   */
  public addInnerBlock(blockType: BlockType, frameElement: HTMLElement): void {
    const templateId = `block-template-${blockType}`;
    const template = document.getElementById(templateId);
    const frameContainer = frameElement.querySelector(
      this.selectors.frameContainer
    ) as HTMLElement;
    const parentIndex = frameContainer?.getAttribute("data-parent-index");

    if (!template || !parentIndex || !frameContainer) return;

    // 現在の枠内ブロック数を取得して上限チェック
    const innerBlockCount = this.getInnerBlockCount(frameContainer);

    if (innerBlockCount >= this.maxInnerBlocks) {
      alert(`枠内ブロック数の上限(${this.maxInnerBlocks})に達しました`);
      return;
    }

    // 新しいインデックスを作成
    const innerIndex = this.uniqueIndex(frameContainer);

    // テンプレートの内容を処理
    let content = template.innerHTML
      .replace(/\${index}/g, innerIndex.toString())
      .replace(
        /blocks\[([^[]*)\]/g,
        `blocks[${parentIndex}][inner_blocks][$1]`
      );

    // ブロック要素の作成と追加
    const blockWrapper = document.createElement("div");
    blockWrapper.className = "block-wrapper inner-block-wrapper";
    blockWrapper.innerHTML = content;
    frameContainer.appendChild(blockWrapper);
    this.setupBlockEventListeners(blockWrapper);

    // 本文の場合はCKEditorを初期化
    if (this.isContentBlock(blockType)) {
      this.initCKEditor(blockWrapper);
    }

    // 枠内ブロック追加後にボタン状態を更新
    this.updateInnerAddBlockButtonState(frameElement);
  }

  /**
   * 枠ブロックコンテナの初期化
   */
  private initFrameBlocksContainer(container: HTMLElement): void {
    this.destroyExistingSortable(container);
    this.applySortableStyles(container);
    this.initFrameSortable(container);
    this.setupFrameAddButtonListeners(container);
  }

  /**
   * 既存のSortableインスタンスを破棄
   */
  private destroyExistingSortable(container: HTMLElement): void {
    const containerWithSortable = container as SortableContainer;
    if (containerWithSortable.__sortable) {
      containerWithSortable.__sortable.destroy();
    }
  }

  /**
   * コンテナにSortableのスタイルを適用
   */
  private applySortableStyles(container: HTMLElement): void {
    // 枠内の受け入れエリアを強調表示するクラスを追加
    container.classList.add(CSS_CLASSES.FRAME_DROP_ZONE);
  }

  /**
   * 枠内のSortableを初期化
   */
  private initFrameSortable(container: HTMLElement): void {
    const sortable = new Sortable(container, {
      ...this.commonSortableOptions,
      group: {
        name: "blocks",
        put: (to, from, dragEl) => {
          // 枠ブロックはドロップ拒否
          if (this.isFrameBlock(dragEl as HTMLElement)) return false;

          // 現在の枠内ブロック数を取得して上限チェック
          const innerBlockCount = this.getInnerBlockCount(container);

          // 既に上限に達していたらドロップ拒否
          if (innerBlockCount >= this.maxInnerBlocks) return false;

          // 枠内への直接ドロップを容易にするフラグ
          (dragEl as HTMLElement).setAttribute(
            "data-frame-drop-candidate",
            "true"
          );
          return true;
        },
      },
      // ドロップエリアを広げる
      emptyInsertThreshold: 10,
      onStart: this.sharedHandlers.onStart.bind(this),
      onMove: (evt: Sortable.MoveEvent) => {
        if (!this.isDragging) return true;

        // 枠内ドロップゾーンを強調表示
        container.classList.add(CSS_CLASSES.FRAME_DROP_ZONE_ACTIVE);

        // 現在の枠内ブロック数を取得して上限チェック
        const innerBlockCount = this.getInnerBlockCount(container);

        // 既に上限に達していたら移動を許可しない
        if (innerBlockCount >= this.maxInnerBlocks && evt.from !== container) {
          return false;
        }

        return !this.isFrameBlock(evt.dragged); // 枠ブロックは禁止
      },
      onEnd: this.sharedHandlers.onEnd.bind(this),
    });

    (container as SortableContainer).__sortable = sortable;
  }

  /**
   * 枠内ブロック数を計算
   */
  private getInnerBlockCount(container: HTMLElement): number {
    return container.querySelectorAll(
      `${this.selectors.innerBlockWrapper}:not(.ui-sortable-placeholder)`
    ).length;
  }

  // ブロック単位の表示/非表示制御
  private expandBlockContent(blockWrapper: HTMLElement): void {
    const inputArea = blockWrapper.querySelector(".input-area") as HTMLElement | null;
    if (!inputArea) {
      return;
    }

    inputArea.classList.remove("hidden");
  }

  private collapseBlockContent(blockWrapper: HTMLElement): void {
    const inputArea = blockWrapper.querySelector(".input-area") as HTMLElement | null;
    if (!inputArea) {
      return;
    }

    inputArea.classList.add("hidden");
  }

  private toggleBlockContent(blockWrapper: HTMLElement): void {
    const inputArea = blockWrapper.querySelector(".input-area") as HTMLElement | null;
    if (!inputArea) {
      return;
    }

    if (inputArea.classList.contains("hidden")) {
      this.expandBlockContent(blockWrapper);
      return;
    }

    this.collapseBlockContent(blockWrapper);
  }

  // 全体展開処理
  private expandAllBlockContents(): void {
    const inputAreas = this.blocksContainer.querySelectorAll(".input-area");
    if (inputAreas.length === 0) return;

    this.blocksContainer.querySelectorAll(".input-area").forEach((inputArea) => {
      (inputArea as HTMLElement).classList.remove("hidden");
    });
    this.expandAllBtn.style.display = "none";
    this.collapseAllBtn.style.display = "";
  }

  // 全体折りたたみ処理
  private collapseAllBlockContents(): void {
    const inputAreas = this.blocksContainer.querySelectorAll(".input-area");
    if (inputAreas.length === 0) return;
    
    this.blocksContainer.querySelectorAll(".input-area").forEach((inputArea) => {
      (inputArea as HTMLElement).classList.add("hidden");
    });
    this.expandAllBtn.style.display = "";
    this.collapseAllBtn.style.display = "none";
  }




  /**
   * 枠内追加ボタンのリスナー設定
   */
  private setupFrameAddButtonListeners(container: HTMLElement): void {
    const frameElement = container.closest(".block-item") as HTMLElement;
    const addBtn = frameElement?.querySelector(
      this.selectors.innerBlockBtn
    ) as HTMLElement;

    if (addBtn) {
      const newAddBtn = addBtn.cloneNode(true) as HTMLElement;
      if (addBtn.parentNode) {
        addBtn.parentNode.replaceChild(newAddBtn, addBtn);
        newAddBtn.addEventListener("click", () => {
          this.currentFrameElement = frameElement;
          this.innerBlockModal.classList.remove("hidden");
        });
      }

      // 初期状態でボタン状態を設定
      this.updateInnerAddBlockButtonState(frameElement);
    }
  }

  /**
   * 削除されたブロックIDを管理対象に追加
   */
  private addDeletedBlockId(blockId: number | string): void {
    if (!blockId || !this.deletedBlockIdsInput) return;

    // 数値に変換
    const id = parseInt(blockId.toString(), 10);
    if (isNaN(id)) return;

    // IDを追加して更新
    this.deletedBlockIds.add(id);
    this.updateDeletedBlockIdsInput();
  }

  /**
   * 削除されたブロックIDリストを隠しフィールドに反映
   */
  private updateDeletedBlockIdsInput(): void {
    if (!this.deletedBlockIdsInput) return;

    // カンマ区切りのIDリストに変換
    const idList = Array.from(this.deletedBlockIds).join(",");
    this.deletedBlockIdsInput.value = idList;
  }

  /**
   * 削除されたブロックIDの初期値を読み込む
   */
  private initDeletedBlockIds(): void {
    if (!this.deletedBlockIdsInput) return;

    const initialValue = this.deletedBlockIdsInput.value;
    if (initialValue && initialValue.trim() !== "") {
      // カンマ区切りの値を配列に分割してから数値に変換
      const ids = initialValue
        .split(",")
        .map((id) => parseInt(id.trim(), 10))
        .filter((id) => !isNaN(id));

      // セットに追加
      ids.forEach((id) => this.deletedBlockIds.add(id));
    }
  }

  /**
   * ブロックが移動した後にname属性を更新
   */
  private updateBlockNamesAfterMove(
    blockElement: HTMLElement,
    newParentIndex: string | null
  ): void {
    // data-block-type属性を設定
    if (!blockElement.hasAttribute("data-block-type")) {
      const blockItem = blockElement.querySelector(".block-item");
      if (blockItem?.hasAttribute("data-block-type")) {
        blockElement.setAttribute(
          "data-block-type",
          blockItem.getAttribute("data-block-type") || ""
        );
      }
    }

    // 入力要素の名前を更新
    const inputs = blockElement.querySelectorAll("input, select, textarea");

    // 枠外に移動した場合
    if (newParentIndex === null) {
      // index 取得
      const index = this.uniqueIndex(this.blocksContainer);

      inputs.forEach((input) => {
        const name = input.getAttribute("name");
        if (!name) return;

        const newName = name.replace(
          /blocks\[\d+\]\[inner_blocks\]\[\d+\]/,
          `blocks[${index}]`
        );

        input.setAttribute("name", newName);
      });
    }
    // 枠内に移動した場合
    else {
      // index 取得
      const frameContainer = blockElement.closest(
        this.selectors.frameContainer
      ) as HTMLElement;
      const childIndex = this.uniqueIndex(frameContainer);

      inputs.forEach((input) => {
        const name = input.getAttribute("name");
        if (!name) return;

        let newName;
        if (name.includes("[inner_blocks]")) {
          // 枠内から別の枠内への移動
          newName = name.replace(
            /blocks\[\d+\]\[inner_blocks\]\[\d+\]/,
            `blocks[${newParentIndex}][inner_blocks][${childIndex}]`
          );
        } else {
          // 枠外から枠内への移動
          newName = name.replace(
            /blocks\[\d+\]/,
            `blocks[${newParentIndex}][inner_blocks][${childIndex}]`
          );
        }

        input.setAttribute("name", newName);
      });
    }
  }

  /**
   * DOMツリーにAlpineを初期化（存在する場合）
   */
  private initAlpine(element: HTMLElement): void {
    // グローバルAlpineオブジェクトがあれば初期化
    if (typeof window !== "undefined" && (window as any).Alpine) {
      (window as any).Alpine.initTree(element);
    } else {
      // Alpineが利用できない場合はコンソールにメッセージを出す
      console.log("Alpine.js not found, skipping initialization");
    }
  }

  /**
   * ブロックのイベントリスナーをセットアップ
   */
  private setupBlockEventListeners(blockWrapper: HTMLElement): void {
    // 削除ボタン
    const deleteBtn = blockWrapper.querySelector(this.selectors.deleteBtn);
    if (deleteBtn) {
      // 既存のイベントリスナーを全て削除して新しく追加
      const oldBtn = deleteBtn.cloneNode(true) as HTMLElement;
      if (deleteBtn.parentNode) {
        deleteBtn.parentNode.replaceChild(oldBtn, deleteBtn);
      }

      // 新しいイベントリスナーを設定
      oldBtn.addEventListener("click", (e) => {
        // イベントの伝播を停止して、親要素のハンドラーが発火するのを防止
        e.stopPropagation();

        if (confirm("このブロックを削除してもよろしいですか？")) {
          // 削除前に関連する枠要素を取得
          let frameElement: HTMLElement | null = null;

          // 削除するのが内部ブロックの場合は親の枠を取得
          if (
            blockWrapper.classList.contains(
              this.selectors.innerBlockWrapper.substring(1)
            )
          ) {
            frameElement = blockWrapper.closest(".block-item") as HTMLElement;
          }

          // ブロックのIDを取得
          const blockItem = blockWrapper.querySelector(".block-item");
          const blockId = blockItem?.getAttribute("data-block-id");

          // IDがある場合は削除リストに追加
          if (blockId) {
            this.addDeletedBlockId(blockId);
          }

          // 枠ブロック内の項目についても処理
          const innerBlocks = blockWrapper.querySelectorAll("[data-block-id]");
          innerBlocks.forEach((block) => {
            const innerId = block.getAttribute("data-block-id");
            if (innerId) {
              this.addDeletedBlockId(innerId);
            }
          });

          // ブロック要素を削除
          blockWrapper.remove();

          // ブロック追加ボタンの状態を更新
          this.updateAddBlockButtonState();

          // 削除されたのが枠内ブロックの場合、親の枠ブロックのボタン状態を更新
          if (frameElement) {
            this.updateInnerAddBlockButtonState(frameElement);
          }
        }
      });
    }

    // 上に移動ボタン
    const moveUpBtn = blockWrapper.querySelector(this.selectors.moveUpBtn);
    if (moveUpBtn) {
      // 既存のイベントリスナーを全て削除して新しく追加
      const oldBtn = moveUpBtn.cloneNode(true) as HTMLElement;
      if (moveUpBtn.parentNode) {
        moveUpBtn.parentNode.replaceChild(oldBtn, moveUpBtn);
      }

      oldBtn.addEventListener("click", (e) => {
        // イベントの伝播を停止して、親要素のハンドラーが発火するのを防止
        e.stopPropagation();

        const parent = blockWrapper.parentNode as HTMLElement;
        const prevBlock = blockWrapper.previousElementSibling;
        if (prevBlock) {
          parent.insertBefore(blockWrapper, prevBlock);
        }
      });
    }

    // 下に移動ボタン
    const moveDownBtn = blockWrapper.querySelector(this.selectors.moveDownBtn);
    if (moveDownBtn) {
      // 既存のイベントリスナーを全て削除して新しく追加
      const oldBtn = moveDownBtn.cloneNode(true) as HTMLElement;
      if (moveDownBtn.parentNode) {
        moveDownBtn.parentNode.replaceChild(oldBtn, moveDownBtn);
      }

      oldBtn.addEventListener("click", (e) => {
        // イベントの伝播を停止して、親要素のハンドラーが発火するのを防止
        e.stopPropagation();

        const parent = blockWrapper.parentNode as HTMLElement;
        const nextBlock = blockWrapper.nextElementSibling;
        if (nextBlock) {
          parent.insertBefore(nextBlock, blockWrapper);
        }
      });
    }

    // ブロック単位の展開/折りたたみ処理
    const toggleBtn = blockWrapper.querySelector(this.selectors.toggleBtn);
    if (toggleBtn) {
      const oldBtn = toggleBtn.cloneNode(true) as HTMLElement;
      if (toggleBtn.parentNode) {
        toggleBtn.parentNode.replaceChild(oldBtn, toggleBtn);
      }

      oldBtn.addEventListener("click", (e) => {
        e.stopPropagation();
        this.toggleBlockContent(blockWrapper);
      });
    }

    this.initAlpine(blockWrapper);
  }

  /**
   * 既存のブロック項目を初期化
   */
  private initExistingBlocks(): void {
    // メインコンテナの既存ブロックにイベントリスナーを設定
    this.blocksContainer
      .querySelectorAll(this.selectors.blockWrapper)
      .forEach((block) => {
        this.setupBlockEventListeners(block as HTMLElement);
      });

    // 既存の枠ブロックコンテナを初期化
    const frameContainers = this.blocksContainer.querySelectorAll(
      this.selectors.frameContainer
    );
    frameContainers.forEach((container) => {
      this.initFrameBlocksContainer(container as HTMLElement);

      // 枠内の既存ブロックも初期化 (直接子要素のみ)
      Array.from(container.children)
        .filter((child) => child.classList.contains("inner-block-wrapper"))
        .forEach((innerBlock) => {
          this.setupBlockEventListeners(innerBlock as HTMLElement);
        });
    });

    // 初期化後にボタン状態も更新
    this.updateAddBlockButtonState();

    // 既存の枠ブロックの「枠内項目を追加」ボタン状態も更新
    document
      .querySelectorAll('div[data-block-type="frame"]')
      .forEach((frame) => {
        this.updateInnerAddBlockButtonState(frame as HTMLElement);
      });
  }

  /**
   * 既存の本文ブロックを初期化
   */
  private initExistingContentBlocks(): void {
    const contentBlocks =
      this.blocksContainer.querySelectorAll("textarea.ckeditor");
    contentBlocks.forEach((block) => {
      const editor = new CKEditorWrapper({
        container: block as HTMLElement,
        placeholder: "入力してください...",
        height: "300px",
      });

      editor
        .init()
        .then(() => {
          (block as HTMLTextAreaElement & { __ckeditorInstance?: CKEditorWrapper }).__ckeditorInstance = editor;
          console.log("Editor initialized");
        })
        .catch((error) => {
          console.error("Editor initialization failed:", error);
        });
    });
  }

  /**
   * 上限値を読み込む
   */
  private loadBlockLimits(): void {
    const container = this.blocksContainer;
    if (!container) return;

    // data属性から上限値を読み込む
    const maxBlocks = container.getAttribute("data-max-blocks");
    const maxInnerBlocks = container.getAttribute("data-max-inner-blocks");

    if (maxBlocks) {
      const limit = parseInt(maxBlocks, 10);
      if (!isNaN(limit) && limit > 0) {
        this.maxBlocks = limit;
      }
    }

    if (maxInnerBlocks) {
      const limit = parseInt(maxInnerBlocks, 10);
      if (!isNaN(limit) && limit > 0) {
        this.maxInnerBlocks = limit;
      }
    }
  }

  /**
   * ブロック追加ボタンの状態を更新
   */
  private updateAddBlockButtonState(): void {
    if (!this.addBlockBtn) return;

    // 現在のブロック数を取得
    const blockCount = this.blocksContainer.querySelectorAll(
      `${this.selectors.blockWrapper}:not(.ui-sortable-placeholder)`
    ).length;

    // 上限に達したかチェック
    if (blockCount >= this.maxBlocks) {
      this.addBlockBtn.setAttribute("disabled", "disabled");
      this.addBlockBtn.classList.add("opacity-50", "cursor-not-allowed");

      // ツールチップまたはヒントを追加
      this.addBlockBtn.setAttribute(
        "title",
        `ブロック数の上限(${this.maxBlocks})に達しました`
      );
    } else {
      this.addBlockBtn.removeAttribute("disabled");
      this.addBlockBtn.classList.remove("opacity-50", "cursor-not-allowed");
      this.addBlockBtn.setAttribute("title", "ブロック項目を追加");
    }
  }

  /**
   * 枠内ブロック追加ボタンの状態を更新
   */
  private updateInnerAddBlockButtonState(frameElement: HTMLElement): void {
    if (!frameElement) return;

    const frameContainer = frameElement.querySelector(
      this.selectors.frameContainer
    ) as HTMLElement;
    if (!frameContainer) return;

    // addBtnの検索方法を改善
    // 枠コンテナの親要素内から検索する代わりに、枠ブロック自体から検索
    const addBtn = frameElement.querySelector(
      this.selectors.innerBlockBtn
    ) as HTMLElement;
    if (!addBtn) return;

    // 現在の枠内ブロック数を取得
    const innerBlockCount = frameContainer.querySelectorAll(
      `${this.selectors.innerBlockWrapper}:not(.ui-sortable-placeholder)`
    ).length;

    // 上限に達したかチェック
    if (innerBlockCount >= this.maxInnerBlocks) {
      addBtn.setAttribute("disabled", "disabled");
      addBtn.classList.add("opacity-50", "cursor-not-allowed");
      addBtn.setAttribute(
        "title",
        `枠内ブロック数の上限(${this.maxInnerBlocks})に達しました`
      );
    } else {
      // ボタンが無効になっている場合に確実に有効化
      addBtn.removeAttribute("disabled");
      addBtn.classList.remove("opacity-50", "cursor-not-allowed");
      addBtn.setAttribute("title", "枠内項目を追加");
    }
  }

  /**
   * ドロップ候補フラグを削除
   */
  private removeDropCandidateFlags(): void {
    document.querySelectorAll("[data-frame-drop-candidate]").forEach((el) => {
      el.removeAttribute("data-frame-drop-candidate");
    });
  }
}

// 遅延初期化
if (document.readyState === "loading") {
  document.addEventListener("DOMContentLoaded", () => new BlockManager());
} else {
  new BlockManager();
}
