// 悬浮小圆圈：可拖动、位置持久化、点击（非拖动）打开铺货面板

const FLOAT_BTN_POS_KEY = 'qe_float_btn_pos_v1';

function createFloatButton() {
  try {
    const currentUrl = window.location.href;
    if (!currentUrl.startsWith('https://www.ozon.ru/') && !currentUrl.startsWith('https://ozon.kz/')) {
      return;
    }
    if (!document.body) {
      setTimeout(createFloatButton, 100);
      return;
    }
    if (document.querySelector('.qe-float-btn')) return;

    let wrapper = document.querySelector('.qe-float-wrapper');
    if (!wrapper) {
      wrapper = document.createElement('div');
      wrapper.className = 'qe-float-wrapper';
      document.body.appendChild(wrapper);

      // Restore saved position if present
      const saved = safeParseJSON(localStorage.getItem(FLOAT_BTN_POS_KEY));
      if (saved && isFinite(saved.x) && isFinite(saved.y)) {
        applyPosition(wrapper, saved.x, saved.y);
      }
    }

    const btn = document.createElement('div');
    btn.className = 'qe-float-btn float-distributing-goods';
    btn.title = '一键铺货（拖动可移动位置）';
    // Use logo (shipped as web_accessible_resources img/*.png)
    try {
      const img = document.createElement('img');
      img.src = chrome.runtime.getURL('img/icon_64.png');
      img.alt = 'qe';
      img.draggable = false;
      btn.appendChild(img);
    } catch (_) {
      btn.textContent = '🐼';
    }

    wrapper.appendChild(btn);
    attachDragAndClick(btn, wrapper);
  } catch (e) {
    console.error('创建悬浮按钮失败:', e);
  }
}

function safeParseJSON(s) {
  try { return s ? JSON.parse(s) : null; } catch (_) { return null; }
}

function applyPosition(el, x, y) {
  const vw = window.innerWidth, vh = window.innerHeight;
  const rect = el.getBoundingClientRect();
  const w = rect.width || 48;
  const h = rect.height || 48;
  x = Math.min(Math.max(0, x), vw - w);
  y = Math.min(Math.max(0, y), vh - h);
  el.style.left = x + 'px';
  el.style.top = y + 'px';
  el.style.right = 'auto';
  el.style.bottom = 'auto';
  el.style.transform = 'none';
}

function attachDragAndClick(btn, wrapper) {
  let dragging = false;
  let moved = false;
  let startX = 0, startY = 0;
  let offX = 0, offY = 0;
  const THRESHOLD = 4; // px of movement before we count as a drag

  btn.addEventListener('pointerdown', (e) => {
    dragging = true;
    moved = false;
    const rect = wrapper.getBoundingClientRect();
    startX = e.clientX;
    startY = e.clientY;
    offX = e.clientX - rect.left;
    offY = e.clientY - rect.top;
    btn.setPointerCapture(e.pointerId);
    btn.classList.add('qe-float-btn--dragging');
  });

  btn.addEventListener('pointermove', (e) => {
    if (!dragging) return;
    const dx = e.clientX - startX;
    const dy = e.clientY - startY;
    if (!moved && Math.hypot(dx, dy) > THRESHOLD) moved = true;
    if (moved) {
      applyPosition(wrapper, e.clientX - offX, e.clientY - offY);
    }
  });

  const endDrag = (e) => {
    if (!dragging) return;
    dragging = false;
    btn.classList.remove('qe-float-btn--dragging');
    try { btn.releasePointerCapture(e.pointerId); } catch (_) {}
    if (moved) {
      const rect = wrapper.getBoundingClientRect();
      try {
        localStorage.setItem(FLOAT_BTN_POS_KEY, JSON.stringify({ x: rect.left, y: rect.top }));
      } catch (_) {}
    } else {
      openSkuPanel();
    }
  };
  btn.addEventListener('pointerup', endDrag);
  btn.addEventListener('pointercancel', endDrag);

  // Keep in view on resize
  window.addEventListener('resize', () => {
    const rect = wrapper.getBoundingClientRect();
    applyPosition(wrapper, rect.left, rect.top);
  });
}

function openSkuPanel() {
  try {
    chrome.runtime.sendMessage({ type: 'FLOAT_BUTTON_CLICKED' });
    let iframe = document.getElementById('distributing-goods-iframe');
    if (iframe) return; // already open
    iframe = document.createElement('iframe');
    iframe.src = chrome.runtime.getURL('html/adtnfosku.html');
    iframe.className = 'distributing-goods-layer';
    iframe.id = 'distributing-goods-iframe';
    document.body.appendChild(iframe);
    iframe.onload = () => {
      iframe.contentWindow.postMessage({ type: 'SET_PRODUCT_URL', url: window.location.href }, '*');
    };
  } catch (e) {
    console.error('打开铺货面板失败:', e);
  }
}

// Iframe close-message relay (unchanged behavior, minus the dead createFallbackCloseButton pathway)
window.addEventListener('message', function (event) {
  const iframe = document.getElementById('distributing-goods-iframe');
  if (event.origin.startsWith('chrome-extension://') && event.data && event.data.type === 'CLOSE_IFRAME') {
    if (iframe && iframe.parentNode) iframe.parentNode.removeChild(iframe);
  }
});

var isshowBox = true;
var hrefUrl = window.location.href;
var platformInfo = MatchingPlatform(hrefUrl);

if (platformInfo.PlatformId > 0) {
  if (platformInfo.CrawlType == 'detail') {
    if (platformInfo.PlatformId == 9) {
      isshowBox = hrefUrl.indexOf('product/') !== -1 || hrefUrl.indexOf('-i.') !== -1;
    }
    if (platformInfo.PlatformId === 21) {
      isshowBox =
        /-g-[0-9]*\.html/.test(hrefUrl) ||
        hrefUrl.indexOf('goods.html') !== -1 ||
        hrefUrl.indexOf('psurl.html') !== -1 ||
        hrefUrl.indexOf('goods_id') !== -1;
    }
    if (platformInfo.PlatformId == 29 || platformInfo.PlatformId == 30 || platformInfo.PlatformId == 27) {
      isshowBox = platformInfo.isDetail;
    }
    if (isshowBox) ShowBottomRightMenu();
  }
}

function ShowBottomRightMenu() {
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', createFloatButton);
  } else {
    setTimeout(createFloatButton, 0);
  }
}
