// Injected into the click-campaign target page (background.js's
// injectClickOverlay() calls chrome.scripting.executeScript with this file)
// — a leaner sibling of content-script.js's surf overlay: just a slim
// top bar (reward estimate, countdown, Skip), no corner banner box, since
// there's no separate ad to show here — the page itself IS the thing being
// promoted. Same shadow-root/pointer-events-passthrough approach as the
// surf overlay so the underlying page stays fully usable underneath it.
(() => {
  const EXISTING = document.getElementById('__cortaly_click_overlay_host');
  if (EXISTING) EXISTING.remove();
  const EXISTING_SPACER = document.getElementById('__cortaly_click_overlay_spacer');
  if (EXISTING_SPACER) EXISTING_SPACER.remove();

  const host = document.createElement('div');
  host.id = '__cortaly_click_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; overflow:hidden; }
    .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; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
    .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; }
  `;
  root.appendChild(style);

  const topbar = document.createElement('div');
  topbar.className = 'topbar';
  topbar.innerHTML = `
    <div class="row">
      <div class="stat"><span class="label">Cortaly — Click &amp; Earn</span><span class="value" id="title">—</span></div>
      <div class="stat" style="text-align:right;"><span class="label">Reward</span><span class="value" id="reward">—</span></div>
      <div class="btns">
        <button id="skip-btn">Skip</button>
      </div>
    </div>
    <div class="progress-track"><div class="progress-bar" id="progress-bar"></div></div>
  `;
  root.appendChild(topbar);

  // Same reserved-space reasoning as content-script.js's own spacer — see
  // that file's comment.
  const spacer = document.createElement('div');
  spacer.id = '__cortaly_click_overlay_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 titleEl = topbar.querySelector('#title');
  const rewardEl = topbar.querySelector('#reward');
  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;
    }
  }

  // Same wall-clock-driven (not tick-counted) 250ms loop as content-script.js
  // — purely cosmetic, the real confirm deadline is background.js's own
  // scheduleClickConfirm()/setTimeout.
  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);
  }

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

  function applyState(state) {
    if (!state || !state.hit) {
      // Confirmed, skipped, or expired — nothing left to track on this page.
      stopCountdown();
      host.remove();
      spacer.remove();
      return;
    }
    titleEl.textContent = state.hit.campaign ? state.hit.campaign.title : '—';
    rewardEl.textContent = state.hit.estimated_reward != null ? `~${state.hit.estimated_reward} credits` : '—';

    if (state.hit.hit_id !== trackedHitId && state.startedAt) {
      trackedHitId = state.hit.hit_id;
      startCountdown(state.startedAt, state.hit.required_seconds);
    }
  }

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

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