const OVERLAY_ID = 'imagelite-overlay-root';

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'getImageInfo') {
    const img = document.elementFromPoint(message.x, message.y);
    if (img && img.tagName === 'IMG') {
      sendResponse({
        src: img.src,
        alt: img.alt || '',
        width: img.naturalWidth,
        height: img.naturalHeight
      });
    } else {
      sendResponse(null);
    }
    return true;
  }

  if (message.action === 'openImageLiteOverlay') {
    openImageLiteOverlay(message.expanded !== false);
    sendResponse({ success: true });
    return true;
  }

  return false;
});

window.addEventListener('message', (event) => {
  if (event.source !== getOverlayIframe()?.contentWindow) return;
  const message = event.data || {};
  if (message.source !== 'imagelite') return;

  if (message.action === 'closeOverlay') {
    closeImageLiteOverlay();
  }
  if (message.action === 'setOverlayExpanded') {
    setOverlayExpanded(!!message.expanded);
  }
});

function getOverlayRoot() {
  return document.getElementById(OVERLAY_ID);
}

function getOverlayIframe() {
  return getOverlayRoot()?.querySelector('iframe') || null;
}

function openImageLiteOverlay(expanded) {
  let root = getOverlayRoot();
  if (!root) {
    root = document.createElement('div');
    root.id = OVERLAY_ID;
    root.attachShadow({ mode: 'open' });
    document.documentElement.appendChild(root);
    renderOverlay(root);
  }

  setOverlayExpanded(expanded);
  root.style.display = 'block';
}

function renderOverlay(root) {
  const iframeUrl = chrome.runtime.getURL('popup.html?overlay=1');
  root.shadowRoot.innerHTML = `
    <style>
      :host {
        all: initial;
      }
      .shell {
        position: fixed;
        right: 18px;
        bottom: 18px;
        z-index: 2147483647;
        width: min(420px, calc(100vw - 24px));
        height: min(620px, calc(100vh - 24px));
        border: 1px solid rgba(124, 92, 252, .26);
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 28px 90px rgba(0, 0, 0, .36);
        background: #08080f;
        transition: width .34s cubic-bezier(.22,1,.36,1), height .34s cubic-bezier(.22,1,.36,1), right .34s cubic-bezier(.22,1,.36,1), bottom .34s cubic-bezier(.22,1,.36,1), border-radius .34s ease;
      }
      .shell.is-expanded {
        right: max(18px, calc((100vw - min(960px, calc(100vw - 32px))) / 2));
        bottom: max(18px, calc((100vh - min(780px, calc(100vh - 32px))) / 2));
        width: min(960px, calc(100vw - 32px));
        height: min(780px, calc(100vh - 32px));
        border-radius: 18px;
      }
      iframe {
        width: 100%;
        height: 100%;
        border: 0;
        display: block;
        background: transparent;
      }
      @media (max-width: 640px) {
        .shell,
        .shell.is-expanded {
          inset: 8px;
          width: auto;
          height: auto;
          border-radius: 14px;
        }
      }
    </style>
    <div class="shell">
      <iframe src="${iframeUrl}" title="ImageLite"></iframe>
    </div>
  `;
}

function setOverlayExpanded(expanded) {
  getOverlayRoot()?.shadowRoot?.querySelector('.shell')?.classList.toggle('is-expanded', expanded);
  getOverlayIframe()?.contentWindow?.postMessage({
    source: 'imagelite-host',
    action: 'overlayExpandedChanged',
    expanded
  }, '*');
}

function closeImageLiteOverlay() {
  const root = getOverlayRoot();
  if (root) root.remove();
}
