(() => {
  const HOST_ID = 'one-pass-floating-host';
  const existing = document.getElementById(HOST_ID);
  if (existing) {
    existing.style.display = existing.style.display === 'none' ? 'block' : 'none';
    return;
  }

  const host = document.createElement('div');
  host.id = HOST_ID;
  host.style.position = 'fixed';
  host.style.top = '70px';
  host.style.right = '32px';
  host.style.width = '430px';
  host.style.height = '640px';
  host.style.maxWidth = 'calc(100vw - 32px)';
  host.style.maxHeight = 'calc(100vh - 32px)';
  host.style.zIndex = '2147483646';
  host.style.borderRadius = '14px';
  host.style.boxShadow = '0 18px 36px rgba(0,0,0,0.35)';
  host.style.overflow = 'hidden';
  host.style.background = '#fff';

  const dragBar = document.createElement('div');
  dragBar.style.height = '36px';
  dragBar.style.display = 'flex';
  dragBar.style.alignItems = 'center';
  dragBar.style.justifyContent = 'space-between';
  dragBar.style.padding = '0 10px';
  dragBar.style.background = 'linear-gradient(145deg, #003da5, #0055b8)';
  dragBar.style.color = '#fff';
  dragBar.style.fontFamily = 'Segoe UI, Arial, sans-serif';
  dragBar.style.fontSize = '13px';
  dragBar.style.cursor = 'move';
  dragBar.textContent = 'One Pass';

  const closeBtn = document.createElement('button');
  closeBtn.type = 'button';
  closeBtn.textContent = 'X';
  closeBtn.style.border = '0';
  closeBtn.style.background = 'transparent';
  closeBtn.style.color = '#fff';
  closeBtn.style.fontSize = '13px';
  closeBtn.style.cursor = 'pointer';
  closeBtn.style.padding = '0';
  closeBtn.style.marginLeft = '10px';
  closeBtn.style.minWidth = '20px';

  closeBtn.addEventListener('click', () => {
    host.remove();
  });

  const iframe = document.createElement('iframe');
  iframe.src = chrome.runtime.getURL('popup.html');
  iframe.style.width = '100%';
  iframe.style.height = 'calc(100% - 36px)';
  iframe.style.border = '0';
  iframe.style.display = 'block';

  dragBar.appendChild(closeBtn);
  host.appendChild(dragBar);
  host.appendChild(iframe);
  document.documentElement.appendChild(host);

  let dragging = false;
  let offsetX = 0;
  let offsetY = 0;

  dragBar.addEventListener('mousedown', (event) => {
    dragging = true;
    const rect = host.getBoundingClientRect();
    offsetX = event.clientX - rect.left;
    offsetY = event.clientY - rect.top;
    event.preventDefault();
  });

  document.addEventListener('mousemove', (event) => {
    if (!dragging) {
      return;
    }

    const maxLeft = window.innerWidth - host.offsetWidth;
    const maxTop = window.innerHeight - host.offsetHeight;

    const nextLeft = Math.min(Math.max(event.clientX - offsetX, 0), Math.max(maxLeft, 0));
    const nextTop = Math.min(Math.max(event.clientY - offsetY, 0), Math.max(maxTop, 0));

    host.style.left = `${nextLeft}px`;
    host.style.top = `${nextTop}px`;
    host.style.right = 'auto';
  });

  document.addEventListener('mouseup', () => {
    dragging = false;
  });
})();
