// content.js  (plain content script, no imports)
// Reads the LinkedIn profile the rep is ALREADY viewing. Passive only: it reads
// on-screen text, never navigates, never background-fetches other pages. This
// keeps us out of LinkedIn's scraping-abuse territory and protects the user's
// account. Triggered only by a message from our own popup. Returns DATA only.

(function () {
  'use strict';

  // Best-effort, conservative expansion of the About section's "see more" so we
  // capture the full bio. We ONLY click an inline see-more inside the about
  // region, wrapped in try/catch, and never anything that could navigate.
  function tryExpandAbout() {
    try {
      const about = findSectionByHeading(['about']);
      if (!about) return;
      const btns = about.querySelectorAll('button');
      for (const b of btns) {
        const label = ((b.getAttribute('aria-label') || '') + ' ' + (b.textContent || '')).toLowerCase();
        if (label.includes('see more') || label.includes('…more') || label.includes('...more')) {
          b.click();
          break;
        }
      }
    } catch (e) { /* never let expansion break extraction */ }
  }

  // Find a <section> in main whose first heading text starts with one of the
  // given words. Keys off VISIBLE heading text (stable across LinkedIn's
  // frequently changing class names), not CSS classes.
  function findSectionByHeading(words) {
    const main = document.querySelector('main') || document.body;
    const sections = main.querySelectorAll('section');
    for (const sec of sections) {
      const h = sec.querySelector('h2, h3');
      if (!h) continue;
      const title = (h.textContent || '').trim().toLowerCase().split('\n')[0];
      if (words.some(w => title.startsWith(w))) return sec;
    }
    return null;
  }

  function sectionText(words) {
    const sec = findSectionByHeading(words);
    if (!sec) return '';
    // innerText keeps human-visible text and drops hidden DOM noise.
    return clean(sec.innerText || '');
  }

  function clean(t) {
    return String(t || '')
      .replace(/\u00a0/g, ' ')
      .replace(/[ \t]+\n/g, '\n')
      .replace(/\n{3,}/g, '\n\n')
      .replace(/\s+see more$/gim, '')
      .replace(/\s+…see more/gi, '')
      .trim();
  }

  function readProfile() {
    tryExpandAbout();

    const main = document.querySelector('main') || document.body;

    // Name: the profile H1.
    let name = '';
    const h1 = main.querySelector('h1');
    if (h1) name = clean(h1.textContent).slice(0, 120);

    // Headline + location live in the intro/top card, just after the H1. We
    // grab a bounded slice of the top of main as "topcard" context and let the
    // model pull headline/location from it.
    const topcard = clean(main.innerText || '').slice(0, 600);

    const about = sectionText(['about']).slice(0, 2500);
    const experience = sectionText(['experience']).slice(0, 4000);
    const education = sectionText(['education']).slice(0, 1500);
    const skills = sectionText(['skills', 'licenses']).slice(0, 1200);
    const activity = sectionText(['activity', 'posts']).slice(0, 2000);

    // Current company: the first company link in the experience section, if any.
    let currentCompany = '';
    const expSec = findSectionByHeading(['experience']);
    if (expSec) {
      const link = expSec.querySelector('a[href*="/company/"]');
      if (link) currentCompany = clean(link.textContent).slice(0, 120);
    }

    // Full visible text as a safety net if section detection misses anything.
    const fullText = clean(main.innerText || '').slice(0, 12000);

    return {
      success: true,
      name,
      topcard,
      about,
      experience,
      education,
      skills,
      activity,
      currentCompany,
      fullText,
      url: location.href.split('?')[0]
    };
  }

  chrome.runtime.onMessage.addListener((req, sender, sendResponse) => {
    if (!req || req.type !== 'JIVUS_READ_PROFILE') return false;
    try {
      sendResponse(readProfile());
    } catch (e) {
      sendResponse({ success: false, error: 'read_failed' });
    }
    return true;
  });
})();
