// On-page "Detect tango" pill (content script, all sites).
//
// Unobtrusive companion to the side panel's Detect button: a small coral pill
// appears bottom-right ONLY while audio/video is actually playing on the page
// (Spotify, SoundCloud, blogs with embedded players, YouTube…). Clicking it
// opens the El Eje side panel and asks it to identify what's playing. Dismissible
// per-site. Style-isolated in a shadow root so it never touches the page's CSS.
//
// It does NOT capture audio itself — content scripts can't. It just routes to the
// service worker, which opens the panel; the panel (an extension page) performs
// the gesture-gated tabCapture. Nothing is recorded until the user asks.
(() => {
  if (window.top !== window) return;                 // top frame only (no iframe dupes)

  // Report this page's URL/title to the side panel (so it can confirm/fast-look-up
  // the track for the current page without the "tabs" permission). Registered on
  // ALL top-frame pages, including YouTube, before the pill's site skips below.
  chrome.runtime.onMessage.addListener((msg, _sender, send) => {
    if (msg && msg.type === "elejePageInfo") {
      send({ url: location.href, title: document.title });
      return true;
    }
  });

  if (location.protocol.startsWith("chrome")) return;
  // YouTube has its own El Eje overlay (identifies the track + shows synced lyrics),
  // and it lives bottom-right too — don't double up there.
  if (/(^|\.)youtube\.com$/.test(location.hostname)) return;
  const KEY = "eleje_detect_hidden";
  let host, shadow, pill, visible = false;

  function dismissedForSite() {
    try { return sessionStorage.getItem(KEY) === "1"; } catch { return false; }
  }

  function anyMediaPlaying() {
    const els = document.querySelectorAll("audio, video");
    for (const m of els) {
      if (!m.paused && !m.ended && m.currentTime > 0 && m.readyState > 2 &&
          (m.muted !== true) && (m.volume == null || m.volume > 0)) return true;
    }
    return false;
  }

  function build() {
    host = document.createElement("div");
    host.id = "eleje-detect-host";
    host.style.cssText = "position:fixed;z-index:2147483646;right:16px;bottom:16px;all:initial;";
    shadow = host.attachShadow({ mode: "open" });
    shadow.innerHTML = `
      <style>
        :host { all: initial; }
        .pill {
          display: inline-flex; align-items: center; gap: 8px;
          font: 600 13px/1 -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
          color: #fff; background: #f24257; border: 1px solid #ff5a6e;
          border-radius: 999px; padding: 9px 12px 9px 11px; cursor: pointer;
          box-shadow: 0 4px 14px rgba(0,0,0,.35); user-select: none;
          opacity: 0; transform: translateY(8px); transition: opacity .18s, transform .18s;
        }
        .pill.in { opacity: 1; transform: none; }
        .pill:hover { background: #ff5a6e; }
        svg { display: block; }
        .x { margin-left: 2px; opacity: .8; font-weight: 700; padding: 0 2px; }
        .x:hover { opacity: 1; }
      </style>
      <div class="pill" role="button" title="Identify the tango playing — opens El Eje">
        <svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true">
          <circle cx="8" cy="8" r="4.6" fill="none" stroke="#fff" stroke-width="1.5"/>
          <line x1="8" y1="2.3" x2="8" y2="13.7" stroke="#fff" stroke-width="1.7" stroke-linecap="round"/>
        </svg>
        <span>Detect tango</span>
        <span class="x" title="Hide here">×</span>
      </div>`;
    pill = shadow.querySelector(".pill");
    pill.addEventListener("click", (e) => {
      if (e.target.classList.contains("x")) {
        try { sessionStorage.setItem(KEY, "1"); } catch {}
        hide(); return;
      }
      try { chrome.runtime.sendMessage({ type: "fpOpenPanelDetect" }); } catch {}
    });
    (document.body || document.documentElement).appendChild(host);
  }

  function show() {
    if (visible || dismissedForSite()) return;
    if (!host) build();
    host.style.display = "";
    requestAnimationFrame(() => pill && pill.classList.add("in"));
    visible = true;
  }
  function hide() {
    if (!host) return;
    pill.classList.remove("in");
    host.style.display = "none";
    visible = false;
  }

  // Cheap poll: show while media plays, hide when it stops.
  let misses = 0;
  setInterval(() => {
    if (dismissedForSite()) { hide(); return; }
    if (anyMediaPlaying()) { misses = 0; show(); }
    else if (visible && ++misses >= 3) hide();   // hide after ~6s of no playback
  }, 2000);
})();
