// 今いるページのホスト名を取得
const currentHost = location.hostname;

// 除外したいホスト名のリスト
const excludedDomains = [
  /^[^.]+\.google\.com$/,  // 例: www.google.com, mail.google.com
  /^www\.canva\.com$/,     // 例: www.canva.com を明示的に除外
  /^chatgpt\.com$/,        // 例: chatgpt.com を明示的に除外
  /^chatwork\.com$/,       // 例: chatwork.com を明示的に除外 
  /^app\.slack\.com$/      // 例: slack.com を明示的に除外
];

// 除外ドメインなら何もしない
if (excludedDomains.includes(currentHost)) {
  console.log("Drag scroll script is disabled on this domain:", currentHost);
} else {
  // ↓↓↓ ここからすべて関数に包む ↓↓↓
  (function () {
    let isDragging = false;
    let startX, startY;
    let startScrollLeft, startScrollTop;
    let pageHeight, pageWidth;
    let viewportHeight, viewportWidth;

    // 初期状態をOFFに設定
    if (localStorage.getItem("dragScrollEnabled") === null) {
      localStorage.setItem("dragScrollEnabled", "false");
    }

    function isDragScrollEnabled() {
      return localStorage.getItem("dragScrollEnabled") === "true";
    }

    function isReversed() {
      return localStorage.getItem("dragScrollReverse") === "true";
    }

    function toggleDragScroll() {
      const current = isDragScrollEnabled();
      localStorage.setItem("dragScrollEnabled", current ? "false" : "true");
      const status = current ? "オフ" : "オン";
      console.log(`ドラッグスクロール: ${status}`);
    }

    // ダブルクリックでON/OFF切替
    document.addEventListener('dblclick', (e) => {
      if (e.target.closest('input, textarea, select, button, a, [contenteditable="true"]')) return;
      toggleDragScroll();
    });

    document.addEventListener('mousedown', (e) => {
      if (!isDragScrollEnabled()) return;
      if (e.ctrlKey || e.button !== 0 || e.target.closest('input, textarea, a, button, select')) return;

      isDragging = true;
      startX = e.clientX;
      startY = e.clientY;
      startScrollLeft = window.scrollX;
      startScrollTop = window.scrollY;

      pageHeight = document.documentElement.scrollHeight;
      pageWidth = document.documentElement.scrollWidth;
      viewportHeight = window.innerHeight;
      viewportWidth = window.innerWidth;

      e.preventDefault();
    });

    document.addEventListener('mousemove', (e) => {
      if (!isDragging || !isDragScrollEnabled() || e.ctrlKey) return;

      const dx = e.clientX - startX;
      const dy = e.clientY - startY;

      const reverseFactor = isReversed() ? -1 : 1;

      const scrollX = startScrollLeft + dx * (pageWidth - viewportWidth) / viewportWidth * reverseFactor;
      const scrollY = startScrollTop + dy * (pageHeight - viewportHeight) / viewportHeight * reverseFactor;

      window.scrollTo(scrollX, scrollY);
    });

    document.addEventListener('mouseup', () => {
      isDragging = false;
    });
  })();
  // ↑↑↑ 関数ラップここまで ↑↑↑
}
