// Profile content script. Runs on linkedin.com/in/*.
// Manifest concatenates extractors.js + this file, so MaxyLinkedinExtractors
// is in scope. One click → scrape → post to the service worker → pill state.

;(function () {
  const TAG_MOUNT = '[linkedin-ext-mount]'
  const TAG_SCRAPE = '[linkedin-ext-scrape]'
  const TAG_ERROR = '[linkedin-ext-error]'
  const PILL_ID = 'maxy-linkedin-pill'

  function setState(pill, state, label) {
    pill.dataset.state = state
    if (label) pill.textContent = label
  }

  async function onClick(pill) {
    const dispatchId = crypto.randomUUID()
    setState(pill, 'busy', 'Capturing…')

    const result = globalThis.MaxyLinkedinExtractors.extractProfile(document)
    if (!result.ok) {
      console.error(TAG_SCRAPE + ' page=profile ok=false missing=' + result.missing.join(','))
      setState(pill, 'error', 'Missing: ' + result.missing.join(', '))
      return
    }
    console.log(TAG_SCRAPE + ' page=profile ok=true fields=' + Object.keys(result.payload).join(','))

    const envelope = {
      source: 'linkedin',
      kind: 'profile',
      capturedAt: new Date().toISOString(),
      pageUrl: location.href.split('?')[0].split('#')[0],
      dispatchId: dispatchId,
      profile: result.payload,
    }

    let reply
    try {
      reply = await chrome.runtime.sendMessage({ type: 'linkedin-ingest', envelope: envelope })
    } catch (err) {
      console.error(TAG_ERROR + ' reason=network detail=' + (err && err.message ? err.message : String(err)))
      setState(pill, 'error', 'Capture failed')
      return
    }

    if (!reply || !reply.ok) {
      const reason = (reply && reply.reason) || 'network'
      const detail = (reply && reply.detail) || ''
      console.error(TAG_ERROR + ' reason=' + reason + ' detail=' + detail)
      if (reason === 'auth') {
        setState(pill, 'auth', 'Sign in to Maxy')
        pill.onclick = function () { chrome.runtime.openOptionsPage() }
        return
      }
      setState(pill, 'error', 'Capture failed')
      return
    }

    setState(pill, 'ok', 'Captured ✓')
  }

  function mount() {
    if (document.getElementById(PILL_ID)) return
    const anchor = document.querySelector('section.top-card-layout, main') || document.body
    if (!anchor) return
    const pill = document.createElement('button')
    pill.id = PILL_ID
    pill.className = 'maxy-pill'
    pill.type = 'button'
    pill.textContent = 'Add to Maxy'
    pill.dataset.state = 'idle'
    pill.addEventListener('click', function () { onClick(pill) })
    anchor.prepend(pill)
    console.log(TAG_MOUNT + ' page=profile url=' + location.href)
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', mount, { once: true })
  } else {
    mount()
  }
})()
