/**
 * Reels discovery (competitor borrow #1). The user browses instagram.com/reels/ in a
 * headed window; an injected overlay lists the authors of reels they scroll past that
 * are NOT yet monitored, each with a one-click 추가 button. Human-in-the-loop — nothing
 * is auto-added. Mirrors the competitor's profile_collector.py (expose_function bridge).
 */

// IG paths that are not user profiles — a '/foo/' link to any of these is not an account.
const RESERVED = new Set([
  'reels', 'reel', 'explore', 'p', 'stories', 'story', 'direct', 'accounts', 'about',
  'legal', 'privacy', 'api', 'graphql', 'ajax', 's', 'tv', 'igtv', 'challenge', 'emails',
  'session', 'web', 'settings', 'archive', 'saved', 'locations', 'hashtag', 'explore',
  'your_activity', 'notifications', 'developer', 'help', 'press',
]);

/**
 * Extract a username from a same-origin IG link path like '/tem.duck/' or '/tem.duck'.
 * Returns null for reserved paths, deep paths (/user/reels/), or non-username shapes.
 * Pure — unit-tested; the injected overlay reimplements the same rule in-page.
 */
export function usernameFromHref(href: string): string | null {
  const m = /^\/([A-Za-z0-9._]+)\/?$/.exec(href);
  if (!m) return null;
  const u = m[1]!;
  if (u.length < 1 || u.length > 30) return null;
  if (RESERVED.has(u.toLowerCase())) return null;
  return u;
}

// Injected at document start on the reels page. Scans for profile links as the user
// scrolls, asks the app whether each is already monitored (window.__imCheckExists),
// and renders a floating panel of NEW authors with 추가 buttons (window.__imAddAccount).
// Both globals are provided by page.exposeBinding() from the collector.
export const DISCOVERY_OVERLAY_SCRIPT = `
(() => {
  if (window.__imDiscoveryInit) return;
  window.__imDiscoveryInit = true;

  const RESERVED = new Set(${JSON.stringify([...RESERVED])});
  function userFromHref(href) {
    const m = /^\\/([A-Za-z0-9._]+)\\/?$/.exec(href || '');
    if (!m) return null;
    const u = m[1];
    if (u.length < 1 || u.length > 30) return null;
    if (RESERVED.has(u.toLowerCase())) return null;
    return u;
  }

  const seen = new Set();     // usernames already processed
  const panel = document.createElement('div');
  panel.id = '__im-discovery';
  panel.style.cssText = 'position:fixed;top:16px;right:16px;width:280px;max-height:80vh;overflow:auto;z-index:2147483647;background:#111319;color:#eef0f6;border:1px solid #2a2f3a;border-radius:14px;padding:12px;font:13px -apple-system,BlinkMacSystemFont,"Malgun Gothic",sans-serif;box-shadow:0 8px 30px rgba(0,0,0,.5)';
  panel.innerHTML = '<div style="font-weight:800;font-size:14px;margin-bottom:8px">🔍 발견된 신규 계정 <span id="__im-count" style="color:#7db2ff">0</span></div><div style="font-size:11.5px;color:#9aa3b2;margin-bottom:8px">릴스를 스크롤하면 아직 등록 안 된 계정이 여기 쌓여요. [추가]로 모니터링에 넣으세요.</div><div id="__im-list"></div>';
  const attach = () => { if (document.body && !document.getElementById('__im-discovery')) document.body.appendChild(panel); };
  attach();

  const list = () => document.getElementById('__im-list');
  const countEl = () => document.getElementById('__im-count');
  let added = 0, found = 0;

  function row(u) {
    const el = document.createElement('div');
    el.style.cssText = 'display:flex;align-items:center;gap:8px;padding:7px 0;border-top:1px solid #23262f';
    el.innerHTML = '<span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:700">@' + u + '</span>';
    const btn = document.createElement('button');
    btn.textContent = '추가';
    btn.style.cssText = 'flex:none;background:#6D4AFF;color:#fff;border:none;border-radius:7px;padding:5px 12px;font-weight:700;cursor:pointer';
    btn.onclick = async () => {
      btn.disabled = true; btn.textContent = '추가 중…';
      try { await window.__imAddAccount(u); btn.textContent = '✓ 추가됨'; btn.style.background = '#0e9f52'; added++; }
      catch (e) { btn.textContent = '실패'; btn.style.background = '#d1435b'; btn.disabled = false; }
    };
    el.appendChild(btn);
    list().appendChild(el);
    found++; countEl().textContent = String(found);
  }

  async function scan() {
    attach();
    const anchors = document.querySelectorAll('a[href^="/"]');
    const candidates = new Set();
    anchors.forEach((a) => {
      const u = userFromHref(a.getAttribute('href'));
      if (u) candidates.add(u);
    });
    for (const u of candidates) {
      if (seen.has(u)) continue;
      seen.add(u);
      try { if (await window.__imCheckExists(u)) continue; } catch (e) { continue; }
      row(u);
    }
  }
  setInterval(scan, 1500);
  scan();
})();
`;
