// Injected fresh into the surfed page on every hit (background.js calls
// chrome.scripting.executeScript with this file as the target) — builds two
// small overlay pieces instead of one big bar, so the surfed page itself
// stays as visible as possible: a slim full-width strip pinned to the top
// (just the Pause/Skip controls + the countdown progress bar) and a
// separate 728x90 banner box pinned to the bottom-right corner, mirroring
// public/assets/js/surf.js's own progress-bar visual language without
// reproducing its full-width toolbar footprint. The outer host spans the
// whole viewport with pointer-events:none so everything OUTSIDE these two
// pieces stays fully click-through to the real page underneath; only the
// two pieces themselves re-enable pointer-events. Uses a shadow root so
// neither the host page's CSS can distort our overlay, nor our styles leak
// onto the host page.
(() => {
  const EXISTING = document.getElementById('__cortaly_surfbar_overlay_host');
  if (EXISTING) EXISTING.remove(); // defensive — a stale overlay from a previous hit on the same document, if any
  const EXISTING_SPACER = document.getElementById('__cortaly_surfbar_spacer');
  if (EXISTING_SPACER) EXISTING_SPACER.remove();

  const host = document.createElement('div');
  host.id = '__cortaly_surfbar_overlay_host';
  host.style.cssText = 'all:initial;position:fixed;inset:0;z-index:2147483647;pointer-events:none;';
  document.documentElement.appendChild(host);
  const root = host.attachShadow({ mode: 'closed' });

  const style = document.createElement('style');
  style.textContent = `
    .topbar { position:absolute; top:0; left:0; right:0; pointer-events:auto; box-sizing:border-box;
              font-family: -apple-system, system-ui, sans-serif; font-size: 12px; color: #e8e8ea;
              background: #14161c; border-bottom: 1px solid #2a2d38;
              box-shadow: 0 2px 0 rgba(0,0,0,.5), 0 6px 18px rgba(0,0,0,.42); overflow:hidden; }
    .row { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:5px 12px; }
    .stat { text-align:left; }
    .stat .label { display:block; font-size:10px; text-transform:uppercase; letter-spacing:.08em; opacity:.65; }
    .stat .value { display:block; font-weight:700; font-size:12px; }
    .btns { display:flex; gap:6px; flex-shrink:0; }
    button { font: inherit; font-size: 11px; padding:4px 12px; border-radius:6px; border:1px solid #3a3d4a;
             background:#20222c; color:#e8e8ea; cursor:pointer; white-space:nowrap; }
    button:hover { background:#2a2d38; }
    .progress-track { height:3px; background:#1b1f27; overflow:hidden; }
    .progress-bar { height:100%; width:0%; background:linear-gradient(90deg,#f7a81e,#c2f24d); transition:width .2s linear; }

    .corner { position:absolute; bottom:16px; right:16px; pointer-events:auto;
              background:#14161c; border:1px solid #2a2d38; border-radius:10px;
              box-shadow: 0 6px 24px rgba(0,0,0,.4); overflow:hidden; line-height:0; }
    .banner { display:block; width:728px; max-width:calc(100vw - 32px); height:90px; object-fit:contain; background:#0c0d11; }
    .banner-html-frame { width:728px; max-width:calc(100vw - 32px); height:90px; border:0; display:block; background:#0c0d11; }
    .placeholder { box-sizing:border-box; display:flex; align-items:center; justify-content:center;
                   width:728px; max-width:calc(100vw - 32px); height:90px; text-align:center; opacity:.6;
                   font-family: -apple-system, system-ui, sans-serif; font-size:12px; color:#e8e8ea; }
  `;
  root.appendChild(style);

  const topbar = document.createElement('div');
  topbar.className = 'topbar';
  topbar.innerHTML = `
    <div class="row">
      <div class="stat"><span class="label">Cortaly Surfbar</span><span class="value" id="reward">—</span></div>
      <div class="btns">
        <button id="pause-btn">Pause</button>
        <button id="skip-btn">Skip</button>
      </div>
    </div>
    <div class="progress-track"><div class="progress-bar" id="progress-bar"></div></div>
  `;
  root.appendChild(topbar);

  // The topbar is position:absolute inside a position:fixed host, so its
  // mere presence in the DOM doesn't reserve any space in the actual page's
  // own layout — without this, the topbar simply floats on top of whatever
  // the page renders at its own top, hiding it for the whole hit. A plain
  // block spacer inserted as body's first child reserves the same height in
  // normal flow, pushing the page's real content down below the topbar
  // instead of covering it. (The corner banner is deliberately left as a
  // pure floating overlay — that's the explicit product ask for it, unlike
  // the topbar.) Known limitation: a page whose OWN body is itself a flex
  // or grid container would treat this spacer as a layout item rather than
  // simple reserved space — an edge case, not the common page shape.
  const spacer = document.createElement('div');
  spacer.id = '__cortaly_surfbar_spacer';
  spacer.style.cssText = 'all:initial;display:block;width:100%;height:0px;';
  if (document.body) {
    document.body.insertBefore(spacer, document.body.firstChild);
  }
  spacer.style.height = topbar.getBoundingClientRect().height + 'px';

  const corner = document.createElement('div');
  corner.className = 'corner';
  corner.innerHTML = `<div id="banner-slot"></div>`;
  root.appendChild(corner);

  const bannerSlot = corner.querySelector('#banner-slot');
  const rewardEl = topbar.querySelector('#reward');
  const pauseBtn = topbar.querySelector('#pause-btn');
  const skipBtn = topbar.querySelector('#skip-btn');
  const progressBar = topbar.querySelector('#progress-bar');

  let countdownTimer = null;
  let trackedHitId = null;

  function stopCountdown() {
    if (countdownTimer) {
      clearInterval(countdownTimer);
      countdownTimer = null;
    }
  }

  // Mirrors surf.js's startCountdown(): a 250ms wall-clock-driven tick (not
  // requestAnimationFrame, not a tick counter) so it can't drift under tab
  // throttling — each tick recomputes elapsed from Date.now(), it doesn't
  // accumulate. This bar is purely cosmetic; the server-authoritative
  // confirm deadline is background.js's own scheduleConfirm()/setTimeout,
  // completely independent of this loop.
  function startCountdown(startedAt, requiredSeconds) {
    stopCountdown();
    countdownTimer = setInterval(() => {
      const elapsed = (Date.now() - startedAt) / 1000;
      const pct = Math.min(100, (elapsed / requiredSeconds) * 100);
      progressBar.style.width = pct + '%';
      if (elapsed >= requiredSeconds) stopCountdown();
    }, 250);
  }

  function renderBanner(banner) {
    bannerSlot.innerHTML = '';
    if (!banner) {
      const placeholder = document.createElement('div');
      placeholder.className = 'placeholder';
      placeholder.textContent = 'Advertise here — cortaly.com';
      bannerSlot.appendChild(placeholder);
      return;
    }
    if (banner.html_content) {
      // Sandboxed with NO allow-scripts/allow-same-origin — house-ad HTML is
      // admin-authored and trusted on Cortaly's own domain (whose CSP
      // neuters any embedded <script> there), but this overlay renders on
      // an arbitrary third-party page with no such guarantee, so the
      // sandbox itself is what keeps any latent <script> from ever
      // executing here, regardless of the host page's own CSP.
      const iframe = document.createElement('iframe');
      iframe.className = 'banner-html-frame';
      iframe.setAttribute('sandbox', '');
      // The sandboxed iframe is a separate document, so app.css's own
      // "force ad markup to fill the slot" !important rules (which only
      // reach elements in the SAME document) can't apply here — reproduce
      // the same fill behavior inside the srcdoc's own <style> instead, so
      // ad snippets shipping their own inline width/height (e.g. A-Ads)
      // still fill the full 728x90 slot instead of rendering small.
      iframe.srcdoc = `<!doctype html><html><head><meta charset="utf-8"><style>
        html,body{margin:0;padding:0;width:100%;height:100%;overflow:hidden;background:#0c0d11;}
        body{display:flex;align-items:center;justify-content:center;}
        body>*{width:100% !important;height:100% !important;}
        iframe{width:100% !important;height:100% !important;border:0;}
      </style></head><body>${banner.html_content}</body></html>`;
      bannerSlot.appendChild(iframe);
      return;
    }
    const link = document.createElement('a');
    link.href = banner.click_url;
    link.target = '_blank';
    link.rel = 'noopener noreferrer sponsored';
    link.title = banner.title || '';
    const img = document.createElement('img');
    img.className = 'banner';
    img.src = banner.image_url;
    img.alt = banner.title || '';
    link.appendChild(img);
    bannerSlot.appendChild(link);
  }

  pauseBtn.addEventListener('click', () => {
    api.runtime.sendMessage({ type: 'TOGGLE_PAUSE' });
  });
  skipBtn.addEventListener('click', () => {
    api.runtime.sendMessage({ type: 'SKIP' });
  });

  function applyState(state) {
    if (!state) return;
    if (state.hit) {
      renderBanner(state.hit.banner);
      rewardEl.textContent = `~${state.hit.credits_per_hit} credits`;
    } else {
      // Without this, skipping while paused (which clears state.hit but
      // can't navigate the tab away since the loop is paused) would leave
      // this overlay frozen showing the previous, already-abandoned hit's
      // banner and reward figure until the user resumes.
      renderBanner(null);
      rewardEl.textContent = '—';
    }
    pauseBtn.textContent = state.paused ? 'Resume' : 'Pause';

    const canCountdown = state.running && !state.paused && state.hit && state.startedAt;
    if (canCountdown && state.hit.hit_id !== trackedHitId) {
      // New hit (or the first STATE_UPDATE this injected script has seen) —
      // start a fresh countdown. Computing elapsed from state.startedAt
      // (wall-clock, set by background.js when the hit began) rather than
      // resetting to 0% here means the bar correctly reflects time already
      // spent server-side even though this script is injected ~1.5s after
      // navigation (see background.js's injectOverlay() delay).
      trackedHitId = state.hit.hit_id;
      startCountdown(state.startedAt, state.hit.required_seconds);
    } else if (!canCountdown) {
      // Between hits, paused, or stopped — matches surf.js's own reset
      // points (loadNext()/showResumePrompt() both zero the bar).
      trackedHitId = null;
      stopCountdown();
      progressBar.style.width = '0%';
    }

    if (!state.running) {
      stopCountdown();
      host.remove();
      spacer.remove();
    }
  }

  api.runtime.sendMessage({ type: 'GET_STATE' }).then((res) => {
    if (res && res.ok) applyState(res.state);
  }).catch(() => {});

  api.runtime.onMessage.addListener((message) => {
    if (message.type === 'STATE_UPDATE') applyState(message.state);
  });
})();
