(() => {
  const ext = (typeof chrome !== 'undefined')
    ? chrome
    : (typeof browser !== 'undefined' ? browser : null);
  if (!ext) {
    console.warn('SSForum Overlay: extension API not found.');
    return;
  }
  if (window.__miniForumInjected) return;
  window.__miniForumInjected = true;

  const host = document.createElement('div');
  const shadow = host.attachShadow({ mode: 'open' });

  const style = document.createElement('style');
  style.textContent = `
    .mf-btn {
      position: fixed;
      right: 16px;
      bottom: 16px;
      z-index: 2147483647;
      background: linear-gradient(135deg, #111827, #1f2937);
      color: #fff;
      border: 1px solid rgba(255,255,255,0.12);
      border-radius: 999px;
      padding: 10px 14px;
      font: 600 14px/1.2 "Arial", sans-serif;
      letter-spacing: 0.2px;
      cursor: pointer;
      box-shadow: 0 8px 24px rgba(0,0,0,0.2);
      transition: transform 200ms ease, box-shadow 200ms ease, background 200ms ease;
      animation: mf-float 4s ease-in-out infinite;
      isolation: isolate;
    }
    .mf-btn::before {
      content: "";
      position: absolute;
      inset: -6px;
      border-radius: inherit;
      background: conic-gradient(from 0deg, #22d3ee, #a78bfa, #f59e0b, #22d3ee);
      filter: blur(10px);
      opacity: 0.35;
      z-index: -1;
      animation: mf-spin 6s linear infinite;
    }
    .mf-btn::after {
      content: "";
      position: absolute;
      inset: 0;
      border-radius: inherit;
      background: radial-gradient(120px 60px at -10% -30%, rgba(255,255,255,0.35), transparent 60%);
      opacity: 0.9;
      transition: opacity 200ms ease;
    }
    .mf-btn:hover {
      transform: translateY(-2px) scale(1.03);
      box-shadow: 0 12px 30px rgba(0,0,0,0.28);
    }
    .mf-btn:active {
      transform: translateY(0) scale(0.98);
    }
    .mf-btn.is-open {
      background: linear-gradient(135deg, #0f766e, #10b981);
      box-shadow: 0 12px 30px rgba(16,185,129,0.35);
    }
    .mf-btn.is-open::after {
      opacity: 0.45;
    }
    @keyframes mf-float {
      0%, 100% { transform: translateY(0); }
      50% { transform: translateY(-3px); }
    }
    @keyframes mf-spin {
      to { transform: rotate(360deg); }
    }
    @media (prefers-reduced-motion: reduce) {
      .mf-btn { animation: none; }
      .mf-btn::before { animation: none; }
    }
    .mf-overlay {
      position: fixed;
      right: 16px;
      bottom: 70px;
      width: 380px;
      height: 600px;
      z-index: 2147483647;
      background: transparent;
      border: none;
      display: none;
    }
    .mf-frame {
      width: 100%;
      height: 100%;
      border: none;
      border-radius: 12px;
      box-shadow: 0 12px 32px rgba(0,0,0,0.25);
      overflow: hidden;
      background: #fff;
    }
    .mf-close {
      position: fixed;
      right: 22px;
      bottom: 678px;
      z-index: 2147483647;
      display: none;
      background: #ef4444;
      color: #fff;
      border: none;
      border-radius: 999px;
      width: 28px;
      height: 28px;
      cursor: pointer;
      font: 700 16px/1 "Arial", sans-serif;
    }
    @media (max-height: 700px) {
      .mf-overlay { height: 480px; }
      .mf-close { bottom: 558px; }
    }
  `;

  const button = document.createElement('button');
  button.className = 'mf-btn';
  button.textContent = 'SSForum';
  button.setAttribute('aria-expanded', 'false');
  try {
    const v = ext.runtime && typeof ext.runtime.getManifest === 'function'
      ? (ext.runtime.getManifest().version || '')
      : '';
    if (v) {
      button.title = 'SSForum v' + v;
    }
  } catch {
    // ignore
  }

  const overlay = document.createElement('div');
  overlay.className = 'mf-overlay';

  const closeBtn = document.createElement('button');
  closeBtn.className = 'mf-close';
  closeBtn.textContent = '×';

  function normalizeDomain(domain) {
    let d = (domain || '').toLowerCase().trim();
    if (d.startsWith('www.')) d = d.slice(4);
    return d;
  }

  const iframe = document.createElement('iframe');
  iframe.className = 'mf-frame';
  const domain = normalizeDomain(window.location.hostname);
  const panelUrl = ext.runtime.getURL('panel.html') + '?domain=' + encodeURIComponent(domain);
  iframe.src = panelUrl;
  iframe.setAttribute('allow', 'fullscreen; autoplay; encrypted-media; picture-in-picture');

  overlay.appendChild(iframe);
  shadow.appendChild(style);
  shadow.appendChild(button);
  shadow.appendChild(overlay);
  shadow.appendChild(closeBtn);

  document.documentElement.appendChild(host);

  function applyPosition(pos) {
    const positions = {
      br: {
        btn: { right: '16px', left: 'auto', bottom: '16px', top: 'auto' },
        ov:  { right: '16px', left: 'auto', bottom: '70px', top: 'auto' },
        close: { right: '22px', left: 'auto', bottom: '678px', top: 'auto' },
        closeSmall: { bottom: '558px', top: 'auto' }
      },
      bl: {
        btn: { right: 'auto', left: '16px', bottom: '16px', top: 'auto' },
        ov:  { right: 'auto', left: '16px', bottom: '70px', top: 'auto' },
        close: { right: 'auto', left: '22px', bottom: '678px', top: 'auto' },
        closeSmall: { bottom: '558px', top: 'auto' }
      },
      tr: {
        btn: { right: '16px', left: 'auto', bottom: 'auto', top: '16px' },
        ov:  { right: '16px', left: 'auto', bottom: 'auto', top: '70px' },
        close: { right: '22px', left: 'auto', bottom: 'auto', top: '48px' },
        closeSmall: { bottom: 'auto', top: '48px' }
      },
      tl: {
        btn: { right: 'auto', left: '16px', bottom: 'auto', top: '16px' },
        ov:  { right: 'auto', left: '16px', bottom: 'auto', top: '70px' },
        close: { right: 'auto', left: '22px', bottom: 'auto', top: '48px' },
        closeSmall: { bottom: 'auto', top: '48px' }
      }
    };
    const p = positions[pos] || positions.br;
    Object.assign(button.style, p.btn);
    Object.assign(overlay.style, p.ov);
    Object.assign(closeBtn.style, p.close);

    // adjust close for small height
    const mq = window.matchMedia('(max-height: 700px)');
    if (mq.matches) {
      closeBtn.style.bottom = p.closeSmall.bottom || 'auto';
      closeBtn.style.top = p.closeSmall.top || 'auto';
    }
  }

  ext.storage.local.get(['widgetPosition'], (res) => {
    applyPosition(res.widgetPosition || 'br');
  });

  ext.storage.onChanged.addListener((changes, area) => {
    if (area !== 'local') return;
    if (changes.widgetPosition) {
      applyPosition(changes.widgetPosition.newValue || 'br');
    }
  });

  function openPanel() {
    overlay.style.display = 'block';
    closeBtn.style.display = 'block';
    button.classList.add('is-open');
    button.setAttribute('aria-expanded', 'true');
  }

  function closePanel() {
    overlay.style.display = 'none';
    closeBtn.style.display = 'none';
    button.classList.remove('is-open');
    button.setAttribute('aria-expanded', 'false');
  }

  button.addEventListener('click', () => {
    if (overlay.style.display === 'block') {
      closePanel();
    } else {
      openPanel();
    }
  });

  closeBtn.addEventListener('click', () => closePanel());
})();
